content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_headings(self, dict): """ Table headings for output Notes: This is awful but it works. """ cont = True keys = list(dict.keys()) count = 0 headings = [] # find the first spectral averaging area where there is a fit # and get the parameter names headings_non_spec...
b73789c6bd016935706e1186178b71499b72a22e
683,067
import argparse def get_cmd_args(): """Get command line arguments """ default_run_name = "test" default_run_dir = ("./") parser = argparse.ArgumentParser( description="Particle phase space diagram") parser.add_argument("--pic_run_dir", action="store", ...
410e177fdef87046fe42a523871f661962163243
683,069
def flatten_protocols(out_packet): """ return present protocols as list """ protocols = [out_packet] out = out_packet while True: out = out.upper_layer() if out is not None: protocols.append(out) else: break return protocols
d7dbdcb1221fffc924ef0008d973e30a2f2dc17d
683,070
def _metadata(image, datapath): """Function which returns metadata dict. :param image: image to get spacing from :param datapath: path to data :return: {'series_number': '', 'datadir': '', 'voxelsize_mm': ''} """ metadata = {"series_number": 0, "datadir": datapath} spacing = image.GetSpacin...
73d97fa0d28087afd6df4b90ac008d29edb0cc27
683,071
def _numeric_eduation(dataf): """ Transforms the string variable education to numeric values """ dataf = dataf.copy() dataf.loc[:, "educ"] = 0 dataf.loc[(dataf['education'] == "[1] Hauptschulabschluss"), "educ"] = 0 dataf.loc[(dataf['education'] == "[2] Realschulabschluss"), "educ"] = 1 ...
84762b37ebfee6813e4c4f19fb7672408285bd83
683,072
def convert_to_SimpleIndex(data, axis=0): """ Converts the index of a DataFrame to a simple, one-level index The target index uses standard SimCenter convention to identify different levels: a dash character ('-') is used to separate each level of the index. Parameters ---------- data: Dat...
2f6ce3af39fd01314feeb0933821dbe67dbe8c1c
683,073
from typing import Callable import click def variant_option(command: Callable[..., None]) -> Callable[..., None]: """ An option decorator for a DC/OS variant. """ function = click.option( '--variant', type=click.Choice(['auto', 'oss', 'enterprise']), default='auto', hel...
94433d3c55a7ec5709e2349b341ea6a814278142
683,074
from typing import Iterable def hr_bytes(data: Iterable[int], delimiter: str = ' ') -> str: # pragma: no cover """ Print bytes (or another int iterable) as hex and delimiters :param data: Bytes or iterable object :param delimiter: Delimiter (str value) :return: str valu...
a399b1da61fc5cef6ff071ea2ae7566036ae1726
683,075
def dict2str(variables, SKIP_KEYS = ["OUT", "DESCRIPTION", "RED", "GREEN", "BLUE", "ID"]): """ Try passing variables = globals(). """ params = sorted((k for k in variables.keys() if k==k.upper() and k[0]!="_" and k not in SKIP_KEYS), key=lambda v: (v, len(v)) ) return " ".join( ("%...
512186cb76bd62f4c974bb7c7f5cf857cc5413ea
683,076
def create_path(network, user_A, user_B, path=[]): """ Finds a connections path from user_A to user_B using recursion. It has to be an existing path but it DOES NOT have to be the shortest path. Circular loops returns None (for example, A is connected to B. B is connected to C. C is connected to B.)...
b3e88f4e18c0ab86c971706ea74e0a1739a61a2e
683,077
def hd(d): """Get hashable form of dictionary.""" return frozenset(d.items())
1d94243581d1539c1a07706fc3ab9564afb8cb5e
683,078
import math def chunk(iterable, n): """Splits a list into n equal parts""" iterable = [e for e in iterable] avg_length = int(math.ceil(len(iterable) / n)) return [iterable[i * avg_length:(i + 1) * avg_length] for i in range(n)]
74d649b8db2625861db6110733a0ea8342541657
683,079
def first_down(items): """Return True if the first item is down.""" return items[0] == '-'
e24afe79971572de01676bda608a317c83fb7792
683,080
def getGenes(doc): """Reads genes from the SBML file and returns a dictionnary""" allGenes = doc.getElementsByTagName("fbc:geneProduct") genes = [] for g in allGenes: gene = {} gene["id"] = g.getAttribute("fbc:id") gene["name"] = g.getAttribute("fbc:name") genes.append(ge...
3436a5318655882efa7f5c7733af26e57869a8a2
683,081
from typing import List def load_files(filenames: List[str]) -> List[str]: """Loads files""" files: List[str] = [] for filename in filenames: with open(filename, "r", encoding="utf-8") as infile: files.append(infile.read()) return files
0391cf93cdf351fa40e6f8e3f739cbc7cc58ea26
683,082
def unsort(sorted_list, oidx): """ Unsort a sorted list, based on the original idx. """ assert len(sorted_list) == len(oidx), "Number of list elements must match with original indices." _, unsorted = [list(t) for t in zip(*sorted(zip(oidx, sorted_list)))] return unsorted
fc54770d389029d36e598035b82264b325d76940
683,083
def figure_linguistic_type(labels): """ Gets linguistic type for labels Parameters ---------- labels : list of lists the labels of a tier Returns ------- the linguistic type """ if len(labels) == 0: return None elif len(labels) == 1: return lab...
14151917bb9ad8f49717ce6c436c496ee3ccfc77
683,084
import argparse def get_plot_parser(): """Argument parser to load model to plot visuals""" parser = argparse.ArgumentParser( description='Plotting') parser.add_argument('--log_dir', type=str, default='logs/', required=True, ...
4681f37834de6e2b640f9fd71d058255e17aad83
683,085
def get_rank(cutoff: dict, coverage: float, quality: float, length: int, contigs: int, genome_size: int, is_paired: bool) -> list: """ Determine the rank (gold, silver, bronze, fail) based on user cutoffs. Args: cutoff (dict): Cutoffs set by users to determine rank coverage (float): Estimat...
2cd31199cb555c6bbbc4cec87e806ed4fcf6c983
683,086
import math def damavandi2(u1, u2) -> float: """ Pretty evil function this one """ # http://infinity77.net/global_optimization/test_functions_nd_D.html#go_benchmark.Damavandi x1 = u1 / 14. x2 = u2 / 14. numerator = math.sin(math.pi * (x1 - 2.0)) * math.sin(math.pi * (x2 - 2.0)) denumerator = (...
ea34f55861a7cf0bdeaa2e127c2cd9a8ce2935f2
683,087
def add_vectors(vec_1, vec_2): """ adds two vectors: non-array results vec_1 & vec_2: XYZ components of the vectors. returns: list of resulting vector """ return [a+b for (a, b) in zip(vec_1, vec_2)]
cdf7f19c7e64fb9118a5d498b643f070eeaf0f9a
683,088
def get_supported_pythons(classifiers): """Return min and max supported Python version from meta as tuples.""" PY_VER_CLASSIFIER = 'Programming Language :: Python :: ' vers = filter(lambda c: c.startswith(PY_VER_CLASSIFIER), classifiers) vers = map(lambda c: c[len(PY_VER_CLASSIFIER):], vers) vers = ...
0160cd9aef2c7756b3c6c887c904673d6277d014
683,089
def _parse_gateway(gw_data): """ compute the amount of ressource unit use by a gateway service :return: dict containing the number of ressource unit used :rtype: [type] """ return {"hru": 0, "sru": 0, "mru": 0.1, "cru": 0.1}
78325094209c2cba25f65e7ee1d0a51d1297c355
683,090
def filter_empty_values(mapping_object: dict) -> dict: """Remove entries in the dict object where the value is `None`. >>> foobar = {'username': 'rafaelcaricio', 'team': None} >>> filter_empty_values(foobar) {'username': 'rafaelcaricio'} :param mapping_object: Dict object to be filtered """ ...
582e7874c96b261779f5a2d6b5a6e5a37b89ec81
683,091
def axis_ticklabels_overlap(labels): """Return a boolean for whether the list of ticklabels have overlaps. Parameters ---------- labels : list of ticklabels Returns ------- overlap : boolean True if any of the labels overlap. """ if not labels: return False try:...
8b9edc2b97ae00976a573aefac5067568328ae05
683,092
import argparse def get_args(): """ Defines training-specific hyper-parameters. """ parser = argparse.ArgumentParser('Sequence to Sequence Model') parser.add_argument('--cuda', default=False, help='Use a GPU') # Add data arguments parser.add_argument('--data', default='prepared_data', help='path ...
6ea36610b69a8d0be991e0fbed4ec0fcc014c7db
683,094
def split_paragraphs(lines, keepends=False): """Split the lines into paragraphs""" paras = list() para = list() for line in lines: if line.strip(): para.append(line) else: if keepends: para.append(line) if para or keepends: ...
f34281743186b7d06ed567cd195c07ba5f61f849
683,096
import os def out_of_date(original, derived): """ Returns True if derivative is out-of-date wrt original, both of which are full file paths. """ return (not os.path.exists(derived) or os.stat(derived).st_mtime < os.stat(original).st_mtime)
6c89151617785e17ba53c1bf424956f74ccc9449
683,097
def logreg_classifier_to_dict(classifier, feature_names=None): """ Serialize sklearn logistic regression classifier Inspired by https://stackoverflow.com/questions/48328012/python-scikit-learn-to-json Parameters ---------- classifier : sklearn.linear_model.LogisticRegression Logistic r...
081330c53eb4dcded9b92c0ee9f878b4bf208b13
683,098
def add(x, y): """This is a doc string :param x: first value to add :param y: second value to add :returns: x + y """ return x + y
421e7d34f7549235694cbdf4b9ec97021e06b46b
683,099
import os def file_to_scene(f): """convert filename of tif to scene""" b = ( os.path.basename(f) .replace("reprojected_", "") .replace("_resampled", "") .replace("_3B_Visual.tif", "") .replace("T", "_") ) if b[-5] != "_": b = f"{b[:-4]}_{b[-4:]}" s =...
1de7c3c5e23e9d208d839f673e86b306b23ace06
683,100
from typing import Tuple import torch from typing import Optional from typing import Dict from typing import List from typing import Any def unpack_non_tensors( tensors: Tuple[torch.Tensor, ...], packed_non_tensors: Optional[Dict[str, List[Any]]] ) -> Tuple[Any, ...]: """See split_non_tensors.""" if packe...
e7259ec9425f717d52f713133081cdf6038a0b50
683,101
def time_to_string(_time): """ 传入一个标准时间,返回其字符串形式 :param _time: 时间 :return: 时间字符串 """ return _time.strftime("%Y-%m-%d %H:%M:%S")
d07ceca790ea22bb31e524090f884388e83f7e73
683,102
def criteria_functions_3(): """3 functions are passed to a VMCCriteria view""" def a_to_m_and_count_less_than_10(args): """Items matching this condition go in column 1""" entry_keys = args return "ABCDEFGHIJKLM".find(entry_keys[0][0]) > -1 and entry_keys[1] < 10 def n_to_z_and_coun...
3d75e1700346a3760d67b6a360ded02a7dbfbe10
683,103
import torch def group_single_model(model): """ Group model parameters """ # find all the BN layers bn_layer_name = [] for name, m in model.named_modules(): if isinstance(m, torch.nn.BatchNorm2d): bn_layer_name.append(name) param_list = [] for name, p in model.named_parame...
ef17a610592358b7ed0c6eb3f840621fed12acc4
683,104
def get_voigt_mapping(n): """ Get the voigt index to true index mapping for a given number of indices. """ voigt_indices = [[0,0],[1,1],[2,2],[1,2],[0,2],[0,1],[2,1],[2,0],[1,0]] if (n%2): indices = [[0],[1],[2]] n-=1 else: indices = [[]] for _ in r...
ed758c106e7f8baf8066be92f42f990401210967
683,105
def version(): """ Return version number """ return "0.1"
db06386d1e3d1c72e91b9578e6bf8deab6b92d8a
683,106
def chop(s): """Chop off the last bit of a file object repr, which is the address of the raw file pointer. """ return ' '.join(s.split()[:-1])
5924242717b5a1fee16fe3e50be100d11aaa9a7d
683,107
def remove_atom_maps(mol): """ Iterates through the atoms in a Mol object and removes atom maps Parameters: mol (rdkit.Mol): Rdkit Mol Object Returns: mol (rdkit.Mol): Rdkit Mol Object without atom maps or 'nan' if error """ try: for atom in mol.GetAtoms(): ...
213b155d5ed8142e7ca75d594ad3a8e296b44804
683,108
import torch def stft_wrapper(x, fft_n, frame_shift, frame_length, window, pad_mode="constant"): """Due to the different signature of torch.stft, write a wrapper to handle this input ----- x: tensor, waveform, (batch, length) window: tensor, window coef, (frame_length, ...
19ab7dc44526fbe8d5b214560c461f313d95cfe6
683,109
def _lm_tail(k, lm): """Return elements of `Lm` with indices `k..N`.""" n = len(lm) assert k >= 1, k assert k <= n, (k, n) start = k - 1 assert start >= 0, start r = lm[start] for i in range(start, n): r |= lm[i] return r
f8b70687682ec5512e42229551c3a56afe0ba3f8
683,110
def flesch_reading_ease(n_syllables, n_words, n_sents, lang=None): """ Readability score usually in the range [0, 100], related (inversely) to :func:`flesch_kincaid_grade_level()`. Higher value => easier text. Note: Constant weights in this formula are language-dependent; if ``lang`` is...
6811b2a25566647729e84fd542f90a1c1b993fdc
683,111
def normalize(name): """Normalize the name of an encoding.""" return name.replace('_', '').replace('-', '').upper()
36631545837f179ca84573a77697b241f1b6a198
683,112
import json def load_twitter_credentials(): """ Loads twitter keys from pre-formed json file (store_twitter_api) """ consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" with open("twitter_credentials.json") as json_file: data = json.load(json_file) consume...
f1d30c9794873f83252b7a349824d6db41fafa7c
683,113
import torch def one_hot_encoding(input, c): """ One-hot encoder: Converts NxHxW label image to NxCxHxW, where each label is stored in a separate channel :param input: input image (NxHxW) :param c: number of channels/labels :return: output image (NxCxHxW) """ assert input.dim() == 3 N...
e91484b5b826db6da8b3877280cff31f0841c243
683,114
import argparse from textwrap import dedent def parse_args(): """command line options""" class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass parser = argparse.ArgumentParser( formatter_class=CustomFormatter, prefix_chars='-', ...
8c2f4fcdc43fad13298df232ffdb28037bafdfa7
683,115
def kv_array_to_dict(kv_pairs): """ Takes an array of key=value formatted Strings and returns a dict """ pairs = {} if kv_pairs: for kv_string in kv_pairs: kv = kv_string.split("=") if len(kv) == 2: pairs[kv[0]] = kv[1] return pairs
586375649f591553c2ba919d5d8b0c9bbdd494bd
683,116
import subprocess import sys def get_condor_config_val(variable, executable='condor_config_val', quiet_undefined=False): """ Use condor_config_val to return the expanded value of a variable. Arguments: variable - name of the variable whose value to return executable - the name of the executable t...
98a7b6681a1a37d8be79507b6dd7962c8969d351
683,117
def lin_interp_50p(xs, ys, thresh=50.0): """ Linear interpolation to find the 50% erase mark In practice sets increase pretty rapidly around 50% so this should be reliable """ if len(xs) < 2: print("WARNING: interpolation failed (insufficient entries)") return 0.0 if ys[0] > 0....
ba5ea84731f1ff4b3317ebcd18efdea0b8e176b8
683,118
import inspect def call(method, **kwargs): """Calls method with only parameters it requires""" # Due to SelfManaged overriding __new__, inspect cannot infer the expected variables from __new__ inspected_method = method.__init__ if inspect.isclass(method) else method expected = inspect.signature(inspec...
a3abb8ca298a5be3891404d8c96ac2974436b70d
683,119
def draw_graph(self, name='Graph', value=False): """Draw the SVG dot_graph of an OpenMDAO Component/Driver/Assembly instance""" return self.make_graph(name, value).svg
b3d45a6fc3b712ab5e0d1823bab10451e7a10186
683,120
def getShiftLists(project): """Descrn: Get a list of shift lists from a CCPN project Inputs: Implementation.Project Output: List of ccp.nmr.Nmr.ShiftLists """ nmrProject = project.currentNmrProject shiftLists = [] for measurementList in nmrProject.sortedMeasurementLists(): if...
e8b4356d75deb361a2bcb81510d3b54a2870341e
683,121
from functools import reduce def largest_continuous_sum(arr): """returns the highest sum of a continuous sequence in a given list""" largest = 0 queue = [] for num in arr: if len(queue) > 0 and queue[-1] + 1 != num: sum = reduce(lambda x, y: x + y, queue) if largest < ...
d6d7a782eac220b5e57e5fe58d4edf16f3c07f5d
683,122
def memoize(cls, method_name): """Memoizes a given method result on instances of given class. Given method should have no side effects. Results are stored as instance attributes --- given parameters are disregarded. :param cls: :param method_name: .. note: original method is stored as <cls>.m...
1a899967b4565f6093d8b2017e434078045bc901
683,123
def read_database(file_name): """ Read the method templates from a file. The first line contains the arguments for this method. All other lines contain the methods body. """ with open(file_name, 'r') as file_obj: lines = file_obj.readlines() methods = {} name = '' for line ...
6419b72e26957e50ba7867075b041f2b128136a9
683,124
def _derive_module_name(ctx): """Gets the `module_name` attribute if it's set in the ctx, otherwise derive a unique module name using the elements found in the label.""" module_name = getattr(ctx.attr, "module_name", "") if module_name == "": module_name = (ctx.label.package.lstrip("/").replace(...
26eb19b2f24ccf22c0387f14aff4caafb3cc63f2
683,125
def inr(value): """Formats value as INR.""" return f"₹{value:,.2f}"
cef7e68eedf508fd1990d6f9d315a032aabbfaf3
683,126
def list_sigs(sigs): """ List all current SIGs """ result = [] for sig in sigs: result.append(sig['name']) return result
ef1ab1662c91095ebe0626a8164f1128dbf2071c
683,127
def extract_folder_base_name(folderBaseName): """ Gives a pure folder base name for depth (without / and \\) :param folderBaseName: :return: """ if folderBaseName[-1] in ('/', '\\'): folderBaseName = folderBaseName[:-1] if folderBaseName[0] in ('/', '\\'): folderBaseName = fo...
319847537834414540cfcfd3a243edb407d9bbd6
683,128
def metadata_string(amr): """ # ::id sentence id # ::tok tokens... # ::node node_id node alignments # ::root root_id root # ::edge src label trg src_id trg_id alignments """ output = '' # id if amr.id: output += f'# ::id {amr.id}\n' # tokens ou...
948cb99817e7f7bcca896d933891abb33091ae44
683,130
import json def fetch_json_from_path(path): """Helper method to fetch json dict from file Args: path: Path to fetch json dict Returns: dict: JSON object stored in file at path """ if path is not None: with open(path, "r") as file: return json.load(file) else...
caff785cef7b29378cfd1e7601155a1a1635fd3c
683,131
from typing import List from typing import Dict def convert_row(list: List[Dict], order: int, is_subset: bool): """ list: testPaths or rest in response to a get subset API order: start number of order is_subset: in subset or not """ return [[order + i, "#".join([path["type"] + "=" + path["name...
819dff3e4a2dbb4e35e296320cfc2c3ccd4ddfae
683,132
def back_num(num: int) -> bytes: """Set terminal background color to a numbered color (0-255).""" return b"\x1b[48;5;%dm" % (num)
32405872e9a5afcc9c95c7ebb083dfe492e70d01
683,133
def build_testset_surprise(dataset): """ Build a test set from a Surprise Dataset so that it can be used for making predictions and model evaluation. """ testset = dataset.build_full_trainset().build_testset() return testset
c0429196d95eae3e79e92e1d545294aea4984ddc
683,135
def join(li): """:returns: list of objs joined from list of iterable with objs. >>> join([[1,2], [3], [4,5]]) [1, 2, 3, 4, 5] """ result = [] for iterable in li: for obj in iterable: result.append(obj) return result
9ca10dc57d120d32f2af90abd6c39d4bf7a16466
683,136
def add_alternative_source(transfer, alt_source): """ Adds an alternative source to a transfer Args: transfer: A dictionary created with new_transfer alt_source: Alternative source Returns: For convenience, transfer """ transfer['sources'].push_back(alt_source) re...
215a7473edc1139d95d81be3c7ee71dc7ab6a7ba
683,137
def ComputeQ(node_weights): """ Computes the value of Q (sum of node weights) given the node weights of a graph. """ return node_weights.sum()
05672096e41861f2ab9f240b733bc65eb78ea2f6
683,138
import glob import csv import fnmatch import sys def get_pid_file_list(file, directory, appliance): """Get a list of PID files""" # Build list of pid files if file == None: file_list = glob.glob(directory + appliance + '.pid') else: file_list = [] try: with open(f...
e3c774551e6b09205acc5ef37a82b0299cd56d99
683,140
def _column_sel_dispatch(columns_to_select, df): # noqa: F811 """ Base function for column selection. This caters to columns that are of tuple type. The tuple is returned as is, if it exists in the columns. """ if columns_to_select not in df.columns: raise KeyError(f"No match was return...
1d8f9ffc79ceec0ee0bfdd8c3402bbd98dc30d5f
683,141
def check_3d(coo, Lx, Ly, Lz, cyclic): """Check ``coo`` in inbounds for a maybe cyclic 3D lattice. """ x, y, z = coo OBC = not cyclic inbounds = (0 <= x < Lx) and (0 <= y < Ly) and (0 <= z < Lz) if OBC and not inbounds: return return (x % Lx, y % Ly, z % Lz)
aa9ef8d82002fe40bef4d58b3e21b6fb43402609
683,143
def get_isbn(raw): """ Extract ISBN(s). @param raw: json object of a Libris edition @type raw: dictionary """ identified_by = raw["mainEntity"].get("identifiedBy") if identified_by: isbns = [x for x in identified_by if x["@type"].lower() == "isbn"] return [x...
55f4f0ea6d8b1b70544dc5b74f703646427f1f81
683,144
from datetime import datetime def transform_datetime(dt): """ converts datetime parameter""" if dt is None: dt = '' else: assert isinstance(dt, datetime) dt = dt.strftime('%Y-%m-%d %H:%M:%S') return dt
1dc0c5fd1da20843023641306201c956f3d2706c
683,145
def has_any_labels(revision, labels): """ Return true if any labels are present. """ for label in labels: if label in revision: return True return False
504f3e07da0a8a30e6fc6138ba8c61770933b81c
683,146
def parse_parent(docname): """ Given a docname path, pick apart and return name of parent """ lineage = docname.split('/') lineage_count = len(lineage) if docname == 'index': # This is the top of the Sphinx project parent = None elif lineage_count == 1: # This is a non-inde...
70bdf557325e04bd85a194b40ceccf3dd3722b19
683,147
def isDonor(NMDP_ID): """ Check if the NMDP_ID is a donor or a recipient Donor: 4-4-1 Recipient: 3-3-1 With the function readBMTinfo(), this function became obsolete. """ if NMDP_ID.index("-") == 4: return("D") else: return("R")
28a47038807fe3c3c8da34ff949d934d9fa7c5c5
683,148
from datetime import datetime def s_ago(ft: float) -> str: """ Calculate a '3 hours ago' type string from a python datetime, if time less than 5 days, otherwise, return date as day/month/year """ units = { 'days': lambda diff_t: diff_t.days, 'hours': lambda diff_t: int(diff...
a0a1cf7b8b105c3da9da3619fa521bd5fa5c0674
683,149
def resolve_mutation_tracker(mutation_tracker): """ From a dictionary with comma separated keys (e.g. {'a.b.c.d': 'e'}), creates a new dictionary with nested dictionaries, each of which containing a key taken from comma separated keys. (e.g. {'a': {'b' {'c': {'d': 'e'}}}}) :param mutation_tracker: the ...
df28b3b7fe67c1b1e7654e113b80ca745d9b434e
683,150
def untrack_cache_storage_for_origin(origin: str) -> dict: """Unregisters origin from receiving notifications for cache storage. Parameters ---------- origin: str Security origin. """ return { "method": "Storage.untrackCacheStorageForOrigin", "params": {"origin": ori...
629487b59edf5e528eff766a9c36d2ad468ef1b1
683,151
def reverse_id(vid): """ :func:`reverse_id` will convert cell id into x, y tuple coordinate that read able for human. :param vid: - :class:`int` cell id return: :class:`tuple` """ binary = f"{vid:b}" if len(binary) < 30: binary = "0" + binary xcord, ycord = binary[15:], binary[...
07a2058da242c3fb4e09cacec7547eabb9e47524
683,152
def _get_config_option(parser, section='stere', option='', default=''): """Get an option from a config section, if it exists. Arguments: section(str): The name of the section option(str): The name of the option Returns: str: The found value, or else the default value """ if...
3c124eea50067318e320de32e5ce9fa85e6083af
683,153
import socket def get_fluentd_syslog_src_port(): """ Returns a TCP/UDP port number that'll be supplied to the fluentd syslog src plugin (for it to listen to for syslog events from rsyslog/syslog-ng). Ports from 25224 to 25423 will be tried for bind() and the first available one will be returned. 25224...
e815e5385a2d25bfd1221448687c2f87832b5edf
683,154
def string_to_bool(arg): """Converts a string into a returned boolean.""" if arg.lower() == 'true': arg = True elif arg.lower() == 'false': arg = False else: raise ValueError('ValueError: Argument must be either "true" or "false".') return arg
279c764d0a2a7b10aca291dc6a13103219e106c6
683,155
def all_subsets(aset): """Solution to exercise C-4.15. Write a recursive function that will output all the subsets of a set of n elements (without repeating any subsets). -------------------------------------------------------------------------- Solution: --------------------------------------...
bc8aa785303510bed33a56c859d4154e4f4045c5
683,156
import os def join_fix_case(good_base, *parts): """Returns a unix-type case-sensitive path of the joined parts. An empty string is returned on failure: file not found.""" # check if input is already correct joined_input = os.path.join(good_base, *parts) if os.path.exists(joined_input): return joined_input co...
5562b879cec7eb50571bbeaee36c3e697b459060
683,158
def should_retry_facebook_batch(facebook_batch) -> bool: """ Returns True when all the failed requests, if any, are transient errors. Otherwise False. :return: a boolean. """ return any( error.is_transient if error else False for error in facebook_batch.errors )
edd3dab98db6dd61c3770ee79338ef7e1cf39f20
683,159
def is_space_free(board, move): """Return true if the passed move is free on the passed board.""" return board[move] == ' '
5d2ebdc6747237448989bf6abf215b2c53c570d2
683,160
def check_module(nwbfile, name, description=None): """ Check if processing module exists. If not, create it. Then return module. Parameters ---------- nwbfile: pynwb.NWBFile name: str description: str | None (optional) Returns ------- pynwb.module """ if name in nwbfil...
605d2672524f5ac033d51c08fab7e5f39e80e7cc
683,161
def _count_righthand_zero_bits(number, bits): """Count the number of zero bits on the right hand side. Args: number: an integer. bits: maximum number of bits to count. Returns: The number of zero bits on the right hand side of the number. """ if number == 0: return...
e174ecc79b27592323084bbda0ab993c9ba292ad
683,162
def swap_links(F1, F2): """ Obtains the fidelity of a link produced using entanglement swapping assuming Werner states :param F1: type float Fidelity of link 1 :param F2: type float Fidelity of link 2 :return: type float Fidelity of the link produced by swapping link 1 and 2 ...
33c044ea772f4022b0f347adc8b2501c7ebe6160
683,163
import os def string_from_file(string, strip=True): """ Return an unaltered string or the contents of a file if the string begins with @ and the rest of it points at a path. If 'strip' is True, remove leading and trailing whitespace (default behavior). """ if not isinstance(string, str):...
7d1e16e043273e59ac61e0f4d0409955964954b4
683,164
import numpy def reshape_vector(ndarr): """ :param ndarr: take list and transform it to a ndarray with reshape :return: numpy array of numpy array """ if not isinstance(ndarr, numpy.ndarray): # If ndarr is not a ndarray raise exception msg = 'This is not a ndarray type: type{}'.for...
ffda639aa8c5409e3821e53773c2ec1b3f6925a4
683,165
import tempfile import zlib import sqlite3 import os def download_batch(zkclient, db_node_path, table, name): """Download snapshot DB and select matching rows. """ events = [] data, _metadata = zkclient.get(db_node_path) with tempfile.NamedTemporaryFile(delete=False, mode='wb') as f: f.wri...
c3f85cfdf1d4e067e7331b8baf30876b28011c5e
683,166
def toposort(tasks): """Simple topological sort routine for task lists. Not fast, but easy - especially leaves nodes in original order if already topologically sorted. Dependencies that are not in the tasks list are ignored for the purpose of the sort. """ tasks_set = set(tasks) tasks_out =...
66c6c8a4ccb1312c628d7b15528badacb3fd8ec0
683,167
def base_convert(space, w_number, frombase, tobase): """ base_convert - Convert a number between arbitrary bases""" # problem with big numbers # php casts 10000000000000000000 to 1.0E+19 # py casts to 1e+19 so we are missing '0' ;-) if w_number.tp == space.tp_array: space.ec.notice("Array to...
e96c4b03aad867dc893d4e01ec340daa9116f0c1
683,168
def remove_contraints(Ca, Lambda): """ Retire de Ca les contraintes de Robinson dont le Lambda est négatif """ removed=False # print 'contraintes_removed' nb=0 for lambda_elements in Lambda: if lambda_elements[0]<0: #print lambda_elements[1] Ca.remove(lambda_elements[...
53e3e42f6b78ae4032c4a417cdfed45e0abf590a
683,169
def _makes_clone(_func, *args, **kw): """ A decorator that returns a clone of the current clom object. """ self = args[0]._clone() _func(self, *args[1:], **kw) return self
16834b5bd311e5b6bf95be6f79f9bc5ad7e43eb9
683,170
import os def file_name(file_dir): """ Find the all file path with the directory Args: file_dir: The source file directory Returns: files_path: all the file path into a list """ files_path = [] for root, dir, files in os.walk(file_dir): for name in files: ...
4575fc3dfde2d0be8d838d2574005e1ec02b16de
683,171
def quiz_question_change(statement): """ Get link for a quiz question update. :param statement: the xAPI statement :return: The url location. """ return '/assistants/api/question_sync_agent/'
3cf745c984e3fbaa6ded7d42c3548b78511567aa
683,172
import random def get_uniform_mutation_function(minimum, maximum): """ Returns a function that returns a value drawn from a uniform distribution over the closed interval [minimum, maximum]; see :ref:`mutation-functions` :Valid For: any gene type :param minimum: the minimum allowed value ...
c9225f92f17111c6a176d05fe335959da7a8a50f
683,173
def disassemble_binary_with_byte_offset(binary): """ Disassemble binary with byte offset of each instructions. Standard Chip-8 Instructions From: http://devernay.free.fr/hacks/chip8/C8TECH10.HTM :param binary: binary file to be parsed :return: string containing parsed opcodes of given binary. ...
59438b659c6a571461bcce0bebec7c8bbb379dd7
683,174