content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import os.path as op import shutil def rename_feat_dir(feat_dir, task): """ Renames the FEAT directory from fsl.FEAT. Mimicks nipype.utility.Rename, but Rename doesn't work for directories, and this function *does*. Parameters ---------- feat_dir : str Path to feat-directory (outpu...
a020a4a9ed04232a3594fced3efd953e6271702c
680,357
def flatten_list(nested_list): """ Given a list of lists, it flattens it to a single list. :param nested_list: list of lists :return: Single list containing flattened list. """ return [item for sub_list in nested_list for item in sub_list]
c0f7bedb4cf776ca1b57c99eec37fc49d5334026
680,358
def weight_distrib(full, weights): """ Return a list of integers summing up to full weighted by weights The items are approximately proportional to the corresponding weights. """ if full == 0: return [0] * len(weights) elif not weights: return [] sw = float(sum(weights)) ...
a3c2583f80149e7a1a2a72f535bf7bf0e462e5a3
680,359
from typing import Dict import os def parse_condor_job_ads() -> Dict[str, str]: """Parse on going Condor job ads.""" jobad_fpath = os.environ.get("_CONDOR_JOB_AD") # --------------------------- # Check if we are running inside Condor if not jobad_fpath: return dict() # ----------------...
e7cb7be53d8b56dcad793a67073f43894dd8837f
680,360
def mask(type) : """ Fonction qui génère la matrice de masque en fonction du type mat_mask = mask(type) Paramètre d’entrée : ------------------- type : code compris entre 0 et 7 type de masque à générer Paramètre de sortie : ------------------- mat_mask : matrice 21...
00f1746701fb0542fcb54fd92b9493ddbfc59f34
680,361
def ExpiryMonth(s): """ SPX contract months """ call_months = "ABCDEFGHIJKL" put_months = "MNOPQRSTUVWX" try: m = call_months.index(s) except ValueError: m = put_months.index(s) return m
76e633b3eeb86f7701d4a4bcefc1cbf772015ea2
680,362
def rn_sub(a, b): """ a - b uses rn_sum and rn_neg to get the difference like a + (-b) :param a: RN object :param b: RN object :return: difference array """ return a + (-b)
483bdcaab4121139f967057082c362e89409093a
680,363
from typing import Any import copy def bubble_dict(target: dict, *keys: Any): """ rebuild dict and bubble the keys to top """ copy_dict = copy.copy(target) new_dict = dict() for key in keys: value = copy_dict.pop(key) new_dict.update({key: value}) new_dict.update(copy_dict)...
28dbf2ec0a99b21aa7d8f2c63fa6696a1e39c473
680,364
import tempfile import os def topdir(): """Get the absolute path to a valid rpmbuild %_topdir.""" top = tempfile.mkdtemp(prefix='rpmvenv') os.makedirs(os.path.join(top, 'SOURCES')) os.makedirs(os.path.join(top, 'SPECS')) os.makedirs(os.path.join(top, 'BUILD')) os.makedirs(os.path.join(top, 'RP...
3eb2f9ce2086b91bfd1d5fdfd9c0832426342ba7
680,365
def get_bookmarks_list(html): """Function to return this first dl tag in the passed html. For bookmarks exported from Firefox to html. """ first_dl_tag = html.find_all('dl')[0] return first_dl_tag
30532f20c36920fcb314c2bcb753fe8736297708
680,366
def split_sig(params): """ Split a list of parameters/types by commas, whilst respecting brackets. For example: String arg0, int arg2 = 1, List<int> arg3 = [1, 2, 3] => ['String arg0', 'int arg2 = 1', 'List<int> arg3 = [1, 2, 3]'] """ result = [] current = '' level = 0 f...
054e339410978d055a3873ee240b08b0c388fa21
680,367
def consistency_events(tidy, verbose=10): """Check the consistency of the events. Ensure that an event has only one True value. rule: np.sum(event) <= 1 .. note: It depends on the events. Some events such as event_admission or event_enrolment should have only one value. Howe...
25b315b692383f070345a63b86d5c96056517c8e
680,368
def get_repo_dpath(repo_name, tmp_root, suffix=""): """Get the repo path.""" dpath = "{}/{}".format(tmp_root, repo_name) if suffix: dpath = "{}_{}".format(dpath, suffix) return dpath
6ff948f5c22b448df08092d7b7e0d5ae30e69761
680,369
def translate_fields(old, translation_table): """Returns a new list of field names based on a translation table.""" result = list() for field in old: if field in translation_table: result.append(translation_table[field]) else: result.append(field) return result
2fc9f8bf7cd6ec079f4a9fe8a55523efdc23c1fd
680,370
def sum_factorial_digits(x): """ Returns the sum of the factorials of the digits of x """ factorials = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880] sum_factorial_digits_ = 0 for i in str(x): sum_factorial_digits_ += factorials[int(i)] return(sum_factorial_digits_)
421dcd734224ee691054bcb032c296bb0006d189
680,371
def resistances(dlib, labels): """ Extract plasmid type """ pl = {} for design in dlib: plasm = dlib[design][1] pl[design] = labels[ plasm ] return pl
64d04ac9e0e34c026e2a267790bf2074088365fc
680,372
import sys import json def get_configurations(): """ Load config json from first command line argument :return: """ config_file = sys.argv[1] with open(config_file) as data_file: configs = json.load(data_file) if "data_folder" not in configs: print("[Config Missing] : data_...
30138ff5b0094226ffa9da77a78beed636174fbf
680,374
def convert2asciii(dictionary): """ Changes all keys (i.e. assumes they are strings) to ASCII and values that are strings to ASCII. Specific to dictionaries. """ return dict([(key.encode('ascii','ignore'),value.encode('ascii','ignore')) if type(value) in [str,bytes] else ...
2e4643adcea466819072f57f490ac8dc0ada8e62
680,375
import random import time def retry(initial_delay, max_delay, factor=2.0, jitter=0.25, is_retriable=None): """Simple decorator for wrapping retriable functions. Args: initial_delay: the initial delay. factor: each subsequent retry, the delay is multiplied by this v...
4c62282671d46e1eb1d1720a84f6792380c21995
680,376
def fixup_acl(acl: str) -> str: """ Replace standard ip/mask entries with "none" and "any" if present """ if acl is None: acl = "none" if acl == '': acl = "none" if acl == "255.255.255.255/32": acl = "none" if acl == "0.0.0.0/0": acl = "any" return acl
a9c983ba5e76089d90d1fa551043615d1f449a45
680,377
import pathlib import shutil import os def copy_any(src, dest_folder, *, overwrite=False): """Copy a source file or directory to a destination folder ``src`` must refer to an existing file or directory. The destination ``dest_folder`` must be an existing folder. A new file or subdirectory, named ``o...
dadaa8033202b76778ce75d9362d01d9125fc2b1
680,378
import aiohttp import base64 async def render(eqn: str, **kwargs) -> bytes: """ Render LaTeX using Matthew Mirvish's "TeX renderer slave microservice thing". Returns raw image data or raises ValueError if an error occurred. """ kwargs["source"] = eqn async with aiohttp.request("POST", "http:/...
c53a8cd5639f854301fafea72902f11427ca6dab
680,379
from typing import Tuple def one_pos_two_pos( x: int, y: int, width: int, height: int, anchor: str ) -> Tuple[int, int, int, int]: """Convert: x, y, width, height -> x1, y1, x2, y2""" if anchor == "ce": x1 = x - int(width / 2) x2 = x + int(width / 2) y1 = y - int(height / 2) ...
2351a8a8667132280f1d14c3e7f7d8a126d7bdd1
680,380
import re def sanitize(s): """ Remove escape codes and non ASCII characters from output """ ansi_escape = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]') s = ansi_escape.sub('', s) mpa = dict.fromkeys(range(32)) return s.translate(mpa).strip().replace(' ', '')
515057bba7eb1edc8066c9a9b1bf77589ad058cd
680,381
def get_max_region(regions, field='area'): """Return the region from the list that maximizes the field.""" max_region = regions[0] for i in range(1, len(regions)): if regions[i][field] > max_region[field]: max_region = regions[i] return max_region
69bcaface96b455fe411c578952c8dff251f291e
680,382
def get_bucket_config(config, bucket_name): """ Pulls correct bucket config from application config based on name/alias. Args: config(dict) bucket_name(string): bucket name or bucket reference name Returns: dict | None: config for bucket or None if not f...
fd742cd7c7484c51b3bb7a15003528834046fea7
680,383
def _has_dns_message_content_type(flow): """ Check if HTTP request has a DNS-looking 'Content-Type' header :param flow: mitmproxy flow :return: True if 'Content-Type' header is DNS-looking, False otherwise """ doh_content_types = ['application/dns-message'] if 'Content-Type' in flow.request...
67bf9d5c4c1106961114459b750c87a2b496a7c5
680,384
def cast_to_str(labels, nested=False): """ Convert every label to str format. If nested is set to True, a flattened version of the input list is also returned. Args: labels: list Input labels nested: bool Indicate if the input list ...
7e5b74a137ca3dfa06c50b1c3d680befd29a617d
680,385
def binary_string_to_int(s): """ Convert a string of a binary representation to a number :param s: a binary representation as a string :return: an integer """ return int(s,2)
5aeebf045ce25164369b92c98020f6db5c200e32
680,386
def optimal_merge_pattern(files: list) -> float: """Function to merge all the files with optimum cost Args: files [list]: A list of sizes of different files to be merged Returns: optimal_merge_cost [int]: Optimal cost to merge all those files Examples: >>> optimal_merge_pattern([2...
724e9a380df3967e127c6e4d389a2aaedd3c4ae3
680,387
def TransitionEvent( state_table ): """Decorator for defining a method that both triggers a transition and invokes a state dependant method. This is equivalent to, but more efficient than using @Transition(stateTable) @Event(stateTable) """ stateVarName = state_table.inst_state_name def wrappe...
1820224cfd29c2550ab34847251045f327bedfef
680,388
import base64 import os import re def getContainerName(job): """ Create a random string including the job name, and return it. Name will match [a-zA-Z0-9][a-zA-Z0-9_.-] """ parts = ['toil', str(job.description), base64.b64encode(os.urandom(9), b'-_').decode('utf-8')] name = re.sub('[^a-zA-Z0-9...
38ce55410a850121c03c614d8aa983f11ac46266
680,389
import math def rotate_point(point, angle, center_point=(0, 0)): """Rotates a point around center_point(origin by default) Angle is in degrees. Rotation is counter-clockwise https://stackoverflow.com/questions/20023209/function-for-rotating-2d-objects """ angle_rad = math.radians(angle % 360)...
ea439535a628fae0ec90560c3a1e6e49daa91616
680,390
def serialize_actividad_laboral(actividad_aboral, tipo): """ $ref: '#/components/schemas/actividadLaboral' """ clave = "OTRO" if actividad_aboral: return { "clave": actividad_aboral.codigo, # actividad_aboral.clave, "valor": actividad_aboral.ambito_laboral, #actividad...
1d60e738b5d32b8ef9e6f28e899acde59aecd6c9
680,391
def calculate_mean_density(mean_densities) : """ Обчислює середнє значення густини """ mean_density = 0 number_of_non_zero_densities = 0 for i in range(0, mean_densities.size) : if mean_densities[i] != 0 : mean_density += mean_densities[i] number_of_non_zero_densities += 1 if number_of_non_z...
a61ddcdefce790804eb7405e8f6377345735cc6b
680,392
def total_mass(particles): """ Returns the total mass of the particles set. >>> from amuse.datamodel import Particles >>> particles = Particles(3) >>> particles.mass = [1.0, 2.0, 3.0] | units.kg >>> particles.total_mass() quantity<6.0 kg> """ return particles.mass.sum()
2865105a8813eeaa3e77da6056051e8605a6e32d
680,393
def isSameTree(p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p and q: return p.val == q.val and isSameTree(p.left, q.left) and isSameTree(p.right, q.right) return p is q
0cdf2ce3458cb8cc65c9be591a6fa97eb652dc31
680,394
def cli(ctx, history_id, gzip=True, include_hidden=False, include_deleted=False, wait=False, maxwait=""): """Start a job to create an export archive for the given history. Output: ``jeha_id`` of the export, or empty if ``wait`` is ``False`` and the export is not ready. """ return ctx.gi.hist...
35e131c11b4812e48977ae483c52a18f3ae98d14
680,395
def _str_to_int(_str): """Convert the input str to an int if possible :param _str: input string :return: integer if text is a digit, else string """ return int(_str) if _str.isdigit() else _str
07fc15199455ed611fa678efe51d94d35791b8b2
680,396
import hashlib def cache(): """ Caching decorator for caching the result of a function called on an object. If not in cache call the underlying function, then case the result """ def _cache(function): def __cache(*args, **kw): fstring = function.__name__.encode('utf-8') ...
72d4c8a0c0d4412dedf895a05b82620c0de0da99
680,397
def proto_to_bytes(proto): """ Converts a proto object to a bytes array """ return proto.SerializeToString()
2e4b00727851131eb367385e9dec69fd2427cc96
680,398
def solve1(ins_set): """Execute the instruction set <ins_set> and return the last value of the accumulator before an infinite loop (or before the normal conclusion of the program). """ acc = 0 executed = set() i = 0 while i < len(ins_set): if i in executed: break ...
16970ee33e7749efe784d9a8ebdb1ecd9901a5ef
680,399
def next_tox_major(): """a tox version we can guarantee to not be available""" return "10.0.0"
bdf493e41f62804524c06bc3dfad743100c01fd1
680,402
def triedtools () : """ Le module triedtools regroupe les différentes méthodes suivantes : centree : Centrage de données centred : Centrage et réduction des données decentred : Décentrage et déreduction de données normrange : Normalisation sur un intervalle [a...
9bb40da375266ae7f5a9bb2c92f335d047b204bb
680,403
import os import hashlib def get_file_md5(file_name): """[calculate file hash md5] """ if os.path.isfile(file_name): file_content = open(file_name, 'rb') contents = file_content.read() file_content.close() md5 = hashlib.md5(contents).hexdigest() else: md5 = None...
d164415794a8a0eaf3f1666ed85a1513bd3501e0
680,404
def exist_column(table_name, col_name, session): """find if column col_name exist""" sql = 'select * from ' + table_name + ' where collection_id = -1' res = session.execute(sql).fetchall()[0] return col_name in tuple(res)
85f3e02315487997d34ac4220c5bc842081c8e2e
680,405
def gen_key_i(i, kappa, K): """ Create key value where key equals kappa, except: key_(i mod n) = kappa_(i mod n) XOR K_(i mod n) Parameters: i -- integer in [0,n-1] kappa -- string K -- string Return: key -- list of bool """ # Transform string into list of booleans kappa = list(kappa) kappa = [boo...
93b69742cc2476b93d2d568ab21bb0f4af276e95
680,406
import os def open_here(filename, encoding='UTF-8'): """Open a file in the same directory as this module.""" here = os.path.dirname(__file__) return open(os.path.join(here, filename), encoding=encoding)
8e1a15292950ed1ad181920cae62b19820209aba
680,407
def find_containments(seed_polygon, target_polygons): """ A function that finds intersections between a seed polygon and a list of candidate polygons. Args: seed_polygon (shapely polygon): A shapely polygon. target_polygons (list): A list of shapely polygons. Returns: array...
2655a6ad52e5d2501695e68afc1ce7d651666d4e
680,408
def compute_op2d_padding(): """ Dummy function, needed for API. Returns: None """ return None
8ef5c1b9d3c25c69c509d46b9c9a8b5deca6eb51
680,409
def get_intent_queries(infold, intent_names, mode): """ Get list of queries with their corresponding intent number. """ intent_queries = ['sentence\tlabel\n'] for index, intent in enumerate(intent_names): queries = open(f'{infold}/{mode}set/{intent}.csv', 'r').readlines() for query in queri...
f4fa21859874f68adfcadbe20b5dea925556c56a
680,411
from typing import Tuple def irot(x: int, y: int, deg: int, origin: Tuple[int, int] = (0, 0)) -> Tuple[int, int]: """ Rotate an integer point by `deg` around the `origin`. Only works when deg % 90 == 0. """ transformed_x = x - origin[0] transformed_y = y - origin[1] assert deg % 90 == 0 fo...
49b47e7ffc70c08d72f4af1189b16f28038f300d
680,412
def lsearch(l,pattern): """ Search for items in list l that have substring match to pattern. """ rvals = [] for v in l: if not v.find(pattern) == -1: rvals.append(v) return rvals
e49d5cbf17d2e7c7b6e5bdf0c1c66e481760db82
680,413
def count_interval_index(arr1d, lower, upper): """ calculates the total number of scenes which are underflooded depending on an threshold interval considering the total number of available scenes ---------- arr1d: numpy.array 1D array representing the time series for one ...
c8e6bfd3bcec29b7be1a5ba4fc489a5bbee9fdd6
680,414
def parse_to_short_cmd(command): """Takes any MAPDL command and returns the first 4 characters of the command Examples -------- >>> parse_to_short_cmd('K,,1,0,0,') 'K' >>> parse_to_short_cmd('VPLOT, ALL') 'VPLO' """ try: short_cmd = command.split(',')[0] return ...
6f1b69d6c3b642265fb13e72bf8b207123a24788
680,415
import hashlib def md5sum(path): """Return the MD5 hash of the file contents. """ BUF_SIZE = 1024 * 64 buf = bytearray(BUF_SIZE) mv = memoryview(buf) md5 = hashlib.md5() with open(path, 'rb') as fh: while True: num_bytes = fh.readinto(buf) md5.update(mv[:num...
6ac92d7074f650d1caa6246e18908ff9de032beb
680,416
def allowed_file(filename, extensions): """ chceck if file extension is in allowed extensions :param filename: name of file :param extensions: allowed files extensions :return: True if extension is correct else False """ return '.' in filename and filename.rsplit('.', 1)[1].lower() in extens...
447c7cafebf501d69f45ec123589d25ac06cb2c0
680,417
import os import sys import pathlib def create_file_list(searchpath='None', ending='cif'): """ walks through the file system and collects cells from res/cif files. Pathlib is nice, but does not allow me to do rglob for more than one file type. """ if not os.path.isdir(searchpath): print('s...
4b6e9837994aecf613793e8d85d809ea7d36c2b5
680,418
def getStructFormat(endian, datatype, bytesize): """ get struct's format Args: endian (string): using struct format datatype (string): data type name bytesize (number): member's data size """ target_format = endian format = '' format_size = bytesize if "char" == datat...
95c49b97a7e9b8e160312326fdb8a57a276c1cef
680,419
def parse_bool(val): """ Parse bool value from cli. Must be represented by integer number 0 or 1. Return: (bool) True/False """ try: val = int(val) assert val == 0 or val == 1, 'Wrong value: {}'.format(val) except: raise ValueError('Cannot parse flag {}. It must an ...
5faf07c03264ec94febff293b6503821fe824977
680,420
def type_of_errors(assignment) -> dict: """ Takes an assignment object and returns a dictionary of each of the types of errors made in the assignment, and how often they were made by all students. """ errors = {} for problem in assignment.problems.all(): for error in pro...
a23943d5188ee74cda0e63703d34a2add5e4ce86
680,421
def is_list_or_tuple(x): """Return True if list or tuple.""" return isinstance(x, tuple) or isinstance(x, list)
0857f275f9daf5535145feb29cf360e98d912fdd
680,422
def MaskedLayerNorm(layerNorm, input, mask = None): """ Masked LayerNorm which will apply mask over the output of LayerNorm to avoid inaccurate updatings to the LayerNorm module. Args: layernorm (:obj:`~DeBERTa.deberta.LayerNorm`): LayerNorm module or function input (:obj:`torch.tensor`): The input tenso...
2834a1c9e49c500fa83fb7aa38d82752c25b2b27
680,423
import re def camel_case(s: str) -> str: """Return a camel case version of `s`.""" # "us"?-doesn"t seem to be there, probably need others leave_alone = ( "mm", "cm", "km", "um", "ms", "ml", "mg", "kg", ) words = [ w.capitaliz...
e6b75cfc789e22667295964998071ae9dff8a383
680,424
def credit_given(file_paths): """Check if Misc/ACKS has been changed.""" return True if 'Misc/ACKS' in file_paths else False
5063ad56a8f159d7dea97623a02c03cc188b0efa
680,425
import torch def get_box_attribute(probability): """ Return the argmax on `probability` tensor. """ return torch.argmax(probability, dim=-1)
1edca219b316e1e6d53378c492f471691227fe1f
680,426
def parse_arg_array(arguments): """ Parses array of arguments in key=value format into array where keys and values are values of the resulting array :param arguments: Arguments in key=value format :type arguments: list(str) :returns Arguments exploded by = :rtype list(str) """ resu...
7158b1b2cfb754a19cbf430cd2287027c882d986
680,427
def get_json_data(json_dict): """ Parameters ---------- json_dict : :obj:`dict` QCJSON dictionary. Returns ------- :obj:`list` [:obj:`int`] Atomic numbers of all atoms :obj:`list` [:obj:`float`] Cartesian coordinates. :obj:`float` Total energy of the...
52b93f4a709213bcfd1c40f982abb14dd2c8eaf1
680,430
from typing import Dict from typing import Any from typing import Counter def extract_properties(mrchem_output: Dict[str, Any]) -> Dict[str, Any]: """Translate MRChem output to QCSChema properties. Parameters ---------- Returns ------- """ occs = Counter(mrchem_output["properties"]["orb...
ffc57549cc792e6e7fdfe77dda875c504a0e00df
680,431
def depth(tree, children_collection_name='subregions'): """Get tree depth.""" if tree is None: return 1 return max(depth(subtree) for subtree in getattr(tree, children_collection_name)) + 1
a12fc81217da2745b78400dcb387bb3eaface902
680,432
def get_total(shopping_list, prices): """ Getting shopping list and prices for goods in it, returns total cost of available products. >>> goods = {'Apple': 2.5, 'Pear': 1, 'Pumpkin': 1.5} >>> prices = {'Apple': 9.50, 'Pear': 23.80, 'Pumpkin': 4.50} >>> get_total(goods, prices) 54.3 If...
1232ee95ee924efc3226d56cce49bbc13e4ccab0
680,433
from typing import List from typing import Dict from typing import Any def sort_by_default(payloads: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Sort payloads by rating and then length length.""" return sorted(payloads, key=lambda k: (int(k["rating"]), len(k["payload"])), reverse=True)
7b604768028b7abed31cd9f45f67a80556d13460
680,434
def build_package_xml(settings, package_dict): """ Build Package XML as follow structure <?xml version="1.0" encoding="UTF-8"?> <Package xmlns="http://soap.sforce.com/2006/04/metadata"> <types> <met:members>*</met:members> <met:members>Account</met:members...
84bff451d3042ba400d86bec8338cda317004dfa
680,435
def increment_mean(pre_mean, new_data, sample_size): """ Compute incremental mean """ inc_mean = pre_mean + (new_data-pre_mean) / sample_size return inc_mean
137119d7239b87bb63b4cb91744b7e03ee318a43
680,436
def build_description(): """Build a description for the project from documentation files.""" try: readme = open("README.md").read() changelog = open("CHANGELOG.md").read() except IOError: return "<placeholder>" else: return readme + "\n" + changelog
6b03ffa4257e30d8f48f65b2d27b17bb80edc677
680,437
import re def str_expr_replacement(frm, to, expr_string, func_ok=False): """ replaces all occurences of name 'frm' with 'to' in expr_string ('frm' may not occur as a function name on the rhs) ... 'to' can be an arbitrary string so this function can also be used for argument substitution. This fun...
2969d48295b2f13b499c39baa2f476de45e4b80e
680,438
def create_index_query(node_type, indexed_property): """ Create the query for the index statement. See: https://neo4j.com/docs/cypher-manual/current/indexes-for-search-performance/ """ print(f'CREATE INDEX ON :{node_type}({indexed_property});') return f'CREATE INDEX ON :{node_type}({indexed_property...
2f73b64cd1fc00ad1dcdffa155b444923d304169
680,439
def consistency_data(request): """Create consistency data""" return request.param
9e6fc5842f3b474b21d294bf7dcb7e16c8f8ba45
680,440
def get_indexes(dfobj, value): """Get a list with location index of a value or string in the DataFrame requested. Parameters ---------- dfobj : pandas.DataFrame Data frame where the value will be searched. value : str, int, float String, integer or float to be searched. Ret...
1b149bec6e5188609ace2eadd6e35aad833f4306
680,441
import inspect def unwrap_fullargspec(func): """recursively searches through wrapped function to get the args""" func_dict = func.__dict__ if "__wrapped__" in func_dict: return unwrap_fullargspec(func_dict["__wrapped__"]) else: return inspect.getfullargspec(func)
e96c5e7f439c5f1ebb95631edec7de20de5320d0
680,442
def opts2w2vfcmdstr(opts): """Prints command line options in word2vecf format.""" cmdstr = "" for opt, val in opts.items(): if val is not None: act=" -%s %s "%(opt,str(val)) cmdstr+=act return cmdstr
a299ca4db5333a4d416b1ad8234b6e7c73044767
680,443
def project_length_in_ns(projnum): """Returns a float with the project length in nanoseconds (ns)""" w = {} # 7 fragment hits w[14346] = 1.0 # RL w[14348] = 10.0 # L # 100 ligands w[14337] = 1.0 # RL w[14339] = 10.0 # L # 72 series for i in range(14600, 14613): ...
1be68d051389680a9ad743e0c3289eb2e638dd0e
680,444
def protocol(site_client, device_a, interface_a, circuit, protocol_type): """ Return a Protocol Object. """ device_id = device_a['id'] interface_slug = interface_a['name_slug'] return site_client.sites(site_client.default_site).protocols.post( { 'device': device_id, ...
764db5af55b2ffc258ecefda3755d06d0e1dff91
680,445
def get_alignment (filename, reverse ="False"): """Find the alignments between source language and target language. Create alignment dictionary.""" align_dict = {} sentence_cnt = 1 print("get alignment") with open(filename) as f: for line in f: sentence = line.split() ...
21248d73c94cad67d61fb1920c7748365e8e5611
680,446
import requests def search_lobid(row, qs_field='query'): """ sends the value of the passed in field to lobid and returns the results in a dict """ query = row[qs_field] result = { 'query': query, 'status': 0, 'error': "", 'hits': 0, 'gnd': [] } r = requests....
0343d181875c140950e88c0c4c808d51b4777337
680,447
def squared_error(prediction, observation): """ Calculates the squared error. Args: prediction - the prediction from our linear regression model observation - the observed data point Returns: The squared error """ return (observation - prediction) ** 2
ed527984eeb79c485ab3bb81def8f1aaa45363ac
680,448
from typing import Counter def recover_message(messages, least_frequent=False): """For each position in the recovered message, find the most- (least-) frequently-occurring character in the same position in the set of raw messages. """ i = len(messages) if least_frequent else 1 return ''.jo...
90349dc430602b683994c05ce917e3ff0ba3140e
680,449
from collections import Counter def get_most_often_item(items=[]): """ :param items: item list to find out the most frequently occurred :return: one object from the item list """ if len(items) == 0: return 'Not existed' item_counter = Counter(items) most_popular = item_counter.mo...
0b4c6dd3f857ba984eb78252a431328ab150a298
680,450
def undamaged_example( session_id, array_id, start, end, ): """ S03 P09, P10, P11, P12 2:11:22 4,090 P11 dropped from min ~15 to ~30 S04 P09, P10, P11, P12 2:29:36 5,563 S05 P13, p14, p15, P16 2:31:44 4,939 U03 missing (crashed) S06 P13, p14, p15, P16 2:30:06 5,097 ...
df4f72472f66165aaef97cd48907b90bbcd37563
680,451
import os def have_same_extesions(*args): """Determines whether all of the input paths have the same extension. Args: *args: filepaths Returns: True/False """ exts = [os.path.splitext(path)[1] for path in args] return exts[1:] == exts[:-1]
7f9436de913f232ce34f7b9987bbc7d5bdce5845
680,452
def strip_leading_zeros(version: str) -> str: """ Strips leading zeros from version number. This converts 1974.04.03 to 1974.4.3 as the format with leading month and day zeros is not accepted by PIP versioning. :param version: version number in CALVER format (potentially with leading 0s in date an...
4e4381d558d932dfd7644d2689b0d089cde82359
680,453
import json def _convert_value(val): """Handle multiple input type values. """ def _is_number(x, op): try: op(x) return True except ValueError: return False if isinstance(val, (list, tuple)): return [_convert_value(x) for x in val] elif v...
d5fc736f8b66082c8c14e1b1238548710ddd089b
680,454
import os import pickle def load_ref(load_name, mypath): """ This function loads the reference profile time series data and metadata from a previously saved pickle file. Parameters ---------- load_name: str Name of the pickle file to load. mypath: str Path to folder containing...
8bbf8b31eedfb6cdc458dd98c3f8c89f991e55a7
680,455
def tie_account_to_order(AccountKey, order): """tie_account_to_order - inject the AccountKey in the orderbody. An order specification is 'anonymous'. To apply it to an account it needs the AccountKey of the account. Parameters ---------- AccountKey: string (required) the accountkey ...
5046a7cb0d8f6dac27c413be9011c214fcc110cf
680,457
def renamefromto(row, renaming): """Rename keys in a dictionary. For each (oldname, newname) in renaming.items(): rename row[oldname] to row[newname]. """ if not renaming: return row for old, new in renaming.items(): row[new] = row[old] del row[old]
5da935a61b929408269f7e47ab3ea0c3e8009bce
680,458
import json def is_bootstrap(event): """ Determines if the message sent in was for an bootstrap action - Bootstrap (success) events are always just strings so loading it as json should raise a ValueError """ try: message = json.loads(event['Records'][0]['Sns']['Message']) if is...
40d66c461428c018420f7a2873dce2b08a60bbb3
680,459
def coincident(p, q, r): """[summary] Arguments: p (type): [description] q (type): [description] r (type): [description] Returns: [type]: [description] """ return r.incident(p * q)
8221bf844fe08b53dccf975f2e4f307c0befef25
680,461
from typing import Any import yaml def to_yaml_str(val: Any) -> str: """ :param val: value to get yaml str value of :return: direct str cast of val if it is an int, float, or bool, otherwise the stripped output of yaml.dump """ if isinstance(val, (str, int, float, bool)): return st...
4d8079c953e74da04041569d84880abeadeb59db
680,462
def remove_comments(line): """ Remove all comments from the line :param line: assembly source line :return: line without comments (; ....) """ comment = line.find(';') if comment >= 0: line = line[0:comment] return line
92a19ac6d1e3eb2114800b961ea41e6d94d6c7f2
680,463
def un_normalize_img_coords(cx, cy, w, h): """From the -1 1 to w h repr.""" cx = int((cx + 1) * w / 2) cy = int((cy + 1) * h / 2) return cx, cy
c971cbb8830bc07bda8ff1c0e3392f00ca39abf5
680,464