content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def is_complete(self): """ Returns if the task is complete """ return self.status == "DONE"
239d0e7dae32f1171a38ecd40fb648b724280fd7
503,853
def mode(lst): """Calculates the mode of a list""" return max(set(lst), key=lst.count)
6bf4393a3e8b3904d0c06fee483e7ca1338af12a
80,701
import requests def read_url(url: str) -> str: """ Return url contents. :param url: URL for request :return: return response content string """ cal_data = requests.get(url).text return cal_data
efe617722ddde37b2ba5e39eca3d3bdfa311f015
572,525
from typing import Dict from typing import Any def response_state_from_mediation_record(record: Dict[str, Any]): """Maps from acapy mediation role and state to AATH state""" state = record["state"] mediator_states = { "request": "request-received", "granted": "grant-sent", "denied...
15062fc26f13d907299793df692bf1e39932691c
641,733
def in_to_cm(inches): """ Convert inches to centimeters """ return inches * 2.54
dd774bcd1de1aa8c6d5e7f8123bbe2b0e6a0892c
223,589
def index_union(df_src, df_target, use_target_names=True): """ Create the union of the indices for the two Pandas DataFrames. This combines the "rows" of the two indices, so the index-types must be identical. :param df_src: Pandas Series or DataFrame. :param df_target: Pandas Series or DataFra...
d69e8714405a6ee55f5e5b14c5e4f069e67b7b87
605,358
def coalesce_dates(dates): """ Coalesces all date pairs into combined date pairs that makes it easy to find free time gaps. >>> from date_collapse import coalesce_dates >>> dates = [(1,4),(2,8),(12,16),(16,21)] >>> cdates = coalesce_dates(dates) >>> print(cdates) [(1, 8), (12, 21)] >>> ...
161ef92c6c8946a277e11504cb3dee1082582123
40,337
def _gr_text_to_no(l, offset=(0, 0)): """ Transform a single point from a Cornell file line to a pair of ints. :param l: Line from Cornell grasp file (str) :param offset: Offset to apply to point positions :return: Point [y, x] """ x, y = l.split() return [int(round(float(y))) - offset[0], int(round(flo...
b07a7587cc82ecc9b6a8796e0d09119086092ad7
668,559
def source_to_locale_path(path): """ Return locale resource path for the given source resource path. Locale files for .pot files are actually .po. """ if path.endswith("pot"): path = path[:-1] return path
6a2ca315e7bb2dfe03dede7c2be06602ff47cb40
685,385
def check_field(vglist,key,value): """ Accepts a list of dicts; for each dict, check the the specified key contains the specified value. """ for row in vglist: assert row[key] == value, \ '** Error: Field: %s contains value: %s, expected: %s' % (str(key),str(row[key]),str(value)) return True
92ba6c26b47e2f96176b4593d89c2b509a004e2f
269,721
def det(x): """ Return the determinant of ``x``. EXAMPLES:: sage: M = MatrixSpace(QQ,3,3) sage: A = M([1,2,3,4,5,6,7,8,9]) sage: det(A) 0 """ return x.det()
8e74bb3c1f8c99ea25b4868690813b11ac47087f
660,614
def calculate_overlap(a: str, b: str) -> int: """ Calculates an overlap between two strings using Knuth–Morris–Pratt algorithm """ pi = [0] * (len(a) + len(b) + 1) string = b + '#' + a for i in range(len(string)): if i == 0: continue j = pi[i - 1] while j > ...
3f2f902d8a9b8d23d69cfbd502cc4d75723e55c5
95,165
def is_file(obj): """ Check if the given object is file-like. """ return hasattr(obj, 'flush') and hasattr(obj, 'readline')
df70bf8651ecfa7e9a2530178c9dda8cef87c787
490,614
def get_request_id_or_none(filename): """Get a unique id out of a filename.""" if filename.endswith(".json"): return int(filename.replace(".", "").replace("json", ""))
c5889e3647025794822dc88cb22f8f05083b34f0
208,038
def is_markdown_cpp_src(ipynb_cell): """ True if a cell is markdown && multiline source code && C++ ```'s wrap multiline code blocks C++ source code blocks have C++ right after starting ``` """ result = False # Markdown if 'markdown' == ipynb_cell['cell_type']: src = ipynb_cell...
2bfcc92b54b9e4645f32422c6909ca33f3bd4add
525,624
def _assign_axis(attributes, axis): """Assign the given axis to the _metpy_axis attribute.""" existing_axes = attributes.get('_metpy_axis', '').split(',') if ((axis == 'y' and 'latitude' in existing_axes) or (axis == 'latitude' and 'y' in existing_axes)): # Special case for combined y/la...
a1586cbdc618a7c958a2b7ee3d9296a63bb99647
498,767
import re def get_valid_filename(s): """ Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. >>> get_valid_filena...
6561030d1e444e8fd5121636ec08d561433ce73c
623,635
def str_to_hex(string): """Convert given string to hex string.""" return ":".join("{:02x}".format(ord(c)) for c in string)
f84337f96970faafee0283748581f5e5654c71a7
502,565
import math def root_mean_square(x): """ Root mean square (RMS) is the square root of the sum of the squares of values in a list divided by the length of the list. It is a mean function that measures the magnitude of values in the list regardless of their sign. Args: x: A list or tuple of...
9a594179fd873e8bd5dd439a427ed917cebcd05c
96,463
def convert_roman(ch): """ converts a roman numeral character into the respective integer """ ret = -1 if ch == 'I': ret = 1 elif ch == 'V': ret = 5 elif ch == 'X': ret = 10 elif ch == 'L': ret = 50 elif ch == 'C': ret = 100 elif ch == 'D':...
912e82046733ca39ba7be112a13d82fba60f9980
245,387
import hashlib import json def treehash(var): """ Returns the hash of any dict or list, by using a string conversion via the json library. """ return hashlib.sha256(json.dumps(var, sort_keys=True).encode("utf-8")).hexdigest()
e196a8d601b59a893bf05bc903aa7e3af4927cef
696,038
def IsArray(obj): """Determine if an object is an array""" return isinstance(obj, (list, tuple))
815e212c276b6c6dbbf15029b5fa2cdf1754c8a4
363,806
def get(api_key, types, p1, p2, n_threads=20, radius=180, all_places=False): """ :param api_key: str; api key from google places web service :param types: [str]; placetypes :param p1: (float, float); lat/lng of a delimiting point :param p2: (float, float); lat/lng of a delimiting point :param n_...
173e9a2367250d3744db4dfe77b486965ea0a62a
357,720
def atf_fc_uri(article_uri): """URI of feature collection""" return article_uri+"/featurecollection"
c725642309955795b5558b638146b782c7f51d0b
63,018
import ast def get_ast_node_name(x): """Return human-readable name of ast.Attribute or ast.Name. Pass through anything else.""" if isinstance(x, ast.Attribute): # x.value might also be an ast.Attribute (think "x.y.z") return "%s.%s" % (get_ast_node_name(x.value), x.attr) elif isinstance(x,...
c00c31638f4789ed45741b4744f290c1822e0a7f
162,221
def element_located_to_be_selected(locator): """An expectation for the element to be located is selected. locator is a tuple of (by, path)""" def _predicate(driver): return driver.find_element(*locator).is_selected() return _predicate
41eca03c731f50aa71692beb407d7c8001945a67
320,439
def greet(name): """Greets you by name!""" return 'Hello {name}!'.format(name=name)
1822209df3852c11f3a6731c9ddbb1ee4c2c5286
373,232
def prompt_for_password(prompt=None): """Fake prompt function that just returns a constant string""" return 'promptpass'
49499970c7698b08f38078c557637907edef3223
2,777
def get_representative(location: str) -> tuple[str, str]: """ Split the location into numeric (row) and alphabet (column). Parameters ---------- location: str A string use to locate the position on the board. Returns ------- row: str ...
b2c973d6e9e5180761fc393a388fa424d7e016dc
142,315
from typing import List def create_id_access_token_header(id_access_token: str) -> List[str]: """Create an Authorization header for passing to SimpleHttpClient as the header value of an HTTP request. Args: id_access_token: An identity server access token. Returns: The ascii-encoded b...
db2450d58c9a8292b80f2d5bbf79cf88c87c2637
314,639
def char_to_word_index(ci, sequence): """ Given a character-level index (offset), return the index of the **word this char is in** """ i = None for i, co in enumerate(sequence.char_offsets): if ci == co: return i elif ci < co: return i - 1 return i
ecdfafd0c301d98d3f600b34022eb2e605a6e1da
637,956
def is_letter_guessed_correctly(player_input, secret_word): """ check whether the (guessed_letter/ player_input) is in the secret_word Arguments: player_input (string): the player_input secret_word (string): the secret, random word that the player should guess Returns: boolean: True if the player_in...
2fd0840300ae16aba4ba1d997c4cd98343778f74
619,247
def my_data_pypath(tmpdir_factory): """temporary directory for storing test data""" pypath = tmpdir_factory.mktemp('singlecell_data', numbered=False) return pypath
c4057f32008c064a5b703e80469d68d0afaf0b2b
371,588
def isMissionary(info, iReligion): """ Returns True if <info> is the Missionary for <iReligion>. """ return info.getReligionSpreads(iReligion)
5331f459cb57f116443c1837d62df8143bb9a133
92,794
def default_flist_reader(flist): """ This reader reads a filelist and return a list of paths. :param flist: path of the flislist to read. The flist format should be: impath label, impath label, ...(same to caffe's filelist) :returns: Returns a list of paths (the examples to be loaded). ""...
216af3ae7e7fbdf7215e4b554a070cabc99ced48
452,007
import uuid def generate_id(length: int = 18): """ Generate a pseudo-random ID. :param length: Length of the requested ID. :return: Generated id. """ return str(uuid.uuid4().hex)[:length]
3b685fd72c38248e1420806f2968fba4ec0db3d0
222,610
import json def process_config(json_file): """Load configuration as a python dictionary. Args: json_file (str): Path to the JSON file. Returns: dict: """ # parse the configurations from the config json file provided with open(json_file, 'r') as config_file: co...
2190525330bb319547fa143ea9e78bbddf052ffa
646,660
def is_in_combat(character): """ Returns true if the given character is in combat. Args: character (obj): Character to determine if is in combat or not Returns: (bool): True if in combat or False if not in combat """ return bool(character.db.combat_turnhandler)
0aaa73d15df3019df8d9bf0dfcc1329e386d27b5
589,933
def _solve_method_3(arr): """ https://github.com/JaredLGillespie/HackerRank/blob/master/Python/minimum-swaps-2.py Couldn't really figure it out via my method, but I found this solution that was very small and I understand. One thing I did was factor out a portion of it into a function call, for ...
fca3a8ace9f026eed0d56a1b80c56073842f3249
687,463
def extract_rules(lines): """ Extracts rules from file. Rules are structured in nested dictionaries. The outer dictionary has the color as key with a dictionary as value that contains the bag colors and amounts. The inner dictionary has the bag color as key and the amount as value. :param lines: Lines ...
5e57f8df21eae3c3778bd2be3dba6d4aedb8dc7b
513,043
from typing import List def missing_number(nums: List[int]) -> int: """Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. From `leetcode <https://leetcode.com/problems/missing-number/>` :param nums: {List[int]} 0, 1, 2, ..., n ...
6dd75d9e596258fab489691e4720e391024139a6
124,521
def _get_part(pointlist, strokes): """Get some strokes of pointlist Parameters ---------- pointlist : list of lists of dicts strokes : list of integers Returns ------- list of lists of dicts """ result = [] strokes = sorted(strokes) for stroke_index in strokes: ...
7f2c96945d39b7704ddefed746c358ee6b41a667
454,883
def parse_list_file(file): """ parses a text file with a list, one string per row :param file: list file to be parsed (strings, one per row) :return: a list of strings """ # get rows of file rows = [row.strip() for row in file.splitlines()] # remove any empty rows rows = [_f for _f...
144303456b58f215208171b2ed88bb958d760464
215,901
def make_obj_list(obj_or_objs): """This method will take an object or list of objects and ensure a list is returned. Example: >>> make_obj_list('hello') ['hello'] >>> make_obj_list(['hello', 'world']) ['hello', 'world'] >>> make_obj_list(None) [] """ if not obj_or_objs: ...
d65407167714d02c63ee8a784e688668711f3b75
169,888
def merge(items1, items2): """Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. Running time: O(n) Passes over each element once Memory usage: O(n) Makes a new list for all the elements """ ind_1, ind_2 = 0, 0 ...
3fa477a93d3aed5337a2b62a516b653b88929d30
623,441
def select_group_nodes(graph, group): """Select nodes from a networkx graph based on a group. Args: graph (networkx.Graph): Networkx graph object. group (str): Group name. Returns: list: List of networkx nodes that are of the specified group. """ nodes = [node for node in graph.nodes(data=True) if group <...
b9d451ebaa81835275ae243684e2cbb86c66f34c
186,898
def index_to_angle(i): """ Takes an index into a LIDAR scan array and returns the associated angle, in degrees. """ return -135.0 + (i / 1081.0) * 0.25
63f99389ef532a662d5ea3a3a173a1ba8dd9df09
43,626
def compose1(f, g): """Return a function that composes f and g. f, g -- functions of a single argument """ def h(x): return f(g(x)) return h
8d4829a787b78826f1c03d5e9621fb7d6a6ea56c
647,491
def getinstancepublicip(instance): """Given a JSON instance, get its public IP address""" if "PublicIpAddress" in instance: return instance["PublicIpAddress"] else: return ""
f265f567ad6fbea5889e1ad9b710fa89834a8ff0
417,966
def create_flickr_url(photo, size): """Create a Flickr image url based on the given photo object and size (in Flickr terms).""" # pylint: disable=C0301 return "https://farm{farm}.staticflickr.com/{server}/{id}_{secret}_{size}.jpg".format( size=size, **photo )
1ec25f0d7300ea85ed6bafd52d66a8cc1fbfc874
414,935
import torch def product_of_gaussians(mus, sigmas_squared): """Compute mu, sigma of product of gaussians. Args: mus (torch.Tensor): Means, with shape :math:`(N, M)`. M is the number of mean values. sigmas_squared (torch.Tensor): Variances, with shape :math:`(N, V)`. V ...
27a59cf57e70c1056ebe5703be1d36aa7e69af67
254,018
import re def get_links(text): """ It will return website links from the text :param text: string :return: list example >>> message = 'http://twitter.com Project URL: https://app.grepsr.com/app/project/message/70454' >>> get_links(message) ['http://t...
c0cb6c5b499db48c553ba76af5044b032547ba34
375,223
import re def baseOfBaseCode(baseCode): """ Return the base (jrnlCode) of the baseCode >>> print baseOfBaseCode("IJP.001") IJP >>> print baseOfBaseCode("IJP001") IJP >>> print baseOfBaseCode("JOAP221") JOAP >>> print baseOfBaseCode("ANIJP-IT.2006") ANIJP-IT >>> print baseO...
9597272d4ffa6f1b6a74a7beff50e1197cda0c54
77,856
def non_content_line(line): """ Returns True iff <line> represents a non-content line of an Extended CSV file, i.e. a blank line or a comment. :param line: List of comma-separated components in an input line. :returns: `bool` of whether the line contains no data. """ if len(line) == 0: ...
8f094f678fedb8307f3ab78a8e3b15b7d35f7497
419,763
import re def _extract_from_arn(arn, position): """ Helper Function to extract part of an ARN :param arn: Arn to extract from :param position: Position in Arn of interest :return: String containing value at requested position """ return re.findall("(.*?):", arn)[position]
b2b19bd1b29a99578115df95172211579d112c90
347,456
def get_dgs(align_dg_dict): """ Function that creates inverse dictionary of align_dg_dict align_dg_dict: dict. Dictionary of alignments and clustering DG assignments Returns dg_align_dict: dict, k=dg_id, v=[alignids] align_dg_dict comes from get_spectral(graph) or get_cliques(graph) """ dgs_...
85bca47657c83d2b308d38f05d1c88d9a78fa448
705,451
import random def choix(liste): """ Renvoie un élément de la liste ``liste`` choisi (pseudo)aléatoirement et de manière équipropable Arguments: liste (int): La liste dans laquelle on choisit un élément. """ return random.choice(liste)
01254d22ee62528e41fcaa75ef28d4c2c3683d73
493,030
import hmac def PRF512(K: bytes, A: bytes, B: bytes) -> bytes: """ Implementation of PRF-512, as defined in IEEE Std 802.11-2007 Part 11, section 8.5.1.1. Returns a 512-bit value. :param K: key :param A: a unique label for each different purpose of the PRF :param B: binary input to the PRF ...
770f6b90ccc8e0ee037232872191d1e94d4389b2
169,272
def seconds_to_human(seconds): """Convert seconds to a human readable format. Args: seconds (int): Seconds. Returns: str: Return seconds into human readable format. """ units = ( ('week', 60 * 60 * 24 * 7), ('day', 60 * 60 * 24), ('hour', 60 * 60), ...
7aea36c236aad9bec1927b4704f322b19a9de308
577,125
def get_user_id(user): """ JavaScript-friendly user-id. """ if user.id: return user.id return 'null'
e9b33099c1b313c81b5a9dcfb35ddcfd5127d6a8
385,846
import itertools def all_combinations(items): """Generate combinations of variable size. :param items: Sequence of items. :return: List of all combinations. :rtype: :py:class:`list` """ combinations = [] for rsize in range(1, len(items) + 1): combinations.extend(list(itertools...
fbb697d75edb4452addb78803e5d48969ba6b250
404,479
def shrink_path(full_path: str, max_len: int = 70) -> str: """ Shrinks the path name to fit into a fixed number of characters. Parameters ----------- full_path: String containing the full path that is to be printed. \n max_len: Integer containing the maximum length for the f...
36bfcc9b3216ef84cc41ea550f8c0176518e0fb6
442,532
def char(int): """ CHAR int outputs the character represented in the ASCII code by the input, which must be an integer between 0 and 255. """ return chr(int)
7fa90e06d9b4498a1603fa2439776789c98bd2be
675,039
def static_isinstance(obj, obj_type): """ A static implementation of isinstance() - instead of comparing an object and a class, the object is compared to a string, like 'pyiron.base.job.generic.GenericJob' or a list of strings. Args: obj: the object to check obj_type (str/list): object ...
c18184293cbad98f3eda6c1450674f6a9d1079c1
532,406
def calculate_error(t_k, y_k): """ Beda antara data target dengan prediksi model args: - t_k: target pada hidden layer k - y_k: hasil prediksi pada hidden layer k """ return t_k - y_k
a8fe6b575b47323b7cf7db44ab10918175fd1e1b
457,079
def NumWord(number): """ Just a bunch of numbers in word-form. Returns the 'number'th element which happens to be that number as a word. works for 0-99 should be good enough for a clock. """ Words=["zero", "one","two","three","four","five","six","seven","eight","nine","ten", "eleven","twelve","thirteen","fourteen...
3f141832a8a6ec16d056e055704c4420f5dfb8cf
377,616
def getIntervalStr( rg, label ): """ Converts and stores range along string as string Parameters: * rg (list, array, tuple): array object with three elements [start, stop, step] * label (str): label to be concatenated with range info Returns: * str: concatenated label and range info """ if len...
4f7585767151cbac636b26c9d01212ddbdd167b8
499,329
import json def get_value(json_file, key): """ return the value associated with the key in the specified json file :param json_file: the json file where the key and value present :param key: the key where the value is associated with :returns: 0 if there is not key found in the json_file. else re...
a97f8e5cb714061cdc1551cf5f9fb49280354471
164,597
def unquote(value): """Removes left most and right most quote for str parsing.""" return value.lstrip('"').rstrip('"')
fe38a7e2786783a11e0f39886517c8b567084e49
549,358
def one_of_k_encoding_unk(x, allowable_set): """ taken from https://github.com/thinng/GraphDTA function which one hot encodes x w.r.t. allowable_set with one bit reserved for elements not in allowable_set x: element from allowable_set allowable_set: list list of all known elements ...
1ccd42a1d4f27e09baedac0e5cdf43ca8871a58a
618,016
def get_iwp_label_name( iwp_label, shortened_flag=False ): """ Retrieves a name for the supplied IWP label. May be a shortened nickname for readability or the full label identifier depending on the caller's needs. Takes 1 argument: iwp_label - IWP label to extract a name from. shorte...
f7f2388e19fcd2fb07008d3615792e7271c4980e
522,046
def time_interval_since(date_1, date_2): """ Calculate seconds between two times Arguments: date_1 -- datetime object #1 date_2 -- datetime object #2 Output: Num of seconds between the two times (with a sign) """ return (date_1 - date_2).total_seconds()
6a5f11b0e2705a4e577e037ba43dfed6bda06be4
687,624
def adapt_format(item): """Javascript expects timestamps to be in milliseconds and counter values as floats Args item (list): List of 2 elements, timestamp and counter Return: Normalized tuple (timestamp in js expected time, counter as float) """ timestamp = int(item[0]) ...
bc39c3b644bbf833a3288c520707d67c07e9cfb1
291,538
import pickle def load_model(filename): """ Function to load an HMM model from a pickle file. :param filename: full path or just file name where to save the variable :type filename: str :return: the trained HMM that was in the file :rtype: object """ with open(filename, 'rb') as f: ...
6a8c3dc590da4f299a17f1e3ffc7378e97be95ba
114,276
def get_rpath_deps(pkg): """Return immediate or transitive RPATHs depending on the package.""" if pkg.transitive_rpaths: return [d for d in pkg.spec.traverse(root=False, deptype=('link'))] else: return pkg.spec.dependencies(deptype='link')
1664fd2e54b2b29cf615a365131c057d7eb261b7
669,704
def ProfondeurMoyenne(tree): """Retourne la hauteur moyenne de l'arbre tree.""" return tree.av_leaf_height()
a59c9ed83bdd7f5a337a0ba82441cf2154df82a7
94,481
def find_all_tiltgroups(fileList): """ Find all unique ID codes for each tilt group in the dataset and return them as a list for use: [ "tilt_id_1", "tilt_id_2", ... "tilt_id_n"] """ tilt_ids = [] for file in fileList: filename_to_list = file.split("_") tilt_id = filename_to_...
1a26132a2ec7b8b9b7e0a4892266b31bcd0e3484
520,123
import psutil def get_num_procs(njobs:int)->int: """ Small wrapper function used to get an integer number of cores, based on the user selection via njobs: - njobs = 0, set it to 1 core (serial) - njobs > 0, set it to njobs cores (parallel) - njobs < 0, set it to njobs * th...
f026e4a748e25175f335eceebb2e709cb310bf5e
317,876
import re def hashtag(phrase, plain=False): """ Generate hashtags from phrases. Camelcase the resulting hashtag, strip punct. Allow suppression of style changes, e.g. for two-letter state codes. """ words = phrase.split(' ') if not plain: for i in range(len(words)): try: if not words[i]: del word...
b6e7ab647330a42cf9b7417469565ce5198edd4f
703,665
def get_device_name(doc): """ Finds device name in the document title :param doc: docx Document instance :return: device name as string """ found = False for paragraph in doc.paragraphs: if found: title = paragraph.text for word in str(title).split(): ...
e2b1201a6425b345f1e0c20d7d1afe5a8774aaa8
358,152
def is_number_offset(c_offset): """ Is the offset a number """ return 0x66 <= c_offset <= 0x6f
6606048314047de7f59e77e01f48e438d4113159
34,107
def validate_higlass_file_sources(files_info, expected_genome_assembly): """ Args: files_info(list) : A list of dicts. Each dict contains the file's uuid and data. expected_genome_assembly(str, optional, default=None): If provided, each file should have this ge...
42124e5a3132861dc3a81b8751859630761b80d2
653,908
def is_file_wanted(f, extensions): """ extensions is an array of wanted file extensions """ is_any = any([f.lower().endswith(e) for e in extensions]) return is_any
c84250126c9700966248b969ded3121ae2c96764
26,558
import io def s_map(p_string, domain, mapping): """ Replaces all characters of the `domain` in `p_string` with their respective mapping in `mapping`. The length of the domain string must be the same as the mapping string unless the mapping string is empty or a single character, in which case all domain charact...
032f46aab9be5443ea118184068406b97391d785
544,112
def train_supervised( model, input_tensor, y_true, loss_fn, optimizer, multiclass =False, n_out = 1, ): """ Helper function to make forward and backward pass with minibatch. Params ------ n_out (int, default = 1) Dimensionality of output dimension. Leave ...
a17d0e883c281b7f5275dcc242e45c1537e8df57
418,692
def is_profile_flag(flag): """ return true if provided profile flag is valid """ return flag in ('cpu', 'mem', 'block', 'trace')
27931fe812840ffa935595d145b80c8073de0c70
611,537
def get_micro_secs(real_str: str) -> int: """ If there is a decimal point returns fractional part as an integer in units based on 10 to minus 6 ie if dealing with time; real_str is in seconds and any factional part is returned as an integer representing microseconds. Zero returned if no factional part ...
33f602bbfff3f18510609beaa7a2153b6ab35c9e
619,303
from typing import List def _get_difference_by(fields1: List[str], fields2: List[str]) -> List[str]: """Get list with common fields used to decimate and difference given Datasets Args: fields1: Fields of 1st Dataset fields2: Fields of 2nd Dataset Returns: List with common fie...
f80b36788c895269e41f6b2a67fe8961c58fb73c
38,453
def list_to_lowercase(l): """given a list of strings, make them all lowercase.""" return [x.lower() for x in l if type(x) is str]
c7dfee82d633e43d776dfb29924aa2c0f3b8a089
130,094
def playback_settings(framecount, days, sleep_sec): """Determine how many frames to skip based on days for total movie playtime and sleep time between screen refreshes. Returns tuple of (sec-to-sleep, frames-to-skip). """ sec_to_play = days * 24 * 60 * 60 frames_to_display = sec_to_play / ...
6faea961d4e1edc5d4470256ccf1c025205ba111
285,482
import torch def mpjpe(predicted, target): """ Mean per-joint position error (i.e. mean Euclidean distance), often referred to as "Protocol #1" in many papers. """ assert predicted.shape == target.shape #l2_error = torch.mean(torch.norm((predicted - target), dim=len(target.shape) - 1), -1).squ...
d4f0d8ec6f611e064a97b55fe990a21a519efde8
299,423
def check_number_threads(numThreads): """Checks whether or not the requested number of threads has a valid value. Parameters ---------- numThreads : int or str The requested number of threads, should either be a strictly positive integer or "max" or None Returns ------- numThreads ...
a8d683d5c265f43567031e8c10314efad2411ec9
42,809
def get_nx_pos(g): """Get x,y positions from a NetworkX CONSTELLATION graph. The returned dictionary is suitable to pass to networkx.draw(g, pos).""" pos = {} for n in g.nodes: x = g.nodes[n]['x'] y = g.nodes[n]['y'] pos[n] = x, y return pos
5004ae7e3314cc95a691e14b4e3acb3487b50982
416,906
def sanitize(guid: str) -> str: """ Removes dashes and replaces ambiguous characters :param guid: guid with either dashes or lowercase letters or ambiguous letters :return: sanitized guid """ if not guid: return '' guid = guid.replace('-', '').upper().replace('I', '1').replace('L', ...
fbb8c5e241e71f0919a55d89d805be6dfb5ac631
421,846
import json def get_dict(raw_json: bytes) -> dict: """ In the database our dictionaries are stored as raw bytes, this function returns them decoded and transformed back as dictionaries. :param raw_json: A JSON represented as raw bytes string :return: A dictionary from the decoded bytes """ ...
f911bcc5bcf4842a8c1692708b259fd9b546dca7
266,401
import math def gauss_objective(x, amplitude, sigma, mu): """Gaussian distribution objective function. This differs from many normal distribution equations online but the amplitude is required to stretch the Gaussian upward to match your specific data size. This equation was adapt...
5d98c35a900361c44bd2110d3325f5b58b1a3ca2
420,965
def customiseFor34120(process): """Ensure TrackerAdditionalParametersPerDetRcd ESProducer is run""" process.load("Geometry.TrackerGeometryBuilder.TrackerAdditionalParametersPerDet_cfi") return process
812279d18922ad1b3130447697f1010ac85b035e
632,523
def generate_progress_bar(percentage): """Generates the progress bar that can be used in a tweet Args: percentage (integer): Percentage progress to Christmas day Returns: string: Progress base using present emojis to visually show the progress of reaching Christmas day """ ...
91fb40078eca888fe6fe18292269009ad08c8844
522,212
def search_key(usb_dict, ids): """ Compare provided IDs to the built USB dictionary. If found, it will return the common name, otherwise returns the string "unknown". """ vendor_key = ids[0] product_key = ids[1] vendor, vendor_data = usb_dict.get(vendor_key, ['unknown', {}]) product = 'un...
f2ef7128ca7fd18f45cc0ce2251aca3985f71c38
358,573
def metadata_from_box(box): """Return a metadata from box.""" return {"box_id": box.box_id, "name": box.name, "owner": box.owner, "created_at": box.created_at}
498a14d32f5b8ad3b50165477fa8aa6de44c6805
414,123