content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def autoclean_cv(training_dataframe, testing_dataframe, drop_nans=False, copy=False,
encoder=None, encoder_kwargs=None, ignore_update_check=False):
"""Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function... | 37b8221193c05db97dde355e06313a9372cd8193 | 3,659,500 |
import asyncio
def make_coroutine_from_tree(tree, filename="<aexec>", symbol="single",
local={}):
"""Make a coroutine from a tree structure."""
dct = {}
tree.body[0].args.args = list(map(make_arg, local))
exec(compile(tree, filename, symbol), dct)
return asyncio.corout... | cbf4e0b0278abc0e929f4ed8b2a9c421b4e8f3c6 | 3,659,501 |
def update_Sigmai(Yi, Es, Vars):
"""
Return new Sigma_i: shape k
"""
return np.mean((Yi - Es) ** 2, axis=1) + np.mean(Vars, axis=1) | f2cb1fa7f5e6b48f033207ee6bb84b8e865c863c | 3,659,502 |
def gather_indexes(sequence_tensor, positions):
"""Gathers the vectors at the specific positions over a minibatch."""
sequence_shape = get_shape_list(sequence_tensor, expected_rank=3)
batch_size = sequence_shape[0]
seq_length = sequence_shape[1]
width = sequence_shape[2]
flat_offsets = tf.resha... | 583ed7ce925ace45dd2a6c9a78efd0360bd141e0 | 3,659,503 |
import typing
def check_sub_schema_dict(sub_schema: typing.Any) -> dict:
"""Check that a sub schema in an allOf is a dict."""
if not isinstance(sub_schema, dict):
raise exceptions.MalformedSchemaError(
"The elements of allOf must be dictionaries."
)
return sub_schema | b64313b28ab63b8342de7b0422cc8c9087a28462 | 3,659,504 |
def get_proto_root(workspace_root):
"""Gets the root protobuf directory.
Args:
workspace_root: context.label.workspace_root
Returns:
The directory relative to which generated include paths should be.
"""
if workspace_root:
return "/{}".format(workspace_root)
else:
r... | 35cff0b28ee6c1893e5dba93593126c996ba72cc | 3,659,505 |
def bwimcp(J, K, x, tr=.2, alpha=.05):
"""
Multiple comparisons for interactions
in a split-plot design.
The analysis is done by taking difference scores
among all pairs of dependent groups and
determining which of
these differences differ across levels of Factor A
using trimmed means. ... | 82d2b77464e5bc37fc101624ed0d88205ab11ff9 | 3,659,506 |
def trigger_decoder(mode: str, trigger_path: str=None) -> tuple:
"""Trigger Decoder.
Given a mode of operation (calibration, copy phrase, etc) and
a path to the trigger location (*.txt file), this function
will split into symbols (A, ..., Z), timing info (32.222), and
targetness (target... | e4d19203e655173f638dc38c0123f88c7342aed1 | 3,659,507 |
def method_comparison(filename=None, extension="png", usetex=False,
passed_ax=None, **kwargs):
"""
Create a plot comparing how estimated redshift changes as a
function of dispersion measure for each DM-z relation.
Parameters
----------
filename: string or None, optional
... | 8c3714cca3aac5f0f7893dc981b68265bf6cea9f | 3,659,508 |
def logCompression(pilImg):
"""Does log compression processing on a photo
Args:
pilImg (PIL Image format image): Image to be processed
"""
npImg = PILtoNumpy(pilImg)
c = 255 / (np.log10(1 + np.amax(npImg)))
for all_pixels in np.nditer(npImg, op_flags=['readwrite']):
all_pixels[.... | d6ab559182e7c836823d4c51fb6af395c1cd875f | 3,659,509 |
def quantile_turnover(quantile_factor, quantile, period=1):
"""
Computes the proportion of names in a factor quantile that were
not in that quantile in the previous period.
Parameters
----------
quantile_factor : pd.Series
DataFrame with date, asset and factor quantile.
quantile : i... | 6c7b2afdd4c4f0a2dbf38064d2d8664a25370ca2 | 3,659,510 |
def dmp_div(f, g, u, K):
"""
Polynomial division with remainder in ``K[X]``.
Examples
========
>>> from sympy.polys import ring, ZZ, QQ
>>> R, x,y = ring("x,y", ZZ)
>>> R.dmp_div(x**2 + x*y, 2*x + 2)
(0, x**2 + x*y)
>>> R, x,y = ring("x,y", QQ)
>>> R.dmp_div(x**2 + x*y, 2*x +... | 1b8f2b2b9d57899862234233a70e7e76100b86be | 3,659,511 |
def is_designated_holiday(timestamp):
"""
Returns True if the date is one of Piedmont’s "designated holidays":
- New Years Day (January 1st)
- Memorial Day (last Monday of May)
- Independence Day (July 4th)
- Labor Day (First Monday of September)
- Thanksgiving Day (4th Thursday in November)... | e6137ac2c3258a3e51294ff432971c04f56137ec | 3,659,512 |
def check(val, desc=None, as_warn=False) -> SimpleAssertions:
"""
function based assertion call
:param val: val to check
:param desc: optional, description of val
:param as_warn: if set, convert assertion error to warning message
:return: assertionClass
"""
return SimpleAssertions(as_wa... | 2115a0b16387cea0fef483a26a6c27daaf72387e | 3,659,513 |
def ChangeExtension(filename, newExtension):
"""ChangeExtension(filename, newExtension) -> str
Replaces the extension of the filename with the given one.
If the given filename has no extension, the new extension is
simply appended.
arguments:
filename
string correspondi... | 0909060e01226520280aeabde906ab9a8f0dfc5d | 3,659,514 |
def file_based_input_fn_builder(input_file,
seq_length,
is_training,
drop_remainder):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"input_ids": tf.FixedLenFeature([se... | 733ddf8b7add0cf9c610537cab0c31172260f0de | 3,659,515 |
def synchrotron_thin_spectrum(freqs, ne, te, bfield):
"""Optically thin (unobsorbed) synchrotron spectrum.
Units of erg/cm^3/s/Hz
NY95b Eq 3.9
"""
const = 4.43e-30 # erg/cm^3/s/Hz
theta_e = K_BLTZ * te / (MELC * SPLC * SPLC)
v0 = QELC * bfield / (2*np.pi*MELC*SPLC)
xm = 2*freqs/(3*v0... | 1334cf0382eecd298472b4717b220a7ac3e96d0e | 3,659,516 |
import os
from pathlib import Path
from re import DEBUG
def extract_val_setup(timestamp, lat, lon, dataPath = "Data/IceData/"):
""" Extracts a timestamped value from a NSIDC GeoTIFF File
Inputs:
timestamp = datetime struct of sample
lat = sample latitude
lon = sample longitude
... | b3af95af7edd50e18bf5a1bf8e760cb0f12fda02 | 3,659,517 |
import base64
def create_message(service, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
... | 6c6df7b1825c13cb8016840527b4dd81ac26d266 | 3,659,518 |
def numpy_ndarray(nb_arr):
"""Return a copy of numba DeviceNDArray data as a numpy.ndarray.
"""
return nb_arr.copy_to_host() | d6ee1c62428783344fe6232ef229a6dabc8f2a2f | 3,659,519 |
def convert_to_dict(my_keys, my_values):
"""Merge a given list of keys and a list of values into a dictionary.
Args:
my_keys (list): A list of keys
my_values (list): A list corresponding values
Returns:
Dict: Dictionary of the list of keys mapped to the list of values
"""
... | e00690d27770539e6b9d2166835f6bd1b9c11c5a | 3,659,520 |
def add_vit(request):
"""
Add a new vit with API, currently image and video are not supported
"""
user = KeyBackend().authenticate(request)
if request.method == "POST":
if request.user.is_authenticated:
form = VitForm(request.POST)
if form.is_valid():
... | 726776e036678cb79051d6ac800d5d883b947320 | 3,659,521 |
def long_control_state_trans(active, long_control_state, v_ego, v_target, v_pid,
output_gb, brake_pressed, cruise_standstill, min_speed_can):
"""Update longitudinal control state machine"""
stopping_target_speed = min_speed_can + STOPPING_TARGET_SPEED_OFFSET
stopping_condition = (v_eg... | f13a5db692ce92fe36204eade10ebb2d54b9caed | 3,659,522 |
def load_group_to_namedtuple(group: h5py.Group):
"""Returns namedtuple with name of group and key: values of group attrs
e.g. srs1 group which has gpib: 1... will be returned as an srs1 namedtuple with .gpib etc
"""
# Check it was stored as a namedTuple
if group.attrs.get('description', None) != 'Na... | e33c0e1b367ddd2ebb745397d473c00452ba853f | 3,659,523 |
import json
def export_json(blocks=None, subsections=False):
"""
Returns JSON representation of parsed config structure
:param blocks: List of blocks to export
:param subsections: Export all subblocks
:return: JSON-dumped string
"""
if blocks is not None:
blocks = [_canonicalize_bl... | 90ae2ee10d6d23f091d079bd87478fa10d3a4083 | 3,659,524 |
def get_dummy_message(text):
"""Get a dummy message with a custom text"""
return botogram.objects.messages.Message({
"message_id": 1,
"from": {"id": 123, "first_name": "Nobody"},
"chat": {"id": -123, "type": "chat", "title": "Something"},
"date": 1,
"text": text,
}) | 0f39712381157b46aed345ef6b46c6b3cfe32d95 | 3,659,525 |
import time
def list_ga4_entities(admin_api):
"""Get a dictionary of GA4 entity settings based on type.
Args:
admin_api: The Admin API object.
Returns:
A dictionary of GA4 entity setting lists.
"""
entities = {
'ga4_account_summaries': [],
'ga4_accounts': [],
'ga4_properties': []... | 83b11c1a001a593da07f6aeb4333bad623bb7ee4 | 3,659,526 |
import textwrap
import os
def text_detection_background(text, background=None, hsize=15, vsize=15):
""" Given a string TEXT, generate a picture with text in it
arguments:
TEXT -- a string to be displayed
HSIZE -- maximum number of characters in one line
VSIZE -- maximum number of lines
background -- a ... | d65677588130ffab84df210e772208fbfddba99f | 3,659,527 |
def print_sig(expr):
"""
Arguments:
- `expr`:
"""
return "{0!s} × {1!s}".format(expr.dom, expr.body) | be8d6fb1ad2256e2a825e383859f72db93318864 | 3,659,528 |
def is_grounded_concept(c: Concept) -> bool:
""" Check if a concept is grounded """
return (
"UN" in c.db_refs
and c.db_refs["UN"][0][0].split("/")[1] != "properties"
) | 2447b289cec20efc2aa359f37a795fd231004030 | 3,659,529 |
def _get_form(app, parent_form, factory_method, force_disable_csrf=False):
"""Create and fill a form."""
class AForm(parent_form):
pass
with app.test_request_context():
extra = _update_with_csrf_disabled() if force_disable_csrf else {}
RF = factory_method(AForm)
rf = RF(**... | b109d983dcf123812ede664719ab56f5462e84d4 | 3,659,530 |
def get_root_disk_size():
""" Get size of the root disk """
context = pyudev.Context()
rootfs_node = get_rootfs_node()
size_gib = 0
for device in context.list_devices(DEVTYPE='disk'):
# /dev/nvmeXn1 259 are for NVME devices
major = device['MAJOR']
if (major == '8' or major =... | 4c01e189dfb4460d118fbd9b94c6a07e420c3bb1 | 3,659,531 |
import numpy
def convert_to_premultiplied_png(file):
"""
http://stackoverflow.com/questions/6591361/method-for-converting-pngs-to-premultiplied-alpha
"""
logger.info("converting to premultiplied alpha")
im = Img.open(file).convert('RGBA')
a = numpy.fromstring(im.tobytes(), dtype=numpy.uint8)
... | 2a2ebf9e3d1152e2d143ba799aab0ff0927653a8 | 3,659,532 |
def DSQuery(dstype, objectname, attribute=None):
"""DirectoryServices query.
Args:
dstype: The type of objects to query. user, group.
objectname: the object to query.
attribute: the optional attribute to query.
Returns:
If an attribute is specified, the value of the attribute. Otherwise, the
... | 2dea68b5897a46c90d2f8cf24e42519c272e70f1 | 3,659,533 |
def calculate_offset(lon, first_element_value):
"""
Calculate the number of elements to roll the dataset by in order to have
longitude from within requested bounds.
:param lon: longitude coordinate of xarray dataset.
:param first_element_value: the value of the first element of the longitude array ... | a55eee1dd11b1b052d67ab1abadfc8087c1a2fe0 | 3,659,534 |
def min_mean_col(m: ma.MaskedArray) -> int:
"""Calculate the index of the column with the smallest mean.
"""
if ma.count_masked(m) == m.size:
return -1
col_mean = np.nanmean(m, axis=0)
return np.argmin(col_mean) | 499b7d5db38edc222aac6517d87d9df30285cb37 | 3,659,535 |
import resnet
import sys
import os
import torch
def load_simclrv2(init_args):
"""
Load pretrained SimCLR-v2 model.
"""
ckpt_file = init_args["ckpt_file"]
model_dir = init_args["model_dir"]
# Load the resnet.py that comes with the SimCLR-v2's PyTorch converter
sys.path.insert(
0,
... | 3d5521cf19b2e5c91af8ed4ce55a22e0573445d4 | 3,659,536 |
def minekey_read(request, mk_hmac, mk_fid, mk_fversion, mk_iid, mk_depth, mk_type, mk_ext, **kwargs):
"""
arguments: request, mk_hmac, mk_fid, mk_fversion, mk_iid, mk_depth, mk_type, mk_ext, **kwargs
implements: GET /key/(MK_HMAC)/(MK_FID)/(MK_FVERSION)/(MK_IID)/(MK_DEPTH)/(MK_TYPE).(MK_EXT)
returns: a ... | b80db062c71d43759602410cd75decf5eadf3a71 | 3,659,537 |
import os
def get_file_metadata(folder, video_relative_path):
""" """
# SAMPLE FILENAME: XXCam_01_20180517203949574.mp4
# XXXXX_XX_YYYYMMDDHHMMSSmmm.mp4
# 2019/01/01/XXCam-20180502-1727-34996.mp4
# XXCam-01-20180502-1727-34996.mp4
video_filen... | c8fcc163f1b3fa89206d752181d5f814219fe74a | 3,659,538 |
def test_data_alignment(role_value, should_pass, check_model):
"""Test a custom model which returns a good and alignments from data().
qtmodeltest should capture this problem and fail when that happens.
"""
class MyModel(qt_api.QAbstractListModel):
def rowCount(self, parent=qt_api.QtCore.QModel... | 4ebed3384cf5c694d72235e703b6f9594de5ff7b | 3,659,539 |
def cov(a, b):
"""Return the sample covariance of vectors a and b"""
a = flex.double(a)
b = flex.double(b)
n = len(a)
assert n == len(b)
resid_a = a - flex.mean(a)
resid_b = b - flex.mean(b)
return flex.sum(resid_a*resid_b) / (n - 1) | 94505852671e4652f96daa7b8e61f759aeca1dda | 3,659,540 |
from bs4 import BeautifulSoup
import re
def beautify(soup: BeautifulSoup, rich_terminal: bool = True) -> str:
"""
Cleans up the raw HTML so it's more presentable.
Parse BeautifulSoup HTML and return prettified string
"""
beautifiedText = str()
for i in soup:
if rich_terminal:
... | df79666ad0ec9592e1a24325813b59e2d9711636 | 3,659,541 |
def design_complexity(design: Design) -> int:
"""Returns an approximation of the design's complexity to create."""
diversity = 3 * len(design.required)
abundance = 2 * sum(design.required.values())
return diversity + abundance + design.additional | b5be6336ce037d010bbb274dc6ce5538ac6ecae8 | 3,659,542 |
import torch
def approx_q_y(q_z, mu_lookup, logvar_lookup, k=10):
"""
refer to eq.13 in the paper
"""
q_z_shape = list(q_z.size()) # (b, z_dim)
mu_lookup_shape = [mu_lookup.num_embeddings, mu_lookup.embedding_dim] # (k, z_dim)
logvar_lookup_shape = [logvar_lookup.num_embeddings, logvar_looku... | 4bc9e18f7c260e11f4085c7deea993e375b87124 | 3,659,543 |
def svn_repos_get_logs2(*args):
"""
svn_repos_get_logs2(svn_repos_t repos, apr_array_header_t paths, svn_revnum_t start,
svn_revnum_t end, svn_boolean_t discover_changed_paths,
svn_boolean_t strict_node_history,
svn_repos_authz_func_t authz_read_func,
svn_log_message_receiver_t... | 8580b4df10d6a6ebecbea960e14cd2ca79720beb | 3,659,544 |
def error_function(theta, X, y):
"""Error function J definition"""
diff = np.dot(X, theta) - y
return (1. / 2 * m) * np.dot(np.transpose(diff), diff) | 0762651fe9f33107a4e198e70319f77a5ae50e0b | 3,659,545 |
def register(operation_name):
"""
Registers the decorated class as an Operation with the supplied operation name
:param operation_name: The identifying name for the Operation
"""
def wrapper(clazz):
if operation_name not in OPERATIONS:
OPERATIONS[operation_name] = clazz
... | 036612a64d987ede2546bd5dbc9d848e6ed6c48b | 3,659,546 |
def url_exists(video):
"""
check each source for a url for this video; return True as soon as one is found. If none are found, return False
"""
max_timeout = int(kodi.get_setting('source_timeout'))
logger.log('Checking for Url Existence: |%s|' % (video), log_utils.LOGDEBUG)
for cls in relevant_s... | ee3c507e824255031e90eac92fbc0e3cc54ca788 | 3,659,547 |
import os
def test_actions_explicit_get_collector_action_for_unexisting_terminal():
"""
Test for situation when `get_collector` has an action for un-existing
terminal.
"""
action = get_collector()
@action
def INT(context, value):
return int(value)
@action
def STRING(cont... | 896e4cf91f2c6ce8949974e501c06ac3f9a8745f | 3,659,548 |
def log2_grad(orig, grad):
"""Returns [grad * 1 / (log(2) * x)]"""
x = orig.args[0]
ones = ones_like(x)
two = const(2.0, dtype=x.checked_type.dtype)
return [grad * ones / (log(two) * x)] | c17d7eeee43e64e0eeb7feb86f357374cc2516e4 | 3,659,549 |
import posixpath
import requests
def _stream_annotation(file_name, pn_dir):
"""
Stream an entire remote annotation file from Physionet.
Parameters
----------
file_name : str
The name of the annotation file to be read.
pn_dir : str
The PhysioNet directory where the annotation f... | 8a1168562b87f27cc035d21b7f91cb23a611d0b4 | 3,659,550 |
def get_scenarios():
"""
Return a list scenarios and values for parameters in each of them
:return:
"""
# Recover InteractiveSession
isess = deserialize_isession_and_prepare_db_session()
if isess and isinstance(isess, Response):
return isess
scenarios = get_scenarios_in_state(i... | 2812cab14347f03e208d5c3b6399ffa954dfe843 | 3,659,551 |
def download() -> str:
""" Returns a download of the active files.
:return: the zip files needs to be downloaded.
"""
file_manager = utility.load_file_manager()
response = make_response(file_manager.zip_active_files(
"scrubbed_documents.zip"))
# Disable download caching
response.h... | a507c6fd2281226a0db4f4e9e84d2c4f0e6e9562 | 3,659,552 |
import subprocess
def evaluate_test_arff(model_path, test_arff_path, out_path):
"""
Obtain predictions of test_file using the trained model in model_path
:param output_folder:
:param output_name:
:param model_path:
:param test_file:
"""
# PREDICTIONS FILE HEADERS: INSTANCE, ACTUAL, PRE... | 46f311efe952e63eceb8c93f56c8d53487ed13ae | 3,659,553 |
import pickle
def load_from_pickle_file(filepath):
""" Loads a pickle file into a python variable """
with open(filepath, "rb") as f:
python_obj = pickle.load(f)
return python_obj | 8ad8b947e762590d1be8d6b3ca4b519293692f09 | 3,659,554 |
from aiida.orm import Dict
from aiida_quantumespresso.utils.resources import get_default_options
def generate_inputs_pw(fixture_code, generate_structure, generate_kpoints_mesh, generate_upf_data):
"""Generate default inputs for a `PwCalculation."""
def _generate_inputs_pw():
"""Generate default input... | fbe0a332a011b1909380275b1f70444b2dfb5d17 | 3,659,555 |
def connected_components(edge_index, num_nodes=None):
"""Find the connected components of a given graph.
Args:
edge_index (LongTensor): Edge coordinate matrix.
num_nodes (int, optional): Number of nodes. Defaults to None.
Returns:
LongTensor: Vector assigning each node to i... | cb0b620fbd5577375b2ac79d62194537e61a1204 | 3,659,556 |
import tqdm
def assembly2graph(path=DATA_PATH):
"""Convert assemblies (assembly.json) to graph format"""
"""Return a list of NetworkX graphs"""
graphs = []
input_files = get_input_files(path)
for input_file in tqdm(input_files, desc="Generating Graphs"):
ag = AssemblyGraph(input_file)
... | 46f2ed913c5047d68ee523f1a23382c2036fc1d7 | 3,659,557 |
def _get_default_backing(backing):
"""
_get_default_backing(backing)
Returns the prefered backing store
- if user provides a valid Backing object, use it
- if there is a default_backing object instantiated, use it
- if the user provided a configuration dict, use it to create
a new de... | 60f878ee730bea33b93b88e88dfe29885f6fac85 | 3,659,558 |
def slice(request, response, start, end=None):
"""Send a byte range of the response body
:param start: The starting offset. Follows python semantics including
negative numbers.
:param end: The ending offset, again with python semantics and None
(spelled "null" in a query ... | 450e43afb988736dee991bcf284d5b92e11aec74 | 3,659,559 |
import warnings
def get_ps(sdfits, scan, ifnum=0, intnum=None, plnum=0, fdnum=0, method='vector', avgf_min=256):
"""
Parameters
----------
sdfits :
scan : int
Scan number.
plnum : int
Polarization number.
method : {'vector', 'classic'}, optional
Method... | 8226f4e38ab7fce3c1c7f66c88b275e7c7798d86 | 3,659,560 |
import click
def choiceprompt(variable: Variable) -> Binding:
"""Prompt to choose from several values for the given name."""
if not variable.choices:
raise ValueError("variable with empty choices")
choices = {str(number): value for number, value in enumerate(variable.choices, 1)}
lines = [
... | 78700032f93abaca2227d653d5f199e6dbf3b4ba | 3,659,561 |
import urllib
import certifi
import urllib3
import http
import logging
def GetCLInfo(review_host, change_id, auth_cookie='', include_messages=False,
include_detailed_accounts=False):
"""Get the info of the specified CL by querying the Gerrit API.
Args:
review_host: Base URL to the API endpoint.... | b43f5f47ca957aefaaf0764b61318d87c4a614ec | 3,659,562 |
import base64
import hashlib
def rehash(file_path):
"""Return (hash, size) for a file with path file_path. The hash and size
are used by pip to verify the integrity of the contents of a wheel."""
with open(file_path, 'rb') as file:
contents = file.read()
hash = base64.urlsafe_b64encode(has... | 167449640e8cbf17d36e7221df3490a12381dd8e | 3,659,563 |
import requests
def _magpie_update_services_conflict(conflict_services, services_dict, request_cookies):
# type: (List[Str], ServicesSettings, AnyCookiesType) -> Dict[Str, int]
"""
Resolve conflicting services by name during registration by updating them only if pointing to different URL.
"""
magp... | 71f72680aebd1fd781c5cbd9e77eeba06a64062e | 3,659,564 |
def rtc_runner(rtc):
"""Resolved tool contract runner."""
return run_main(polish_chunks_pickle_file=rtc.task.input_files[0],
sentinel_file=rtc.task.input_files[1],
subreads_file=rtc.task.input_files[2],
output_json_file=rtc.task.output_files[0],
... | c9d5a1c23e5b88c6d7592dde473dc41123616a77 | 3,659,565 |
from typing import Any
import json
def dict_to_json_str(o: Any) -> str:
"""
Converts a python object into json.
"""
json_str = json.dumps(o, cls=EnhancedJSONEncoder, sort_keys=True)
return json_str | 8377cee2e25d5daeefd7a349ede02f7134e052b2 | 3,659,566 |
def paramid_to_paramname(paramid):
"""Turn a parameter id number into a parameter name"""
try:
return param_info[paramid]['n']
except KeyError:
return "UNKNOWN_%s" % str(hex(paramid)) | c5e47c6754448a20d79c33b6b501039b1463108e | 3,659,567 |
def max_dist_comp(G, cc0, cc1):
""" Maximum distance between components
Parameters
----------
G : nx.graph
Graph
cc0 : list
Component 0
cc1 : list
Compoennt 1
Returns
-------
threshold : float
Maximum distance
"""
# Ass... | 5df633ee746d537462b84674dc5adadd6f6f7e53 | 3,659,568 |
def convert_examples_to_features(
examples,
label_list,
max_seq_length,
tokenizer,
cls_token_at_end=False,
cls_token="[CLS]",
cls_token_segment_id=1,
sep_token="[SEP]",
sep_token_extra=False,
pad_on_left=False,
pad_token=0,
pad_token_segment_id=0,
pad_token_label_id=-... | 02e4a731c818e0833152aa8e44d6a49e523ef1fb | 3,659,569 |
def exp(var):
"""
Returns variable representing exp applied to the input variable var
"""
result = Var(np.exp(var.val))
result.parents[var] = var.children[result] = np.exp(var.val)
return result | d2811bbb240da33ce158a8bff5739ace2275da0e | 3,659,570 |
from typing import List
from typing import Any
from typing import Callable
def invalidate_cache(
key: str = None,
keys: List = [],
obj: Any = None,
obj_attr: str = None,
namespace: str = None,
):
"""Invalidates a specific cache key"""
if not namespace:
namespace = HTTPCache.namespa... | 1b200db81db9d1134bbbbb8a09d3b57f5c6623dc | 3,659,571 |
def read_dataset(filename):
"""Reads in the TD events contained in the N-MNIST/N-CALTECH101 dataset file specified by 'filename'"""
# NMIST: 34×34 pixels big
f = open(filename, 'rb')
raw_data = np.fromfile(f, dtype=np.uint8)
f.close()
raw_data = np.uint32(raw_data)
all_y = raw_data[1::5]
... | 74861968e36d3e357ce62f615456aa02eb3bd28b | 3,659,572 |
def prge_annotation():
"""Returns an annotation with protein/gene entities (PRGE) identified.
"""
annotation = {"ents": [{"text": "p53", "label": "PRGE", "start": 0, "end": 0},
{"text": "MK2", "label": "PRGE", "start": 0, "end": 0}],
"text": "p53 and MK2",
... | dda417c1c1a1146482f4a3340741d938714dbf30 | 3,659,573 |
from scipy.spatial import Delaunay
def inner_points_mask(points):
"""Mask array into `points` where ``points[msk]`` are all "inner" points,
i.e. `points` with one level of edge points removed. For 1D, this is simply
points[1:-1,:] (assuming ordered points). For ND, we calculate and remove
the convex h... | d81788fdbe3f19f67719951b319bcdd5e01d4d60 | 3,659,574 |
from typing import Union
import torch
from typing import Tuple
from typing import List
def array2list(X_train: Union[np.ndarray, torch.Tensor],
y_train: Union[np.ndarray, torch.Tensor],
X_test: Union[np.ndarray, torch.Tensor],
y_test: Union[np.ndarray, torch.Tensor],
... | 8b4703b9296a786d24ae97edf142fc917d9a3b07 | 3,659,575 |
def livecoding_redirect_view(request):
"""
livecoding oath2 fetch access token after permission dialog
"""
code = request.GET.get('code')
if code is None:
return HttpResponse("code param is empty/not found")
try:
url = "https://www.livecoding.tv/o/token/"
data = dict(cod... | acf06a996da8b70d982fa670080b48faeb452f60 | 3,659,576 |
from typing import OrderedDict
def sort_dict(value):
"""Sort a dictionary."""
return OrderedDict((key, value[key]) for key in sorted(value)) | 93e03b64d44ab79e8841ba3ee7a3546c1e38d6e4 | 3,659,577 |
def hyb_stor_capacity_rule(mod, prj, prd):
"""
Power capacity of a hybrid project's storage component.
"""
return 0 | 86ed72e48738df66fca945ff8aaf976f0a7d14e0 | 3,659,578 |
def gilr_layer_cpu(X, hidden_size, nonlin=tf.nn.elu,
name='gilr'):
"""
g_t = sigmoid(Ux_t + b)
h_t = g_t h_{t-1} + (1-g_t) f(Vx_t + c)
"""
with vscope(name):
n_dims = X.get_shape()[-1].value
act = fc_layer(X, 2 * hidden_size, nonlin=tf.identity)
gate, impulse =... | fce2d10be0b8ccb5923d1781795d08b562d602bf | 3,659,579 |
from typing import Callable
from typing import Awaitable
from re import A
from typing import Tuple
import asyncio
async def retry(f: Callable[..., Awaitable[A]], schedule: Schedule[Exception, Tuple[OpinionT, float]]):
"""
Run an awaitable computation,
retrying on failures according to a schedule.
"""... | d59367da8ae63a4932948b55c7ffcdcc5c8b3c2d | 3,659,580 |
import torch
import os
def dual_solve_u(v, s, alpha, eps, verbose=False, n_iters=100, gtol=0):
"""
min_{u>=0} max_pi L(pi, u, v)
= E_xy [ u(x)alpha(x) + v(y)beta(y) + Softplus(1/eps)(s-u-v) ],
where u = min{u>=0 : E_y[pi(x,y)] <= alpha(x)}
find exact u s.t. E_y[pi(x,y)] == alpha(x)
... | 867f02897568b84a33f5fe5c5c41795e69b3b08d | 3,659,581 |
import urllib
import json
def activation(formula=None, instrument=None,
flux=None, cdratio=0, fastratio=0,
mass=None, exposure=24, getdata=False):
"""Calculate sample activation using the FRM II activation web services.
``formula``:
the chemical formula, see belo... | 40588f5d5d76625b759f6642205b28aba8b9ceb8 | 3,659,582 |
def wrap_parfor_blocks(parfor, entry_label = None):
"""wrap parfor blocks for analysis/optimization like CFG"""
blocks = parfor.loop_body.copy() # shallow copy is enough
if entry_label == None:
entry_label = min(blocks.keys())
assert entry_label > 0 # we are using 0 for init block here
# ... | 03528c18c9cd1f8d9671d12e0a4fa8668003305b | 3,659,583 |
from typing import Counter
def frequency_of_occurrence(words, specific_words=None):
"""
Returns a list of (instance, count) sorted in total order and then from most to least common
Along with the count/frequency of each of those words as a tuple
If specific_words list is present then SUM of frequencie... | a98670a89e843774bd1237c0d2e518d2cd8fb242 | 3,659,584 |
from typing import Union
def cache_remove_all(
connection: 'Connection', cache: Union[str, int], binary=False,
query_id=None,
) -> 'APIResult':
"""
Removes all entries from cache, notifying listeners and cache writers.
:param connection: connection to Ignite server,
:param cache: name or ID o... | 81e7cdbae9b3a04e205e15275dee2c45caa96d36 | 3,659,585 |
import json
from typing import OrderedDict
import os
import re
def transform_bundle(bundle_uuid, bundle_version, bundle_path, bundle_manifest_path, extractor=None):
"""
This function is used with the ETL interface in dcplib.etl.DSSExtractor.extract.
Given a bundle ID and directory containing its medatata ... | dc42d07ff69a0a6b6f1778064153cd521151da4e | 3,659,586 |
from typing import List
def choices_function() -> List[str]:
"""Choices functions are useful when the choice list is dynamically generated (e.g. from data in a database)"""
return ['a', 'dynamic', 'list', 'goes', 'here'] | 30b4b05435bacc0a42c91a3f0be09a90098a012f | 3,659,587 |
def GetInfraPythonPath(hermetic=True, master_dir=None):
"""Returns (PythonPath): The full working Chrome Infra utility path.
This path is consistent for master, slave, and tool usage. It includes (in
this order):
- Any environment PYTHONPATH overrides.
- If 'master_dir' is supplied, the master's python p... | a43486c68559e42606a3a55444c998640529ef2b | 3,659,588 |
import uuid
def nodeid():
"""nodeid() -> UUID
Generate a new node id
>>> nodeid()
UUID('...')
:returns: node id
:rtype: :class:`uuid.UUID`
"""
return uuid.uuid4() | 88a3ddc335ce2ca07bfc0e2caf8487dc2342e80f | 3,659,589 |
def drop_redundant_cols(movies_df):
"""
Drop the following redundant columns:
1. `release_data_wiki` - after dropping the outlier
2. `revenue` - after using it to fill `box_office` missing values
3. `budget_kaggle` - after using it to fill `budget_wiki` missing values
4. `duration` - after usin... | f4fb2c98eafc4ec9074cbc659510af30c7155b9c | 3,659,590 |
import pickle
import gzip
import collections
import re
import fnmatch
def get_msids_for_add_msids(opt, logger):
"""
Parse MSIDs spec file (opt.add_msids) and return corresponding list of MSIDs.
This implements support for a MSID spec file like::
# MSIDs that match the name or pattern are include... | b7f2a5b9f1452c8f43684223313716253e27848b | 3,659,591 |
def gaussian_similarity(stimulus_representation, i, j, w, c, r):
"""
Function that calculates and returns the gaussian similarity of stimuli i and j (equation 4b in [Noso86]_)
Parameters
----------
stimulus_representation : np.array
The stimuli are given to this function in the form of a n ... | e1436a26d4f028f237e03d40590cb6b7405b3f16 | 3,659,592 |
def windShearVector(u, v, top, bottom, unit=None):
""" calculate the u and v layer difference and return as vector
"""
udiff = layerDiff(u, top, bottom, unit)
vdiff = layerDiff(v, top, bottom, unit)
return makeVector(udiff, vdiff) | fa9fe1869621c04f00004a8a5c01e78d4faa3221 | 3,659,593 |
def withdraw_entry(contest):
"""Withdraws a submitted entry from the contest.
After this step the submitted entry will be seen as a draft.
"""
return _update_sketch(contest, code=None, action="withdraw") | fdedfeb61e0fe3b47918b66ca1f9dfd56450e39c | 3,659,594 |
def _conditional_field(if_, condition, colon, comment, eol, indent, body,
dedent):
"""Formats an `if` construct."""
del indent, dedent # Unused
# The body of an 'if' should be columnized with the surrounding blocks, so
# much like an inline 'bits', its body is treated as an inline list o... | 09c357659d5f78946d74cddc83f3e4c5c9cad0ed | 3,659,595 |
def check_sum_cases(nation='England'):
"""check total data"""
ck=LocalLatest()
fail=False
data=ck.data.get('data')
latest={}
data=clean_cases(data) #repair glitches
#check latest data matches stored data for nation
for i in data:
_code=i['areaCode']
latest[_code... | 5f30d4a856c21c1397e2f1cdd9a0ee03d026b5a2 | 3,659,596 |
def get_module_name() -> str:
"""Gets the name of the module that called a function
Is meant to be used within a function.
:returns: The name of the module that called your function
"""
return getmodulename(stack()[2][1]) | 12541aa8445ebd796657d76d3001523882202ea0 | 3,659,597 |
def hand_points(work_hand):
"""returns the point value of a given hand"""
debug_level = 1
work_points = 0
for card in work_hand:
work_points += card_point_value(card)
return work_points | 996c0f9f1836495d99836eab8ef3a26e7b592be6 | 3,659,598 |
def elements_counter(arr, count=0):
"""递归计算列表包含的元素数
Arguments:
arr {[list]} -- [列表]
Keyword Arguments:
count {int} -- [列表包含的元素数] (default: {0})
Returns:
[int] -- [列表包含的元素数]
"""
if len(arr):
arr.pop(0)
count += 1
return elements_counter(arr, coun... | 80809781fd2d6a7a2fa92a4b7d5713771a07f8eb | 3,659,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.