content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def coerceColType(colType): """ Given a colType, coerce to closest native SQLite type and return that, otherwise raise a ValueError. Parameters: colType (str): column type from DBML specification. Returns: str: valid SQLite column type. """ colType = colType.upper() n...
acff9fac321b26b1a3591eb81f2ce24997a130fd
672,832
def _jupyter_server_extension_points(): """ This function is detected by `notebook` and `jupyter_server` because they are explicitly configured to inspect the nbgitpuller module for it. That explicit configuration is passed via setup.py's declared data_files. Returns a list of dictionaries with met...
eda4fbe88cf78b77ccfebf939d330a0371a65c58
672,833
import pickle def read_file_data(name, input_path='/inputs'): """ Reading :param name: :return: """ filename = '{}/{}.pkl'.format(input_path, name) with open(filename, 'rb') as input: return pickle.load(input)
c6ba690fdc0b3ab555b275e2fc6e615d823dd256
672,834
from typing import Any import importlib import ast def load_cli(import_str: str) -> Any: """Load the cli object from a import name. Adapted from gunicorn. Examples: flask.cli:cli pipx.cli:create_parser() """ import_name, _, obj = import_str.partition(":") if not (import_name and ...
23f3e8107446c205834ed3cc7bd3384718ea797e
672,836
import itertools def intersecting_lines(lines): """ provides a list where pairs of intersecting lines are listed """ combs = itertools.combinations(lines, 2) _ret = [comb for comb in combs if comb[0].intersection_on_segment(comb[1])] return _ret
6aa989a2fd284ddb499869c30216f2306e98f636
672,838
def parse_regex_string(string): """ Parse header string according to wappalizer DB format strings follow the below format: <string>[\\;version:\\\d][\\;confidence:\d] "string" is a mandatory regex string followed by 0 or more parameters (key:value), can be empty parameters are divided by a \\;...
41a11b9099abcd03f87f14aefe85dbe9e6ccc45b
672,839
import sys def parseENDFByMT_MF( fileName, stripMATMFMTCount = True, logFile = sys.stderr ) : """This function reads an endf file and creates a python dictionary with the keys being MT numbers and the values being the data for the MT key. For each MT, the data are stored in a python dictionary with the ke...
6efc201bfb42e745a28b0f74eedb74d21e37e5c1
672,840
from math import pi as π, radians def theoretical_peak_angle_velocity(stride_freq_Hz: float = 3., total_angle_deg: float = 180., disp: bool = True): """Cheetah leg moves from 0⁰ -> 90⁰ -> 0⁰ in about 1/3 of a second. Ie, follows the shape: ...
48fe8201bf56200598963f4fa58b6405e9836a65
672,841
import os def _get_module_dir(): """Return the path of the module.""" return os.path.abspath(os.path.dirname(__file__))
309106616c1e63e3f61b7ec34c1fe43f53391f2b
672,842
def Courant(alpha, h, c): """ Computes the courant condition. Parameters ---------- alpha: Scaling parameter (generally 0.4) h: array of h's c: array of speeds of sound Returns ------- float: min. time step according to courant condition...
c6783f8dd8f0dea204ab076a1badfed1eadbff9a
672,843
def cal_iou(box1, box2): """ computing IoU :param box1: (y0, x0, y1, x1), which reflects (top, left, bottom, right) :param box2: (y0, x0, y1, x1) :return: scala value of IoU """ cx1, cy1, cx2, cy2 = box1 gx1, gy1, gx2, gy2 = box2 # 计算每个矩形的面积 S_rec1 = (cx2 - cx1) * (cy...
f58bd3be9d507c3f3e0814194b04a359aced233f
672,845
def extract_accessions(genbank_query, taxonomy_filters): """The query contains GenBank accessions and Cazymes_Genbanks records, retrieve the accessions. :param genbank_query: sql collection :param taxonomy_filters: set of genera, species and strains to restrict retrieval of sequences Return a list of ...
d494a81e231db54173d17dcabf923c7ff3e122be
672,847
def suppress_zeros(s: str, leading: bool = False, trailing: bool = True): """Suppress trailing and/or leading ``0`` of string `s`. Args: s: data string leading: suppress leading ``0`` trailing: suppress trailing ``0`` """ # is anything to do? if (not leading) and (not tr...
f1ba1177a3485bb6d39b4dc9143a0f450b486199
672,848
import textwrap def _get_embl_wrapper(embl_key, indent=5, subsequent_indent=None, width=80): """Returns a textwrap.TextWrapper for embl records (eg, write <key> <string> by providing embl key and a string. Wrap text to 80 column""" # define the string to prepen (eg "OC ") prepend = '{key:<{in...
c6b142233bb870dda812a01f31924b8f938cb316
672,849
def find_worst(list_of_values, quantity): """ auxiliary function to changeworst, finds the indexes of the worst performing members :param list_of_values: list of values relative to the members of the candidate used to determine which is the worst performing ones :param quantity: the quantity...
efb47dca893cc6f20f7ae4c13d45b3b15e20153c
672,850
def key_displace(key_bin): """ 密钥置换 :param key_bin: 64 位密钥 :return: 置换后的 56 位密钥 """ if len(key_bin) != 64: raise ValueError("二进制密钥字符串长度必须是 64") key_table = [57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, ...
e2a541b4671a9f4f86d2ef78754d86c6cd945f81
672,852
def get_resource_file(entity, resource_info, base_url): """ Create a file object from which resource data can be read. resource_info is a value returned by `find_fixed_resource` or `find_entity_resource` base_url is a base URL that may be used to resolving relative references in the ...
3b21e4a6288e29bc7bef97ebb5549b10ebc0ab8c
672,853
def field_eq(p, e): """ Checks the field values of a parsed message for equality against some ground truth value. Parameters ---------- p : object with dict-like attributed access Parsed field contents. e : object with dict-like attributed access Expected field contents. Returns ---------- ...
e6e9410a72e93c8f587bb6ee365d941ae5271ae3
672,855
def release(full: bool = False) -> str: """Returns the software version number""" # c133d9af2aee7c2bd37212fc8cd757a695b3cc5e result = "0.0.2" if full: result += " (12 July 2019)" return result
cb06dbdfff8fa1fec4c280acf69639442864ef50
672,856
def _format_list(elems): """Formats the given list to use as a BUILD rule attribute.""" elems = ["\"{}\"".format(elem) for elem in elems] if not elems: return "[]" if len(elems) == 1: return "[{}]".format(elems[0]) return "[\n {},\n ]".format(",\n ".join(elems))
37c1b2d6558d8d96dc3381d73fafaf9c7e489e92
672,857
import csv def make_edgelist(file, cols=[2, 3], delim="\t"): """Create an edgelist that's easy to parse""" pairs = [] with open(file, "r") as inter_file: reader = csv.reader(inter_file, delimiter=delim) for row in reader: pairs.append([row[i] for i in cols]) interacts = ...
6914aa45e3557cc864b99165d7cb3f1f0de465c5
672,858
def footer() -> str: """ Return the footer of the LaTeX document. :return: LaTeX document footer. """ return "\\end{tikzcd}\n\\end{document}"
f3d6615d089e489a88e6eba3c87a0fa9a655c20c
672,859
def ReformatForLog( data ): """ Change all non printable characters into something human readable. Arguments: data -- The raw data that may contain unprintable characters Example: 0x0D will show up as <D> """ output = '' for char in data: o = ord( char ) if( o < 32 ): # Unprintable control character...
0ed1f657bf1afbb495c09c6e3db4bdba30628449
672,860
def read_text_file(filename): """ Read .txt file Args: :param: filename(str): the name of .txt file Returns: :param: text(str): text in .txt file """ with open(filename, "r", encoding="utf-16") as file: text = file.readlines() return str(text)
e76e7922aaccd5b5c7971dbb6bfe34125425aa03
672,861
def chop(s, n=1, d=None): """Chops initial words from a string and returns a list of them and the rest of the string. The returned list is guaranteed to be n+1 long. If too little words are found in the string, a ValueError exception is raised. :Parameters: s : str or unicode String to ch...
a873777c5a621c1574b3b29d2f6890b7a343efb9
672,862
def dict_to_json(dict_obj): """Converter dict with obj to JSON""" result = {} for name, obj in dict_obj.items(): result[name] = obj.dump() return result
b55c033477992e5c11621be300dd772de9a2f4e4
672,865
def _filterobsoleterevs(repo, revs): """returns a set of the obsolete revisions in revs""" return {r for r in revs if repo[r].obsolete()}
1471f9c3818965c42080947a7f96390d668e0a5b
672,866
from typing import Tuple import math def win_probability(home_elo: float, away_elo: float) -> Tuple[float, float]: """Calculate probability that either player will win a match.""" home_prob = 1.0 / (1 + math.pow(10, (away_elo - home_elo) / 400)) return home_prob, 1.0 - home_prob
b883c8a0a0ea509d338c1433acda28268f2e4891
672,867
def parse_mode(new_mode): """Function to parse a mode give in input to chmod function. Parameters ---------- new_mode --> str, the new resource permissions, in the form of [0-7][0-7][0-7] Returns ------- (own,grp,others) --> tuple(int,int,int), the permissions parsed """ #t...
49bb96475b8b78e4550ddae6e17ee079056e8beb
672,868
def iseven(n): """ Return True if n is an even number and False otherwise. """ return (n % 2 == 0)
c3139d5b11d83f1d4e98d0575472bf817610b5c8
672,869
def doc_dep_graph(doc): """ Put the graph with entity labels present (see 'tag' and 'label') """ words = [] # the words of a dependency graph arcs = [] # the arcs of a dependency graph # iterate through each token in a doc for tok in doc: # if the token is not a named entity, us...
1655fa141d563eb29cca934fd29a7734ddc02ba6
672,870
import inspect def get_object_classes(classes_or_instances, expected_base_class=None): """Given a list of instances or class objects, return the list of their classes. :param classes_or_instances: mixed list to parse :type classes_or_instances: list[type or object] :param expected_base_class: if give...
738b99224111d940c0a14c753fad69eb66f16271
672,871
def d(b, a, bnds): """ Calculate difference between two images Parameters: b (ee.Image): 'before' image a (ee.Image): 'after' image bnds (ee.List<str>): band names included in calculation Returns: ee.Image: difference image with original bands """ ...
9a08abccd84ab39da7f8f4fad04f1e9d9beb4fa7
672,872
def file_type(filename, param='rb'): """returns the type of file, e.g., gz, bz2, normal""" magic_dict = { b"\x1f\x8b\x08": "gz", b"\x42\x5a\x68": "bz2", b"\x50\x4b\x03\x04": "zip" } if param.startswith('w'): return filename.split('.')[-1] max_len = max(len(x) for x in...
0b0ca1cbc37e0713865a9cefabc3af5bff0bd3ce
672,873
def find_nth_natural_number(i, limit): """Returns the ith natural number and the number containing it""" assert i >= 1 number_map = {} nums = [] prev_len = 0 for num in range(1, limit + 1): nums.append(num) new_len = len(str(num)) + prev_len number_map.update({j: (prev_le...
dd06e37f34e48c327494b0f6c1ab19012d672836
672,874
def get_label_list(namefile): """ Return the list of labels from namefile""" list_label = [] first = True with open(namefile, 'r') as f: for line in f: if not first: new_line = line.split(';') qt = int(new_line[1].replace('\n', '')) lis...
aa31ab040b79f04bad7491bcca042c85ed185f9a
672,875
import re def form_date_parameter(date: str, name: str) -> str: """Form the date parameter for the API query after checking whether given date is valid. Args: date (str): date in format YYYY-MM-DD name (str): either 'startDate' or 'endDate', used to differentiate API query parameters Rai...
1a229254731ca43748e1f6939a54cd2d029fee3a
672,876
import torch def matvec(mat, vec, out=None): """Matrix-vector product (supports broadcasting) Parameters ---------- mat : (..., M, N) tensor Input matrix. vec : (..., N) tensor Input vector. out : (..., M) tensor, optional Placeholder for the output tensor. Return...
aa866fe9e3bf893c74ecac2b5c4c7cff3beebdb3
672,877
def acquire_title(soup): """ Take a BeautifulSoup content of a book page. Return the title of the book. """ title = soup.h1.string return title
a3d661430d1516142a720b8981999db0ea5970a5
672,878
def find_samples(data): """ Parse a list of raw packages into a list of raw samples :param data: List of raw packages (int) :return: samples, fail_count. samples: List of raw samples fail_count: number of samples that could not be decoded """ sample = None looking_...
9cd1351acba500a4615b42a5db5482d36cb48b19
672,879
def load_room_descrips(data, room_names): """ Loading each rooms respective main description. Parameters: data(dict): Nested dictionaries containing all information of the game. room_names(list): List containg room names. Returns: room_descrips(list): Returns list o...
078762791ca9d10533dda0d5f86443b0693d36e7
672,880
def id_from_data(value): """return the name from the test data object""" return f" {value.pull_policy} "
e6067f22d0e265089e9fed572ab799840c18900c
672,881
def reprsort(li): """ sometimes, we need a way to get an unique ordering of any Python objects so here it is! (not quite "any" Python objects, but let's hope we'll never deal with that) """ extli = list(zip(map(repr, li), range(len(li)))) extli.sort() return [li[i[1]] for i in extli]
bcfbc4a2dc8807a2b846e87c48e76681da921a5f
672,882
def lines2paragraphs(lines): """ Return a list of paragraphs from a list of lines (normally holding the lines in a file). """ p = [] # list of paragraphs to be returned firstline = 0 # first line in a paragraph currentline = 0 # current line in the file lines.insert(l...
2f6cf177ac3fe93edc3df3b8ffbe11763e395558
672,883
def bytes_as_char_array(b): # type: (bytes) -> str """ Given a sequence of bytes, format as a char array """ return '{ ' + ', '.join('0x%02x' % x for x in b) + ' }'
980f1b57d2cc9b1b2b054843d54a24c5257d2996
672,884
def _get_extra_filters(db, table, dscfg): """설정에서 추가 필터 얻음.""" filters = [] for sect in dscfg.keys(): if not sect.startswith('filter'): continue add = False if sect == 'filter': add = True elif sect.startswith('filter.'): elms = sect.split...
2a2504d7dd98d4341fc934a65c568ed20093616a
672,887
def get_cpubind(cpu_binding): """Convert aprun-style CPU binding to PALS-style""" # First check for keywords if not cpu_binding or cpu_binding == "cpu": return "thread" if cpu_binding == "depth": return "depth" if cpu_binding == "numa_node": return "numa" if cpu_binding =...
5c0bbdedb3aca3580ca712d7af25a0b7e1ab4c2b
672,888
def info_to_name(display): """extract root value from display name e.g. function(my_function) => my_function """ try: return display.split("(")[1].rstrip(")") except IndexError: return ""
d01ce91fe18a57f1788feefa7fff37e4ec38a66e
672,889
import argparse def boolean(arg): """Convert a string to a bool treating 'false' and 'no' as False.""" if arg in ('true', 'True', 'yes', '1', 1): return True elif arg in ('false', 'False', 'no', '0', 0): return False else: raise argparse.ArgumentTypeError( 'could no...
b5138c692d651c8b19ac026077e63100bf3c4442
672,891
def get_x_minmax(start_times, end_times): """Determine the horizontal (x) min and max values. This function adds 1% to either side for padding. Args: start_times (np.array): First packet unix timestamps of all pcaps. end_times (np.array): Last packet unix timestamps of all pcaps. Retur...
95f95a281a626b0eefbbabf457a23303926c927b
672,892
import os def get_fileext(file_path): """Returns file extension Parameters ---------- file_path: str Path to file :return: file extension :rtype: string """ return os.path.splitext(file_path)[1]
dd47e931d55f0c0a176c0f8752b90d235a668a74
672,893
def get_busco_score(short_summary): """get busco Complete score from short_summary.txt""" with open(short_summary) as f: for line in f: line = line.strip() if line.startswith(("#", "*")) or line == "": continue elif line.startswith("C:"): ...
ddafc7092f7f6d0821aacc75b0acbd940626098e
672,894
import yaml def read_yaml(): """返回解析的yaml配置""" yaml_path = './yaml_test.yaml' with open(yaml_path, 'r', encoding='utf-8') as f: config = f.read() loaded_config = yaml.safe_load(config) return loaded_config
9acd0724b4fe7a07ad0341eb276c3b9f25746b5b
672,896
from datetime import datetime def GetShortLastBeer(last, now=None): """Returns a shortened string for the last scan.""" if not now: now = datetime.now() delta = now - last seconds = int(delta.total_seconds()) if seconds == 0: return ' 0s' periods = [ ('yr', 60*60*24*365), ('mo', 60*60...
2f6727623774456c92c949229d80f98b3ae07b03
672,897
def fizz_buzz_four( start, end ): """ Fizz buzz showing compact if-elif-else form, and precalculatio of boolean values. """ result = [] # initalising a list to hold our result for i in range(start, end+1): fizz = (i % 3 == 0) buzz = (i % 5 == 0) if fizz and buzz: result...
c666802d1f4b5f1dca17088af26ef56b784e5367
672,898
def rgb_to_hex(rgb): """ Covert RGB tuple to Hex code """ return f'0x{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}'
6b2e0cfeee567dd42635a69903e2317605c0fe87
672,899
def is_managed_by_cloudformation(physical_resource_id: str, resource_array: list) -> bool: """ Given a physical resource id and array of rources - returns if the resource is managed by cloudformation Parameters: physical_resource_id (string): The identifier of the resource - eg igw-09a7b4932e331edb...
49e4bd6d704df37824bde273b1e78079ca7e679d
672,901
import os import time def get_file_info(filepath): """ return file information :param filepath: file full path name """ f_info = os.stat(filepath) f_ctime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(f_info.st_ctime)) f_size_bytes = f_info.st_size f_name ...
6e15b7d6880d7a4001ff1ee664053294fd72406e
672,902
def EscapeDictionaryElement(element): """Escape all unprintable and control characters in an element.""" element_escaped = element.encode('string_escape') # Remove escaping for single quote because it breaks libFuzzer. element_escaped = element_escaped.replace('\\\'', '\'') # Add escaping for double quote. ...
5841ebd7b1675ec60fca9e95fa59559ab551a47a
672,903
def combine_QUBO_storage(QUBO_storage, solved_QUBOs, column_solutions): """ Merges previous QUBO storage with new solutions. Parameters ---------- QUBO_storage : list Input QUBO storage list. solved_QUBOs : dict The QUBOs that were solved in this latest iteration. column_sol...
6a8c217f75c4b3c3f51a6292ce4179a165276fd5
672,905
import codecs def file_to_data(filename, topic_id): """Transforms a single summary file into a data object for pipeline.""" # open file review_sentences = [] with codecs.open(filename, "r", encoding='utf-8', errors='ignore') as fh: review_sentences = fh.read().splitlines() # put sentences...
48bd51747e5697c35ee7becfe7e52bc62b55b786
672,906
from datetime import datetime def get_week_format_from_timestamp(timestamp_millis: int) -> str: """Get week format from timestamp in milliseconds. The week number returned will follow ISO-8601 standard :param timestamp_millis: Timestamp in milliseconds. :type timestamp_millis: int :return: Return...
e9cbd2ffcde5bef2ef02fa5a670a4fdba9fd7934
672,907
def counting_sort(array, maxval): """ Sorts the list 'array' using counting sort >>> from pydsa import counting_sort >>> a = [5, 6, 1, 9, 3] >>> counting_sort(a, 9) [1, 3, 5, 6, 9] """ count = [0] * (maxval + 1) for a in array: count[a] += 1 i = 0 for a in range(max...
9f40f270b5974a80d2d46db5896ecf34b80b8568
672,908
import logging def get_string_from_comment(comment): """Extract a string from a comment formatted like this: '/u/<username> string' or '/u/<username> string' """ lines = comment.body.split("\n") try: if lines[0] != "/u/check_em_out": assert lines[0].startswith("/u...
6446243bd31040999e257cf4fe05414894777b4d
672,909
def Nu_dist(Re_outtube_dist, Pr_coolwater_dist): """ Calculates the Nusselt criterion of coolwater. Parameters ---------- Re_outtube_dist : float The Reynold criterion, [dimensionless] Pr_coolwater_dist : float The Prandtl criterion, [dimensionless] Returns ------- Nu...
5ab8684977a83902d6dd386432310a00c8cbdd9f
672,912
def similarity_tannimoto(left, right): """ :param left: Dictionary <key, value> :param right: Dictionary <key, value> :return: """ in_common = 0 total = 0 for left_fragment_key in left: for right_fragment_key in right: left_fragment = left[left_fragment_key] ...
7c74d84b6102426e4b1dc05e01372381d72f84a2
672,913
import requests import json def get_periodical_year_article(perioId, publishYear): """ 获取 XXX年《期刊》的所有文章ID :param perioId: 期刊代码,如汉语学习代码为:hanyxx :param publishYear: 出刊年份 :return: [] """ URL = 'http://www.wanfangdata.com.cn/sns/third-web/per/perio/articleList' headers = { "User-A...
d914fc3d6260bd8cba8c76d815b97dbe934d3f3b
672,914
def get_full_duplicates(data, list_of_duplicates_indexes): """Searches for full data in original Cognito response for every email that has duplicates by their indexes, using advantage of ordered lists Args: data (List): List of objects representing user in Cognito list_of_duplicates_indexes (Tu...
feac03dd4a68c0a32dbdbd7536a3c53f2e8aab61
672,915
def get_rb_blob_attribute(blobdict, attr): """Get Attribute `attr` from dict `blobdict` Parameters ---------- blobdict : dict Blob Description Dictionary attr : string Attribute key Returns ------- ret : Attribute Value """ try: value = blobdict['BLOB'][...
3f3768057cde529c467774da93cc33bb83571a78
672,916
def bxor(*args): """Return the bitwise xor of all arguments.""" res = 0 for arg in args: res ^= arg return res
8e2c7f93888ac2bbebc0bdd4e280db39305b88d7
672,917
def opListFuse(ops): """ 算子融合 """ fuseOpList = [ 'relu', 'relu6', 'leaky_relu', 'scale', 'sigmoid', 'hard_sigmoid', 'pow', 'sqrt', 'tanh' ] # 判断op是否为单节点 def opExistSingleNode(opName): name = opName if name: ...
1edb8b4447f0254af1be020f26720183ed20c137
672,918
def pre_process(board, turn="x"): """ Takes the board with x and o and turns in into vectors with numbers. 1 is AI, -1 is human, and 0 is empty """ result = [] opposite = "o" if turn == "x" else "x" result = [1 if x == turn else x for x in board] result = [-1 if x == opposite else x for x in result...
f0932c42248ce2509a717f78c208dbdd74b2ea82
672,919
def b_count(pattern): """ Count the number of B's that occur in a site pattern Input: pattern --- a site pattern Output: num_b --- the number of B's in the site pattern """ num_b = 0 for char in pattern: if char == "B": num_b += 1 return num_b
99f32f92057b663f59bef3f7431477d6821c766c
672,920
import os def convert_to_platform_path(distutils_path): """ Convert a distutils Unix path distutils_path to the platform format. """ if os.sep == '/': return distutils_path return os.sep.join(distutils_path.split('/'))
c5293447d975430783d309b97600ece3a7ef3684
672,921
import torch def adaptive_add_fusion(z: torch.Tensor, p: torch.Tensor): """Adds a point cloud to a noise tensor that can have a smaller dimension. The noise tensor `z` with `dim_z` channels will be added to the first `dim_z` channels of the point cloud `p`. Args: z: Reference point cloud of ...
cb49c8b1607da108d2a4ea8b682bcfc5b5730007
672,922
def discover_unit_test(): """Build a 2048 node system for unit testing purposes. """ nodecount = 2048 rack = 0 nodes = 0 node_list = [] while nodes < nodecount: for cabinet in range(0, 4): for slot in range(0, 4): for node in range(0, 8): ...
504e63a982780b12ed52548d6a643f2a8b58be8d
672,923
import logging def Aggregate_median_SABV_AGE(rnaseq): """Compute median TPM by gene+tissue+sex+age.""" logging.info("=== Aggregate_median_SABV_AGE:") logging.info(f"Aggregate_median_SABV_AGE IN: nrows = {rnaseq.shape[0]}, cols: {str(rnaseq.columns.tolist())}") rnaseq = rnaseq[["ENSG", "SMTSD", "SEX", "AGE", "...
ef41a3929c5c052c434151dce4fae8fd85da027b
672,924
def try_mine(block): """Updates the nonce and sees if it's valid. """ block.nonce += 1 return block.is_valid()
8b3d5842c36783d17b24250a08578c1cfeca8432
672,925
def v0_is_perfect_square(number): """Return True if given number is the square of an integer.""" return int(number**0.5)**2 == number
0e2950429a84d622c7a386e9f54e1289689b9367
672,926
def unpack_and_split_nodes(data, path): """Unpack a list of results Args: data: A dictionary containing the results path: A list of fields indicating the fields to select. final one should be a list of nodes Returns: issues: A list of dicts; each dict is the data for some of the results ...
1f8063ba52350a8408fcfe6a3300d7c88d4b248e
672,928
def select_seeds(bronchial, ct_clice): """ Selection initial pixel. Args: bronchial: A label of the pixels with the bronchi. ct_clice: A label of CT slice. Returns: Area of the bronchi with minimal voxels """ return (ct_clice * bronchial) == ct_clice[bronchial].min()
8646b253046df549cb7321f09499299fcd514d94
672,929
import sys import os def run_cmd(path): """Generates the command to run a file at `path` """ if sys.platform == "win32": return ["python", os.path.join(".", "bin", "PongChamp"), path] else: return [os.path.join(".", "bin", "PongChamp"), path]
a9edd4f126ee9c69811913aed9b76bf65fb0e6ed
672,930
def keys_by_value(dct, vals): """ return dictionary keys for specific values """ return tuple(key for key, val in dct.items() if val in vals)
834cdcbe3005cf1e23e6d5bfc2deb8952195fe86
672,932
def evaluate(function, param1, param2): """ Returns <function>, called with <param1> and <param2> """ return function(param1, param2)
9c2310936049dce931e94058634e94dca4585517
672,934
import torch def _linear_interpolation_utilities(v_norm, v0_src, size_src, v0_dst, size_dst, size_z): """ Computes utility values for linear interpolation at points v. The points are given as normalized offsets in the source interval (v0_src, v0_src + size_src), more precisely: v = v0_src + v_...
7e664fec2d3198c8124131541f2d07658a9f1f83
672,935
def _get_channel_id(data): """ Get channel ID which this event data is associated to. Event payload schema highly depends on event type. :param data: event payload :type data: dict :rtype: non empty string or None """ for key in ['channel', 'channel_id']: channel = data.get(key...
f434962b6e20952fd68729204d6f4f77fe8c2a13
672,936
def codegen_reload_data(): """ Parameters required reload codegen for the fn_icdx package """ return { "package": u"fn_icdx", "message_destinations": [u"fn_icdx"], "functions": [u"icdx_get_archive_list", u"icdx_get_event", u"icdx_find_events"], "workflows": [u"example_icd...
209c1a2a2fd7e11b979b835f289a31e27ea116d7
672,937
def is_truthy(data): """ Returns True if the data is a truthy value, False otherwise. """ string = str(data).lower() return string in ['true', '1', 'f']
a5e6b743f11e7b18c6f249ef8a9f4f764ed9c927
672,938
import hashlib def make_hash(*texts): """ The text is hashed together with its makefile because the built corpus will look different on many settings. For example, if word annotations are taken from the corpus or generated by our tools. """ return hashlib.sha1("".join(texts).encode("UTF-8")).h...
cab41e94929bc58e30c5ea6d0207537bf839b152
672,939
def sor(*args): """ sor aka or aka alternative; "or" keyword is reserved, that's why this name """ def parse(parser): for i in args: result = i(parser) if result is not None: return result return None return parse
5defe4e23bd8387f2f27c5e0e1ad4c02134879e2
672,940
def get_toolchain_dir(toolchain_dir_output): """Find the toolchain directory.""" prefix = 'vs_path = ' for line in toolchain_dir_output.splitlines(): if line.startswith(prefix): return line[len(prefix):].strip('"') raise Exception('Unable to find toolchain dir in output:\n%s' % ( too...
43017a4afc8ec5a5318129f57f465f8a66bca2cd
672,941
def resetar_orbita_padrao(): """ Função para resetar os dados de orbita Retorna: Sem retorno """ reset = {'moho': {'apoastro': 10000, 'periastro': 10000}, 'eve': {'apoastro': 100000, 'periastro': 100000}, 'gilly': {'apoas...
76f2ee578f33546d52054bac9df70bc6f9ea7aea
672,942
def grind(txt): """Performs final feed-forward modifications.""" txt = "|$|" + txt[:-3] return txt
65d7260da04ccc15443d6ba2437bf272215e7eb9
672,943
def cal_accuracy_on_2(sample_label_prob_dict_list, test_label_list): """ :param sample_label_prob_dict_list: [ {1: 0.2, 2:0.15, 3:0.2, ..., 9:0.1} {1: 0.2, 2:0.15, 3:0.2, ..., 9:0.1} ... ] test_label_list: [1,2,5...
38f39920e0bfbc159bfe697cecfccac4e349c346
672,944
def clamp(value: float, mini: float, maxi: float) -> float: """ it clamps a value between mini and maxi :param value: the value that will be clamped :param mini: the floor value :param maxi: the ceil value :type value: float :type mini: float :type maxi: float :return: Union[int, flo...
2e69b4bd395b29c9dae459d70f1badf12add7582
672,945
def indices_to_ids(splits, ids): """Converts split indices to subject IDs""" return [[[ids[i] for i in ids_group] for ids_group in split] for split in splits]
4ce97020d1ae50017e6ec694b3b158360a76bb18
672,946
def unique_list(seq): """ Returns unique values from a sequence. Modified to remove empty context entries https://www.peterbe.com/plog/fastest-way-to-uniquify-a-list-in-python-3.6 """ return list(dict.fromkeys(s for s in seq if s))
accfd2088580b0aa6b69b53515023586ea539964
672,947
def fileSizeStrToInt(size_str): """Converts file size given in *iB format to bytes integer""" unit_dict = {"KiB": (2 ** 10), "MiB": (2 ** 20), "GiB": (2 ** 30), "TiB": (2 ** 40)} try: num = float(size_str[:-3]) unit = size_str[-3:] return int(num * unit_dict[unit]) except Except...
ccdbebef08297a47d276d43d75a96d2f78daf760
672,948
def reciprocate_currency(dataframe, reciprocal_list): """ Reciprocate the values of columns for currencies subordinate to USD :param dataframe: dataframe to reciprocate values :param reciprocal_list: list of currencies to reciprocate values for :return: dataframe with reciprocated values """ regex_reciprocal =...
83773361c84dc7340ab39d3df627acb9a53a369d
672,949
import re def generic_addresses(dot_content): """The stack changes every time the core files are recreated. Should I commit the core files and the binaries in the repo? Or should I "wildcard" the addresses? Or abandon this way of testing? ...I wish I knew. For now, I replace the addresses wit...
cc7ef18a1a21d7582324168fac8045fbd4c8faaa
672,950