content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def layer_prepostprocess(previous_value, x, sequence, dropout_rate, norm_type, depth, epsilon, default_name, name=None, ...
f983888739fa04d0c086e276997cec3919cf3e24
3,650,000
def build_norm_layer(cfg, num_channels, postfix=''): """ Build normalization layer Args: Returns: layer (fluid.dygrah.Layer): created norm layer """ assert isinstance(cfg, dict) and 'type' in cfg cfg_ = cfg.copy() layer_type = cfg_.pop('type') if layer_type not in norm_cfg: ...
d29437854587f7aeaac3b97c2e98d70b56369402
3,650,001
import torchvision def get_split_cifar100_tasks(num_tasks, batch_size): """ Returns data loaders for all tasks of split CIFAR-100 :param num_tasks: :param batch_size: :return: """ datasets = {} # convention: tasks starts from 1 not 0 ! # task_id = 1 (i.e., first task) => start_class = 0, end_class = 4 cif...
85c06c07682c74554aa11826431e5fdbd7eb84c8
3,650,002
import re def _find_loose_date(date_string): """Look for four digit numbers in the string. If there's only one, return it.""" if re.search(r'digit', date_string): # Might be something like "digitized 2010", which we want to avoid. return None # find all the (unique) four digit numbers in t...
9e946af42ad28c26bed4b347a04a1fd2a49ea104
3,650,003
import subprocess import time import syslog import sys import select def invoke(command_requested, timeout=DEFAULT_TIMEOUT): """ """ p = subprocess.Popen(command_requested, shell=True, stdin=subprocess.PIPE, stdout=None, stderr=None) p.stdin.close() # since we do not allow invoked processes to listen ...
ef121fea037b39cd5d9b19e782257b0c8e8fad8c
3,650,004
from pathlib import Path import os import shutil import re import zipfile def zip_addon(addon: str, addon_dir: str): """ Zips 'addon' dir or '.py' file to 'addon.zip' if not yet zipped, then moves the archive to 'addon_dir'. :param addon: Absolute or relative path to a directory to zip or a .zip file. :p...
4eb4731fd69dd9dc234640386c39b5494d013877
3,650,005
def set_simulation_data( state_energies, T_array, state1_index, state2_index ): """ Create and set SimulationData objects for a pair of specified states """ # Set default UnitData object default_UnitData = UnitData( kb=kB.value_in_unit(unit.kilojoule_per_mole/unit.kelvin), ...
edff2bd66a359da10f64c175aa125f8749a2064d
3,650,006
def park2_euc(x): """ Comutes the park2 function """ max_val = 5.925698 x1 = x[0] x2 = x[1] x3 = x[2] x4 = x[3] ret = (2.0/3.0) * np.exp(x1 + x2) - x4*np.sin(x3) + x3 return min(ret, max_val)
96448c502867d360010238526791144fdc1e7581
3,650,007
def num_compositions_jit(m, n): """ Numba jit version of `num_compositions`. Return `0` if the outcome exceeds the maximum value of `np.intp`. """ return comb_jit(n+m-1, m-1)
40562a1ee1564e7b2015f5b8e5d2298a18644493
3,650,008
def fake_get_vim_object(arg): """Stubs out the VMwareAPISession's get_vim_object method.""" return fake_vmware_api.FakeVim()
ee7c7b0331f344b1428e48da38d185dc01bf11d9
3,650,009
import os import re def get_version(*file_paths): """Retrieves the version from replicat_documents/__init__.py""" filename = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(filename).read() version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) ...
b94580d378b4e35777f9719fe898fd134aba5170
3,650,010
import json def get_old_ids(title): """ Returns all the old ids of a particular site given the title of the Wikipedia page """ raw_data = json.loads( readInDataFromURL("https://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=json&rvlimit=100000&titles=" + title) ) old_ids = dict() # initial...
9e9bc37ac51d7b3a8491fa41db5867943a170e1e
3,650,011
def max_expectation_under_constraint(f: np.ndarray, q: np.ndarray, c: float, eps: float = 1e-2, display: bool = False) -> np.ndarray: """ Solve the following constrained optimisation problem: max_p E_p[f] s.t. KL(q || p) <= c :param f: an array of ...
88a67ae4eece82c08bc683dc015904f2d307c54f
3,650,012
def payload_to_plain(payload=None): """ Converts the myADS results into the plain text message payload :param payload: list of dicts :return: plain text formatted payload """ formatted = u'' for p in payload: formatted += u"{0} ({1}) \n".format(p['name'], p['query_url'].format(p['qty...
53050791335dd8d259bf6b55bd36d3e8bc3f5fb0
3,650,013
import json def get_credentials_from_request(cloud, request): """ Extracts and returns the credentials from the current request for a given cloud. Returns an empty dict if not available. """ if request.META.get('HTTP_CL_CREDENTIALS_ID'): return get_credentials_by_id( cloud, req...
29fa45d17a0473643b2db448dfbe2de7837c4dd7
3,650,014
from functools import reduce def nCr(n, r): """n-choose-r. Thanks for the "compact" solution go to: http://stackoverflow.com/questions/2096573/counting-combinations-and-permutations-efficiently """ return reduce( lambda x, y: x * y[0] / y[1], izip(xrange(n - r + 1, n + 1), ...
06ab7a4e12a35cf49f7ddf3e75780576d3b8972c
3,650,015
from pythia.pyre.inventory import facility from pylith.bc.DirichletTimeDependent import DirichletTimeDependent def bcFactory(name): """Factory for boundary condition items. """ return facility(name, family="boundary_condition", factory=DirichletTimeDependent)
65bb203b901c1648ee504bfd5bfd0956e9f849d4
3,650,016
def decode(value): """Decode utf-8 value to string. Args: value: String to decode Returns: result: decoded value """ # Initialize key variables result = value # Start decode if value is not None: if isinstance(value, bytes) is True: result = value....
9704678f6ff96de3b711758922c28f5ecbd11bc7
3,650,017
def sequence_rec_sqrt(x_init, iter, dtype=int): """ Mathematical sequence: x_n = x_{n-1} * sqrt(n) :param x_init: initial values of the sequence :param iter: iteration until the sequence should be evaluated :param dtype: data type to cast to (either int of float) :return: element at the given i...
a7e695ee605caad5cef7881a2eeafbee8a25bf15
3,650,018
def convert_string_to_type(string_value, schema_type): """ Attempts to convert a string value into a schema type. This method may evaluate code in order to do the conversion and is therefore not safe! """ # assume that the value is a string unless otherwise stated. if schema_type == "fl...
4d99470f7094a36567851bb23c1edd49686149cf
3,650,019
import os import glob def counter(path): """Get number of files by searching directory recursively""" if not os.path.exists(path): return 0 count = 0 for r, dirs, files in os.walk(path): for dr in dirs: count += len(glob.glob(os.path.join(r, dr + "/*"))) return count
e2d0498d1156a10a4ee98a3ad6701030af68e594
3,650,020
def get_local_coordinate_system(time_dep_orientation: bool, time_dep_coordinates: bool): """ Get a local coordinate system. Parameters ---------- time_dep_orientation : If True, the coordinate system has a time dependent orientation. time_dep_coordinates : If True, the coordinat...
daa8259e92a31884d798915522d4e538f316fc91
3,650,021
def _get_tooltip(tooltip_col, gpd): """Show everything or columns in the list.""" if tooltip_col is not None: tooltip = folium.GeoJsonTooltip(fields=tooltip_col) else: tooltip = tooltip_col return tooltip
8a2dc564ef65aa0eaf8a9e85457876ad0e6989ec
3,650,022
def encryption(message: str, key: int) -> str: """Return the ciphertext by xor the message with a repeating key""" return b"".join( [bytes([message[i] ^ key[i % len(key)]]) for i in range(len(message))] )
674e4a27491a9f6c918f2129276349ba426cd676
3,650,023
def data_fun(times): """Generate time-staggered sinusoids at harmonics of 10Hz""" global n n_samp = len(times) window = np.zeros(n_samp) start, stop = [int(ii * float(n_samp) / (2 * n_dipoles)) for ii in (2 * n, 2 * n + 1)] window[start:stop] = 1. n += 1 data = 1e-7 * ...
edbdf5e059b8f4c3559386497961a1c65133a80b
3,650,024
def var(x, axis=None, ddof=0, keepdims=False): """ Computes the variance along the specified axis. The variance is the average of the squared deviations from the mean, i.e., :math:`var = mean(abs(x - x.mean())**2)`. Returns the variance, which is computed for the flattened array by default, oth...
b39bf29caf4f47882fb3be900c2924a90b25a880
3,650,025
def check_inputs(supplied_inputs): """Check that the inputs are of some correct type and returned as AttributeDict.""" inputs = None if supplied_inputs is None: inputs = AttributeDict() else: if isinstance(supplied_inputs, DataFactory('dict')): inputs = AttributeDict(supplied...
a5369767c23a96b44da2bff2c0ac49456e3452f1
3,650,026
def _parse_none(arg, fn=None): """Parse arguments with support for conversion to None. Args: arg (str): Argument to potentially convert. fn (func): Function to apply to the argument if not converted to None. Returns: Any: Arguments that are "none" or "0" are converted to None; ...
4ebd283eb9e2218e523ba185c4500c9879d5719d
3,650,027
def generate_constraint(category_id, user): """ generate the proper basic data structure to express a constraint based on the category string """ return {'year': category_id}
f55151a5b4b17bbf6eb697e1b1489ee4897f5db0
3,650,028
def get_RIB_IN_capacity(cvg_api, multipath, start_value, step_value, route_type, port_speed,): """ Args: cvg_api (pytest fixture): snappi API temp_tg_port (pytest fixture): Por...
e13c85d9e6ebdbfba84e20a81324da8156e7c934
3,650,029
import os def input_file_exists(filepath): """ Return True if the file path exists, or is the stdin marker. """ return (filepath == '-') or os.path.exists(filepath)
5f6a0c2195ce90ba551679d516ebee0e593184c8
3,650,030
from typing import List from typing import Set def ladder_length(beginWord: str, endWord: str, wordList: List[str]) -> int: """ 双端交替迫近目标层,根据一层数量最多节点确定为目标层 :param beginWord: :param endWord: :param wordList: :return: >>> ladder_length('hit', 'cog', ["hot","dot","dog","lot","log","cog"]) ...
020f3ffd2e009b682a47ff9aad8d1d6025c29f37
3,650,031
def setup_option(request): """Создаем объект для удобство работы с переменными в тестовых методах """ setup_parameters = {} if request.config.getoption('--site_url'): setup_parameters['site_url'] = request.config.getoption('--site_url') return setup_parameters
49908ee8e1422cc4fd05c6d93a96c00d734cf6d1
3,650,032
import time import torch def train_one_epoch(img_input,model,optimizer,writer,epoch,args): """ Finish 1.train for one epoch 2.print process, total loss, data time in terminal 3.save loss, lr, output img in tensorboard Note 1.you can change the save frequency """ loss_train = 0...
b26e2933dd3575e45c33ba6bf801f5a92fc72ab7
3,650,033
def get_unique_tokens(texts): """ Returns a set of unique tokens. >>> get_unique_tokens(['oeffentl', 'ist', 'oeffentl']) {'oeffentl', 'ist'} """ unique_tokens = set() for text in texts: for token in text: unique_tokens.add(token) return unique_tokens
f9c174b264082b65a328fd9edf9421e7ff7808a2
3,650,034
def _symmetric_difference(provided: dict, chosen: dict) -> dict: """ Returns the fields that are not in common between provided and chosen JSON schema. :param provided: the JSON schema to removed the chosen schema from. :param chosen: the JSON schema to remove from the provided schema. :return: a J...
5900c6de35c0665ab2c0ec10c4df4dc87b75483a
3,650,035
import subprocess import re def check_pv_name_in_rados(arg, image_id, pvc_name, pool_name): """ validate pvc information in rados """ omapkey = 'csi.volume.%s' % pvc_name cmd = ['rados', 'getomapval', 'csi.volumes.default', omapkey, "--pool", pool_name] if not arg.userkey: c...
11d530ed1047064367a36af3fbf8652b1e0f60a8
3,650,036
def moved_in(nn_orig, nn_proj, i, k): """Determine points that are neighbours in the projection space, but were not neighbours in the original space. nn_orig neighbourhood matrix for original data nn_proj neighbourhood matrix for projection data i index of the point considered ...
b63a9b0f53554032fc920aeaf6d3d76b93dd8ab3
3,650,037
import re def _get_lines_changed(line_summary): """ Parse the line diff summary into a list of numbers representing line numbers added or changed :param line_summary: the summary from a git diff of lines that have changed (ex: @@ -1,40 +1,23 @@) :return: a list of integers indicating which lines chang...
01d1b51ef480a0d7dcdc916fe68aac08ce81d23f
3,650,038
def tj_agri_sup(): """ Real Name: b'Tj Agri Sup' Original Eqn: b'MIN(Tj Agri Dem *Agri Tajan Dam Coef, (Tj Outflow-Tj Dom Sup-Tj Env Sup-Tj Ind Sup))' Units: b'' Limits: (None, None) Type: component b'' """ return np.minimum(tj_agri_dem() * agri_tajan_dam_coef(), ...
07c6029dc062f20756b3f72289640a29526c41bf
3,650,039
def correlation_coefficient(y_true, y_pred): """The CC, is the Pearson’s correlation coefficient and treats the saliency and ground truth density maps, as random variables measuring the linear relationship between them.Values are first divided by their sum for each image to yield a distribution...
9d0f7825219a5957edfbf464ca9b62182b81bb3c
3,650,040
def init_args(): """Init command line args used for configuration.""" parser = init_main_args() return parser.parse_args()
c2939b8d6fbefa7a6b792d13c98a805a3e53785f
3,650,041
import warnings def _fit_binary(estimator, X, y, classes=None, **kwargs): """Fit a single binary estimator with kwargs.""" unique_y = np.unique(y) if len(unique_y) == 1: if classes is not None: if y[0] == -1: c = 0 else: c = y[0] ...
24e37aa50cada6cce4ab52c1be85cace3ad4c417
3,650,042
import csv def data_index(person, dim): """ Output sequence of eye gaze (x, y) positions from the dataset for a person and a dimension of that person (task, session, etc) Index starts at 0. The vectors are [x, y, flag], flag being if it's null """ session = "S1" if dim % 2 == 0 else "S2" #...
e8b37aaeb2c228f0749aece26609fb04e0d4a226
3,650,043
def getStatic(): """ These are "static" params for a smoother application flow and fine tuning of some params Not all functions are implemented yet Returns the necessary Params to run this application """ VISU_PAR = { # ============================================================================...
f82ed9c4156b8199be924fc1ed62398fcbad9e0c
3,650,044
def current_device(): """Return the index of the current active device. Returns ------- int The index of device. """ return dragon.cuda.GetDevice()
453b81673e198ddd3a5870843d16b9cc395802d4
3,650,045
import time async def access_logger(app, handler): """Simple logging middleware to report info about each request/response. """ async def logging_handler(request): start_time = time.time() request_name = hex(int(start_time * 10000))[-6:] client_ip, _ = request.transport.get_extra_i...
55d4ac318a65d6f4256467f7909b5a6ee2115a6d
3,650,046
from typing import Tuple def main(source: str) -> Tuple[astroid.Module, TypeInferer]: """Parse a string representing source text, and perform a typecheck. Return the astroid Module node (with the type_constraints attribute set on all nodes in the tree) and TypeInferer object. """ module = astroid...
f8e9b9a0ac9ff4334cce9ca7c888d3ff11570661
3,650,047
def to_literal_scalar(a_str): """Helper function to enforce literal scalar block (ruamel.yaml).""" return ruamel.yaml.scalarstring.LiteralScalarString(a_str)
7cdb3d37bad184b7c6e68b374d1b6fd7e4c744c4
3,650,048
from typing import Optional def get_first_free_address(subnet_id: Optional[int] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetFirstFreeAddressResult: """ Use this data source to access information about an existing resource. """ __args__ = dict() __...
ea4a599a7f3ac65e296cce4c8fc3a764202bba26
3,650,049
def pagenav(object_list, base_url, order_by, reverse, cur_month, is_paginated, paginator): """Display page navigation for given list of objects""" return {'object_list': object_list, 'base_url': base_url, 'order_by': order_by, 'reverse': reverse, 'cur_month': cur_...
eb61fb76dd32b8d0b3e264e77ce912766d3e38da
3,650,050
def read_input(path: str): """ Read game board file from path. Return list of str. >>> read_input("skyscrapers1.txt") ['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***'] """ with open(path, 'r') as f: game_lst = f.readlines() for idx, line in enumerate(...
a4bf08525ca3fe4b0b1efab1901830b4d7c45f05
3,650,051
def run_tweeter(): """ Captures image and sends tweet """ capture_image_and_tweet() return schedule.CancelJob
2cf3895270e5f5f64ecb2e943548f0a290c35b02
3,650,052
import time from functools import reduce from operator import add def get_retro_results( outdir, recos_basedir, events_basedir, recompute_estimate=False, overwrite=False, ): """Extract all rectro reco results from a reco directory tree, merging with original event information from correspo...
e3753b86ed4efa60057f1e3a0c70c34193447718
3,650,053
import copy def split_surface_v(obj, t, **kwargs): """ Splits the surface at the input parametric coordinate on the v-direction. This method splits the surface into two pieces at the given parametric coordinate on the v-direction, generates two different surface objects and returns them. It does not modi...
6603fb5e4c45fa60817168d776ac005475bd37a5
3,650,054
from typing import OrderedDict def oidc_userprofile_test(request): """ OIDC-style userinfo """ user = request.user profile, g_o_c = UserProfile.objects.get_or_create(user=user) data = OrderedDict() data['sub'] = user.username data['name'] = "%s %s" % (user.first_name, user.last_name) ...
aeae1962615ac9894b1b555814851c33efa85b45
3,650,055
def split_idx( idx,a,b): """ Shuffle and split a list of indexes into training and test data with a fixed random seed for reproducibility run: index of the current split (zero based) nruns: number of splits (> run) idx: list of indices to split """ rs = np.random.RandomState() rs.sh...
e5c9850a0bbcdb187d12dff4cd9df6c9faddfacc
3,650,056
def scale(val, src, dst): """ Scale the given value from the scale of src to the scale of dst. val: float or int src: tuple dst: tuple example: print(scale(99, (0.0, 99.0), (-1.0, +1.0))) """ return (float(val - src[0]) / (src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]
26cfaccaeea861ccecb36697838710c0ab706520
3,650,057
def add(c1, c2): """Add two encrypted counters""" a1, b1 = c1 a2, b2 = c2 return (a1 + a2, b1 + b2)
d3e519524fac558622f692a46ffb8fed9899176f
3,650,058
async def wait_all_tasks_blocked(cushion=0.0): """Block until there are no runnable tasks. This is useful in testing code when you want to give other tasks a chance to "settle down". The calling task is blocked, and doesn't wake up until all other tasks are also blocked for at least ``cushi...
35b144f4a214cb1f02bb1448f78a54ed93ac66aa
3,650,059
def get_chisq_grid(data, type, forecast=False, errors=None): """ Generates 2d meshgrid for chisq values of a given type (i.e. BBN, CMB etc) """ masses = np.unique(data['mass']) omegabs = np.unique(data['OmegaB']) MASS, OMEGAB = np.meshgrid(masses, omegabs) OMEGABDAT = data['OmegaB'].reshape(...
3ea6fcf16d6c506733f5164e8808c5d5dce6c969
3,650,060
import os import random def collect_samples_clouds_video(upsampling, opt, deferred_shading=False): """ Collect samples of cloud videos. opt is expected to be a dict. Output: DatasetData - samples: list of Sample - images_high: num_frames x output_channels x H*upsampling x W*upsampling -...
aab7be545d3b1561c7677bd9d370f8b5562d0c4f
3,650,061
import ctypes def spectrl2(units, location, datetime, weather, orientation, atmospheric_conditions, albedo): """ Calculate solar spectrum by calling functions exported by :data:`SPECTRL2DLL`. :param units: set ``units`` = 1 for W/m\ :sup:`2`/micron :type units: int :param locatio...
aa8bd3878bc3f230d89e1d9545621a43e2d2fa6c
3,650,062
def setup_transition_list(): """ Creates and returns a list of Transition() objects to represent state transitions for an unbiased random walk. Parameters ---------- (none) Returns ------- xn_list : list of Transition objects List of objects that encode information about th...
702c7a7083546797578e5463841c7b59548dcca2
3,650,063
def error_message(error, text): """ Gives default or custom text for the error. -------------------- Inputs <datatype>: - error <Error Object>: The error code - text <string>: Custom error text if error has no message Returns <datatype>: - error description <string>: The cust...
466fec2d2abefc9f05a3f0adf569fba1c63ea4c1
3,650,064
def maskguard(maskarray, niter=1, xyonly=False, vonly=False): """ Pad a mask by specified number of pixels in all three dimensions. Parameters ---------- maskarray : `~numpy.ndarray` The 3-D mask array with 1s for valid pixels and 0s otherwise. niter : int, optional Number of i...
098964878e313b08c73f1a3c1a66a2b7f1664090
3,650,065
def validdest(repo, old, new): """Is the new bookmark destination a valid update from the old one""" repo = repo.unfiltered() if old == new: # Old == new -> nothing to update. return False elif not old: # old is nullrev, anything is valid. # (new != nullrev has been exclu...
8206b1ec130582864979ea9fb617c60b6175deff
3,650,066
def no_rbac_suffix_in_test_filename(filename): """Check that RBAC filenames end with "_rbac" suffix. P101 """ if "patrole_tempest_plugin/tests/api" in filename: if filename.endswith('rbac_base.py'): return if not filename.endswith('_rbac.py'): return 0, "RBAC t...
6ebfcede8b6e30f24f5ecc1f9d3f0985bd4c44fa
3,650,067
def import_results(results_file, valid_codes=None, session=None): """Take a iterable which yields result lines and add them to the database. If session is None, the global db.session is used. If valid_codes is non-None, it is a set containing the party codes which are allowed in this database. If None,...
e7faea1b78418b6fdb599612fdc72fe20fe45bc6
3,650,068
def fit_lens_data_with_tracer(lens_data, tracer, padded_tracer=None): """Fit lens data with a model tracer, automatically determining the type of fit based on the \ properties of the galaxies in the tracer. Parameters ----------- lens_data : lens_data.LensData or lens_data.LensDataHyper The...
c94454462e4e9fd770eebf39a9574daa0e6a9025
3,650,069
def sround(a, *ndigits): """Termwise round(a) for an iterable. An optional second argument is supported, and passed through to the built-in ``round`` function. As with the built-in, rounding is correct taking into account the float representation, which is base-2. https://docs.python.org/...
ee75d82fa3bdfb50afb279cce87d6d6ec6120adf
3,650,070
def part_b(lines): """ For each valid line consider the stack of opening characters that didn't get closed. Compute a score for each line per the question, then return the median value of these scores. """ scores = [] for line in lines: is_line_valid, stack = assess_line(line) if is_...
e745a3be40f5a83f0e8ce3de4c647bd5984e7511
3,650,071
def _get_activation( spec): """Get a rematlib Layer corresponding to a given activation function.""" if spec == mobile_search_space_v3.RELU: result = layers.ReLU() elif spec == mobile_search_space_v3.RELU6: result = layers.ReLU6() elif spec == mobile_search_space_v3.SWISH6: result = layers.Swish...
d2e67564eb366128b6dfe9f0c1c919ceb0e949ac
3,650,072
def addUpdateCarrierGroups(): """ Add or Update a group of carriers """ db = DummySession() try: if not session.get('logged_in'): return redirect(url_for('index')) if (settings.DEBUG): debugEndpoint() db = SessionLoader() form = stripDictV...
570374d0c42e89c2cd57b628345e88e7e5680d90
3,650,073
def RT2tq(poses, square=False): """ !!NOT TESETED!! :param poses: N x 3 x 4, (R|T) :return: (N, 7) """ N,_,_ = poses.shape R = poses[:,:,:3] T = poses[:,:,3:] # Nx3x1 q = quaternion.as_float_array(quaternion.from_rotation_matrix(R)) #Nx4 t= T.squeeze(-1) tq = np.concatena...
5241aa7110df8074fe203b1cbe33cb7bf509c2f3
3,650,074
import json def make_callback(subscription_path, project_id): """Return a callback closure""" def callback(message): """Handle Pub/Sub resurrection message. Ignore (and ACK) messages that are not well-formed. Try handle any other message, ACKing it eventually (always). """ logger.info('Handl...
ac16d67ee9e7b89d69b79702e4121b1983df2bb8
3,650,075
import os def make_partition_table(target_device, part_name, **kwargs): """ Create new GUID partition table on ``target_device``, with two partitions: 1) GRUB second stage partition with type 0xEF02 2) size of rest of the disk with name ``part_name`` Returns path to the boot partit...
c40fc6c256ce2f94f4a909b633a47e07443940f0
3,650,076
def data_to_bytes(data, encoding): """\ Converts the provided data into bytes. If the data is already a byte sequence, it will be left unchanged. This function tries to use the provided `encoding` (if not ``None``) or the default encoding (ISO/IEC 8859-1). It uses UTF-8 as fallback. Returns th...
78d0813075c24d2a85412648fa45d720227ae853
3,650,077
def get_session_store(state: State = Depends(get_app_state)) -> SessionStore: """Get a singleton SessionStore to keep track of created sessions.""" session_store = getattr(state, _SESSION_STORE_KEY, None) if session_store is None: session_store = SessionStore() setattr(state, _SESSION_STORE...
4204371079babbfdc15327bb62b3c1c306e27f39
3,650,078
import os def get_comments(filename): """ Get Julia, Python, R comments. """ comments = [] try: with open(filename, 'r', encoding='utf8') as fp: filename = os.path.basename(filename) for comment, start, end in getcomments.get_comment_blocks(fp): comments.append({ "ln%s" % (start[0])...
a3944acc98914c3d245fe62a03b825790dad8565
3,650,079
def extractCurrentlyTLingBuniMi(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if item['title'].startswith('[BNM]'): return buildReleaseMessageWithType(item, 'Bu ni Mi wo Sasagete Hyaku to ...
9b91a6a2329cb4e2572f181b16ddc6b2f0fb3553
3,650,080
from dif import dif_stats def dif_stats(filename, # [<'my/file.txt',...> => name of scored data file] student_id = 'Student_ID', # [<'Student_ID', ...> => student id column label] group = ['Sex', {'focal':0, 'ref':1}], # [<e.g.'Sex', {'focal':'female', 'ref':'male'}]> => column label...
0ed6b94e63d5eacc40aeaf4f2181012ef8aacc22
3,650,081
def delete_all_devices_for_user(): """ delete all active devices for the given user """ try: username = get_jwt_identity() with session_scope() as session: user = user_service.get_user(username, session) device_count = user.devices.count() if device_...
2ac4c0f40e72dc54ca78a109ead9d09f15481b92
3,650,082
def _GetNormalizationTuple(url): """Parse a URL into a components tuple. Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params>?<query>#<fragment> Args: url:A URL string. Returns: A 6-tuple: (scheme, netloc, path, params, query, fragment). """ url = encoding_util.EncodeToAscii(url) ...
cbc8dad95202a9a17f75dac754b6ec00e3efcdfd
3,650,083
def gCallback(dataset, geneid, colors): """Callback to set initial value of green slider from dict. Positional arguments: dataset -- Currently selected dataset. geneid -- Not needed, only to register input. colors -- Dictionary containing the color values. """ colorsDict = colors try: ...
5a97fd16ea362b3b53f33f52a449c4dccc617e44
3,650,084
def intForcesMoments(sliceZnes,method, direction): """ Loops over the sliceZnes and performs an integration of Forces and moments for each slice (Scalar integrals, variables are depending on the method). Returns a ([dir, dirNormalized,fxNr,fyNr,fzNr,mxNr,myNr,mzNr]*Nslices array) """ #direction...
16e0a3adc3a3b171fd02b07f241ed8623b16c7e3
3,650,085
from typing import List def _other_members(other_members: List[parser.MemberInfo], title: str): """Returns "other_members" rendered to markdown. `other_members` is used for anything that is not a class, function, module, or method. Args: other_members: A list of `MemberInfo` objects. title: Title of...
77c02e8532dd01bab0b9ea0f9d14634dc3523cd2
3,650,086
def full_url(parser, token): """Spits out the full URL""" url_node = url(parser, token) f = url_node.render url_node.render = lambda context: _get_host_from_context(context) + f(context) return url_node
d54e9cf5acee1b6283f3166e9479e8c9e8bb5047
3,650,087
def Chi2CoupleDiffFunc(nzbins, nzcorrs, ntheta, mask, data1, xi_obs_1, xi_theo_1, data2, xi_obs_2, xi_theo_2, inDir_cov12, file_name_cov12): """ Estimate chi^2 for difference between two data vectors Note: this assumes two data vectors ...
c0cd8a683447b0572a93914e633fb8f770c3a6fd
3,650,088
def minimax(just_mapping, mapping): """ Scale the mapping to minimize the maximum error from just intonation. """ least_error = float("inf") best_mapping = mapping for i in range(len(just_mapping)): for j in range(i+1, len(just_mapping)): candidate = mapping / (mapping[i] + m...
b2226de7a916e3075327cd30c64e7412e186027d
3,650,089
from datetime import datetime def app_used_today(): """Check the session and the backend database for a record of app use from the last 24 hours.""" now = UTC.localize(datetime.datetime.utcnow()) last_app_use = get_last_app_use_date() day_length_in_seconds = 60 * 60 * 24 if last_app_use and (last_...
290bb4b87e74f5134effeb37da36cedcca05c4aa
3,650,090
def search_by_pattern(pattern, limit=20): """Perform a search for pattern.""" pattern_ = normalize_pattern(pattern) db = get_db() results = db.execute( """ SELECT json FROM places WHERE document MATCH ? ORDER BY rank DESC LIMIT ?; """, (fts_pattern...
467b85c850bb27ac1ed9a6e7fff6bb969a5f84e0
3,650,091
def gcd(a, b): """Greatest common divisor""" return _gcd_internal(abs(a), abs(b))
886d366893a0215ccf0208af56c9c45037ad9549
3,650,092
def exp_create_database(db_name, demo, lang, user_password='admin', login='admin', country_code=None, phone=None): """ Similar to exp_create but blocking.""" _logger.info('Create database `%s`.', db_name) _create_empty_database(db_name) _initialize_db(id, db_name, demo, lang, user_password, login, count...
b1d956628d864e0aa3998c00fd6a0b7cfb3ba411
3,650,093
def fix_cr(data): """Cosmic ray fixing function. Args: data (:class:`numpy.ndarray`): Input image data. Returns: :class:`numpy.dtype`: Fixed image data. """ m = data.mean(dtype=np.float64) s = data.std(dtype=np.float64) _mask = data > m + 3.*s if _mask.sum()>0: ...
40702ccc9400f4ba5f10cad1f376b83eac487876
3,650,094
def iou(box1, box2, iouType='segm'): """Compute the Intersection-Over-Union of two given boxes. or the Intersection-Over box2. Args: box1: array of 4 elements [cx, cy, width, height]. box2: same as above iouType: The kind of intersection it will compute. 'keypoints' is for intersectio...
42ef4689c977e4ccbdbb987ff3ae63b265d3c42d
3,650,095
def transform_color(color1, color2, skipR=1, skipG=1, skipB=1): """ transform_color(color1, color2, skipR=1, skipG=1, skipB=1) This function takes 2 color1 and color2 RGB color arguments, and then returns a list of colors in-between the color1 and color2 eg- tj.transform_color([0,0,0],[10,10,20]) returns a list:...
5f04daa951c59b0445387b2dc988ab7efb98aff4
3,650,096
def sandwich(func): """Write a decorator that prints UPPER_SLICE and LOWE_SLICE before and after calling the function (func) that is passed in (@wraps is to preserve the original func's docstring) """ @wraps(func) def wrapped(*args, **kwargs): print(UPPER_SLICE) fun...
167e1a753b7ba1f0d42732e12c5b37e0b0670f1b
3,650,097
def as_dict(bdb_path, compact=True): """Get the state of a minter BerkeleyDB as a dict. Only the fields used by EZID are included. """ with nog.bdb_wrapper.BdbWrapper(bdb_path, dry_run=False) as w: return w.as_dict(compact)
dab02d671c099bd726839dc40167632cab812015
3,650,098
def _ecg_findpeaks_ssf(signal, sampling_rate=1000, threshold=20, before=0.03, after=0.01): """From https://github.com/PIA- Group/BioSPPy/blob/e65da30f6379852ecb98f8e2e0c9b4b5175416c3/biosppy/signals/ecg.py#L448. - W. Zong, T. Heldt, G.B. Moody, and R.G. Mark. An open-source algorithm to detect onset of art...
d7527db71724d8208a3438f8f959d23e82c89d6a
3,650,099