content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def count_attached(mol): """ Counts the number of atoms labelled 'attached'. Parameters ---------- mol : :class:`rdkit.Chem.rdchem.Mol` A molecule to have 'attached' atoms counted. Returns ------- :class:`int` The number of atoms with the property 'attached' in `mol`. ...
4fee5a3aa650609e1365fbb2e6b73dedffcf5e24
677,110
def remove_method_from_itemname(itemname): """Return an itemname without any method name in it""" return itemname.split(':')[0]
3b55116dfd88d4348e968ffdbcae0f2f3a9398d4
677,111
def num(s): """Function will try to convert the variable to a float. If not possible it will return the original variable.""" try: return float(s) except: return s
d867980a3663a13af12f25e750cc03f638e4cabd
677,112
import inspect def is_class(obj): """ Returns True if obj is a class, else False. """ return inspect.isclass(obj)
5a49139a19ca9b2d0108e1db10a1d558b81ed5de
677,113
def sum_even_values(d: dict) -> int: """Returns the sum of all even values in d, using recursion if d contains nested dictionaries.""" total = 0 for value in d.values(): if type(value) == int: if not value % 2: total += value elif type(value) == dict: ...
3de76e3ac86ce7958f9f07584103229f70950da4
677,114
import re def string_builder(string): """ To match DaCe variable naming conventions, replaces all undesired characters with "_". """ newstring = string if string[0].isdigit(): newstring = "_" + string out = re.sub("[^a-zA-Z0-9_]", "_", newstring) return out
cbb1ec2270c6fab997dd2dfd69a26339abf05728
677,115
def dfs_for_cc(grid, point, visited, island): """Returns a list of all vertices within one island. Parameters: point(tuple): the coordinates of the starting point visited(set): all other points visited in the overall grid so far connected(list): collection of points visted so far in...
3cec43075165143a1c349e8314d0b504a50f016f
677,116
def main(): """Funçao index""" print('Init do main_route') #window_id = str(get_window_id()) #print('1') #set_base_context(window_id) #print('2') #ctx_dict = get_context(window_id) ctx_dict = {'titulo':'Portal de Compras Públicas'} #ctx_dict['window_id'] = window_id #ctx_dict['na...
ce09328b00ea737590676bb1ce3f5d01552e92a6
677,117
def get_action_desc(action_type): """ Called by generate_card Used to filter / modify any alert categories action_type: raw alert category :return: More friendly name of the alert category """ return action_type
5e1be5f4c9dbc526f69c43491ce7104a9658f0d6
677,118
import itertools def longest_common(words): """ Наибольший общий префикс нескольких слов """ char_tuples = zip(*words) prefix_tuples = itertools.takewhile(lambda x: all(x[0] == y for y in x), char_tuples) return "".join(x[0] for x in prefix_tuples)
fbf29b47b86f73f7c36f81a33c8562e4f8bf1f03
677,119
import multiprocessing def is_main_process(): """ Good for wrapping some code sections which you don't want to run during the import of a sub-process. Useful for module-level code such as singletons :return: True if we're in the main process """ return multiprocessing.current_process().name =...
6549951605bafadf662c1e55b20f187cec597fc9
677,121
def filter_topic(df, pop=0): """ Return judgement on given popular topics """ return df[df['group'] == pop]
4fa6a469f7cdf9137b9c68ca131ec36f47c38ac9
677,123
def translate_service_orm_to_json(orm): """Translate ORM to JSON for response payload.""" ret = {"service_id": orm.service_id, "schema": orm.schema, "config": {}} for config in orm.configs: if config.hostname not in ret["config"]: ret["config"][config.hostname] = {} ret["config"]...
2f0c26dfbf00d9d703200512c1874d49494658dd
677,124
import socket def try_address(fqdn): """ Check if the fqdn is valid Args: fqdn (str): fully qualified domain name """ try: socket.gethostbyname_ex(fqdn) except (socket.gaierror, UnicodeEncodeError): return False else: return True
c78be3aed0bb4418d0785f6a368da4bdfdc1134d
677,125
def _zh_len(s): """ Calculate text length in Chinese """ try: return len(s.encode("gb2312")) except ValueError: return len(s)
58aabcf3b9d4760e783a034f09bea15c9452ab11
677,126
import inspect def _is_non_defaulted_positional_args(param: inspect.Parameter) -> bool: """Returns True if `param` is a positional argument with no default.""" return ((param.kind == param.POSITIONAL_OR_KEYWORD or param.kind == param.POSITIONAL_ONLY) and param.default is param.empty)
a001f9130f3e5be1acad61959faf5e9ef66c19f1
677,127
def idems(dit): """Convenience function for iterating dict-likes. If dit.items is defined, call it and return the result. Otherwise return dit itself. """ return dit.items() if hasattr(dit, 'items') else dit
e9fa755e7187bee24a1682380c62d38bd9d8a50d
677,128
import os def get_device_name(): """ Returns the balena name of the device, if running a local docker build, run before starting docker: export BALENA_DEVICE_NAME_AT_INIT="chosen_name" """ return os.environ["BALENA_DEVICE_NAME_AT_INIT"]
2cb84ddcca791ec3f22dc11d8f38a18c648f9dcb
677,129
def extract_terminals_mod(matrix) : """ Extracts and logs the terminal states in the graph. """ terminals = [] for i in range(len(matrix)) : flag = True for j in range(len(matrix[i])) : if matrix[i][j] != 0 : flag = False break if flag : ...
f3455471af590e8d916558c8b7c121ca8d2091b8
677,130
def reached_eof(stream): """ """ token = stream.get_token() if token == "": return True else: stream.push_token(token) return False
da97fe483e3c43966573635d93083c84c49e187b
677,131
import math def calc_free_space_path_loss(distance, dl_frequency, random_variations): """ Calculate the free space path loss in decibels. FSPL(dB) = 20log(d) + 20log(f) + 32.44 Where distance (d) is in km and frequency (f) is MHz. Parameters ---------- distance : float Distance be...
0316410980178a65c837794825706354bc1fe165
677,132
import math import torch def inverse_gnomonic_projection(x, y, center_coord=(0.0, 0.0)): """ Computes the projection from the map to the sphere """ center_lon, center_lat = center_coord rho = (x**2 + y**2).sqrt() c = rho.atan() lat = (c.cos() * math.sin(center_lat) + y * c.sin()...
fd564dba0dcd2846f8558a582a7b1a96f200bc03
677,133
def _network_query(v): """Return the network of a given IP or subnet""" return str(v.network)
342a7c511cc4b37caf2f706a209d3a7edec0e49c
677,134
def parse_data_url(data_url): """ Parse a data url into a tuple of params and the encoded data. E.g. >>> data_url = "data:image/png;base64,ABC123xxx" >>> params, encoded_data = parse_data_url(data_url) >>> params ('image/png', 'base64') >>> data 'ABC123xxx' """ # e....
b06819b02d4453ec60b9875251484f01b19aa09f
677,136
def are_strings(*args): """Tells wheter all the argument passed are of type string""" return all(map(lambda _: type(_) is str, args))
88277b7be08d6cc1a0fdbc1300f955797000c53b
677,137
def _check_diff(base, obj): """ 取差集 :param base: 基准 :param obj: 对象 :return: """ res = list(set(base).difference(set(obj))) return res
1f6ffe8158ef072ce45d5fa2ddd371d8152d31a5
677,138
from functools import reduce def isurl(url): """Determine if this is a supported protocol""" prefixes = ('file:','http:','https:','ftp:','ftps:','gsiftp:') try: return url.startswith(prefixes) except Exception: try: return reduce(lambda a,b: a or url.startswith(b), prefixes...
e78a373a1acd87e4f7e6b935f18c6476739cb646
677,139
def get_host(environ): """ Return the real host for the given environment. """ if 'HTTP_X_FORWARDED_HOST' in environ: return environ['HTTP_X_FORWARDED_HOST'] elif 'HTTP_HOST' in environ: return environ['HTTP_HOST'] result = environ['SERVER_NAME'] if (environ['wsgi.url_scheme'...
5d8bedd1d4bdfe80ff135042929649d1e0d5e826
677,140
import os def _GetPreferredShell(path, default='bash'): """Returns the preferred shell name based on the base file name in path. Args: path: str, The file path to check. default: str, The default value to return if a preferred name cannot be determined. Returns: The preferred user shell name...
faa54e27e649e87f2153656ff2b7b50083a920b1
677,141
def any_difference_of_one(stem, bulge): """ See if there's any difference of one between the two ends of the stem [(a,b),(c,d)] and a bulge (e,f) :param stem: A couple of couples (2 x 2-tuple) indicating the start and end nucleotides of the stem in the form ((s1, e1), (s2, e2)) :pa...
8fbd986943286443f9a177a5b3336fa920fbd649
677,142
def _unpack(match_group): """Returns instead of a `Match` object only it's value, also if we have only one Match, return it instead of returning a list with one `Match` """ unpacked = [match.value for match in match_group] if len(unpacked) == 1: unpacked = unpacked[0] return unpacked
c1ee109c87d1382c2e6f3457b1b871cc050f56cd
677,144
def fuzzy_not(mfx): """ Fuzzy NOT operator, a.k.a. complement of a fuzzy set. Parameters ---------- mfx : 1d array Fuzzy membership function. Returns ------- mfz : 1d array Fuzzy NOT (complement) of `mfx`. Notes ----- This operation does not require a unive...
f96d1c90838789daa204f1d61db62cb9736d9ab1
677,145
import torch def get_dev_mem_used(): """Return memory used in device.""" return torch.cuda.memory_allocated() / 1024. / 1024.
ce3bedec58df5f3230228b06fcab5cdcd4dc64b6
677,146
def get_group_cv_splits(groups, cv): """ Presplit the groups using the given cross-validation scheme. Normally, the train/test split is done right before training and testing, but this function will presplit the data for all cross folds before any training/testing is done. This is us...
1eeea2193d836b48a03dac56b3ae94af2b31839c
677,147
from typing import List def counting_sort(arr: List[int], limit: int): """ Counting Sort Algorithm T(N): Best Case: Ω(n + k) Avg. Case: Θ(n + k) Worst Case: O(n + k) S(N): O(k) where, k -> the largest value exists in the array :param arr: An a...
24e6afe795cb8400ff5ec2914fae388b3a558409
677,148
def power_pump(flate_pump_feed, rho_F, g, head_pump, ECE_motor, ECE_trans): """ Calculates the power of pump. Parameters ---------- flate_pump_feed : float The flow rate pump for Feed [m**3 / h] rho_F : float The density of feed, [kg / m**3] head_pump : float The hy...
9571fe2c80c2da9d69b51ec52ac2b8942b267261
677,149
def bin2hex(strbin): """ Convert a string representing a binary number into a string representing the same value in hexadecimal format. """ dic = { "0000":"0", "0001":"1", "0010":"2", "0011":"3", "0100":"4", "0101":"5", "0110":"...
7069dba59e699acbeb53cf9ea78c8e169ce60de9
677,150
def df_by_type_splitter(dataframe): """ a larger dataframe into immediately identifiable numeric and other type dataframes""" num_df = dataframe._get_numeric_data().copy() cat_df = dataframe.select_dtypes(exclude = [int, float]).copy() return num_df, cat_df
43b5edbfca2671e38578c50c6c64111a3dace881
677,151
def walk_derivation(derivation, combiner, leaf): """ Traverse a derivation as returned by parser.item.Chart.kbest. Apply combiner to a chart Item and a dictionary mapping nonterminals (and indices) to the result of all child items. """ if type(derivation) is not tuple: if derivation =...
ab4b9b1c3d5cf9ae2b053f8de8b832892c77634e
677,152
import re def canonical_domain(dom: str) -> str: """ Transform a provided URL into a uniform domain representation for string comparison. from DINO: database_processing.py """ canon_dom = re.sub("^http(s)?://", "", dom) canon_dom = re.sub("^www", "", canon_dom) canon_dom = re.sub("^\\.", "...
74e4280195697b005a258583fcb6af46d4867302
677,153
def _representLattice(dumper, lat): """! Create a YAML representation of a Lattice using a `!lattice` node. """ if lat.nx() > 1: adj, hopping = zip(*[([i, neigh[0]], neigh[1]) for i in range(lat.nx()) for neigh in lat.getNeighbors(i) if ...
4bcae843b87a70850c7fe35a74215831b5b15ca2
677,154
def get_device_fn(device): """Choose device for different ops.""" OPS_ON_CPU = set([ 'ResizeBilinear', 'ResizeBilinearGrad', 'Mod', 'Hungarian', 'SparseToDense', 'Print', 'Gather', 'Reverse' ]) def _device_fn(op): if op.type in OPS_ON_CPU: return "/cpu:0" else: return device re...
a7761338bd9800ff7a90143b05e86976bc08c63f
677,155
def memoized_knapsack(profits, profits_length, weights, capacity): """ Parameters ---------- profits : list integer list containing profits profits_length : int number of profits in profit list weights : list integer list of weights capacity : int capacity of...
9e18e81fe0adf225e607aed84bd42e48aa423b59
677,156
import re def get_skipped_reason(data): """Return test case skip reason from report string. Args: data(str): test case report Returns: str: skip reason or None """ try: reason_rules = re.compile("Skipped:(.*?)..$") return ('\n'.join(reason_rules.findall(data))).s...
fc20f07b80477ca3252adaee2f5e8269ffda74ca
677,157
import binascii import logging def checkHeader(filename, headers, size): """ The checkHeader function reads a supplied size of the file and checks against known signatures to determine the file type. :param filename: The name of the file. :param headers: A list of known file signatures for the fil...
052b5d037dbda64a4556e19e007033e9fedaeeaa
677,158
def replace_tup(tupl, old, new, count=-1): """ Creates a copy of ``tupl`` with all occurrences of value ``old`` replaced by ``new``. Objects are replaced by value equality, not id equality (i.e. ``==`` not ``is``). If the optional argument ``count`` is given, only the first count occurrences are ...
ab6ab25b3620b9d0c8729b77658bb33d5702c47c
677,159
def prepare_target(df): """ Args: df: Returns: pd.DataFrame """ df2 = df return df2
ef2d8507e33d58bfcf5b52652751c99b9094090b
677,160
def write(journal_obj, msg): """ Write to journal """ txid = msg['request_id'] step = msg['step'] rc = journal_obj.write(txid, step, msg) return rc
b774985018abb26e0c633405b54f734ee9ef4619
677,161
def identifier_to_flag(identifier): """ Turn an identifier back into its flag format (e.g., "Flag" -> --flag). """ if identifier.startswith('-'): raise ValueError('expected identifier, not flag name: %r' % identifier) ret = identifier.lower().replace('_', '-') return '--' + ret
e5af739656ef7c18a17d7a2427202c2366cf47ae
677,162
def violatesLaziness(fragment): """ conditionals are lazy on the second and third arguments. this invariant must be maintained by learned fragments. """ for surroundingAbstractions, child in fragment.walkUncurried(): if not child.isApplication: continue f, xs = child.appl...
8cc47244ae0078ec200b06575b5bdf71348bc17c
677,163
import json def view_string(s): """Recebe uma string formatada como json e retorna somente o valor 'value' da string""" try: d = json.loads(s) return d.get("valor", s) except json.JSONDecodeError: return s
fca395720799239dc963dab09d72f258815ec786
677,164
import csv def write_csv(csv_list, filename): """ writes a single csv file to the current directory :param csv_list: 2d list containing the csv contents :param filename: name of the newly created csv file :return: True if write successful, False if not """ try: with open(filename,...
281adbad93d791538d276b1a4edd884592e5c108
677,165
import numpy def _convert_to_numpy_floats(input_array): """Converts input array to numpy array of floats. :param input_array: Input array. :return: output_array: numpy array of floats. """ try: _ = 0.1 * input_array return input_array.astype(float) except: return nump...
5e2a5099c378ed487893d3eccb51d615f66e05b3
677,166
def _range_length(start, stop, step): """ return length of range """ assert(step != 0) assert(start is not None and stop is not None and step is not None) if step > 0 and start < stop: return 1 + (stop - 1 - start) // step elif step < 0 and start > stop: return 1 + (start - 1 - stop)...
90adf2279dedb92121b97a0debdf5c1675b5434b
677,167
import os def mesname(n, dirname, h=1): """ get the measurement data filename Parameters ---------- n Tx point number dirname PATH to measurements directory h height index 1|2 Notes ----- This function handle filename from WHERE1 M1 measurement campai...
7031040879a736bd8f7546f2e6329fd1df73b666
677,168
def really_simple_sort(array): """ Really simple sort algorithm for sorting an array of ints of value 1 or 2. Returns sorted array. Running time = O(n) """ A = array.copy() n = len(array) # Loop over the first to penultimate elements in array k = 0 for i in range(0, n): i...
9f5f0fa01ab7f24fb1ad1739b08daaafd11dff02
677,169
def ptsort(tu): """Return first element of input.""" return tu[0]
b5ec4c5111850b4730600c2c2844a120b62b97ad
677,170
def probe(value): """ Factorization of n by probing. :param n: value to factorize. :returns: all proper divisors of n. >>> probe(10) [1, 2, 5, 10] >>> probe(12) [1, 2, 3, 4, 6, 12] """ value = abs(value) limit = value // 2 divisors = [1] divisor = 2 while divis...
c4bcc3c0d6fb859258710ddea833fe497a731b38
677,171
def find_dict(lattice, attribute_name): """Return a dict 'attribute_name' and indices of matching elements.""" latt_dict = {} for i, ele in enumerate(lattice): if hasattr(ele, attribute_name): att_value = getattr(ele, attribute_name) if att_value in latt_dict: ...
818dc5e37e45556fe91cfec87f7975f96c9b93ca
677,172
def find_ancilla_values(counts, ancilla_qubits, ancilla_location = 0): """Returns a dictionary with a count of each possible ancilla bit string. Parameters ---------- counts : dictionary counts for each possible output bit string ancilla_qubits : int number of ancilla qubits anc...
5af09ee5e7cb6565aa7db8c7485ca59d04fc3e4f
677,173
def destroy_lvol_store(client, uuid=None, lvs_name=None): """Destroy a logical volume store. Args: uuid: UUID of logical volume store to destroy (optional) lvs_name: name of logical volume store to destroy (optional) Either uuid or lvs_name must be specified, but not both. """ if (...
221fd9f589c7ad56955c609db91ab4ef9ab3c6fc
677,174
def url_normalize(url: str): """ Convert a URL into the standard format """ if url.startswith('//'): return 'http:' + url if url.startswith('www'): return 'http://' + url if not url.startswith('http'): return 'http://' + url return url
bfdcbd8006176a65b102fee96f4f80a3fde13f55
677,175
def generate_extra_time_headline(selected_match): """ generates additional data for the headline if the result occured in extra time or not match is the match used to create the headline returns the extra time headline details """ str_nt_details = ("" if selected_match.normal_time =...
cfe314ff3a3142d64ef9f6ed7c81e215cf512998
677,176
def gaze_duration(interest_area, fixation_sequence): """ Given an interest area and fixation sequence, return the gaze duration on that interest area. Gaze duration is the sum duration of all fixations inside an interest area until the area is exited for the first time. """ duration = 0 fo...
9df438a342d61114ed6d2fc61ca5c47397e64791
677,177
def returning_available(raise_exception=False): # type: (bool) -> bool """ Tests if returning query is available :return: boolean """ try: return True except ImportError: if raise_exception: raise ImportError('Returning feature requires django-pg-returning library...
d015290bc0c348c5e518e1811cd2334d98996bfa
677,178
def decrypt(ciphertext, cipher, shift): """ Caesar decryption of a ciphertext using a shifted cipher. :param ciphertext: the encrypted plaintext to decrypt. :param cipher: set of characters, shifted in a directed to used for character substitution. :param shift: offset to rotate cipher. :return...
af487c893837356ee8ba1eed22818561d984f519
677,179
import os def check_if_staged(): """ Check if we have some staged file Since this script commits, we cannot run if we have staged files, because it would commit something we do not want to commit Return True if we have a staged file """ stream = os.popen("git status -s") gfiles = str...
cd85dc03161d9d8d2b0fcaffa63bb70621a4ab6f
677,180
import glob def make_fileslist(path_list): """Get lists of files from paths which may contains wildcards and symbols.""" ret = [] for p in path_list: ret += glob.glob(p) return ret
30a4c2eedd9c953601448281ec19221b97156732
677,181
def drop_rows(self, predicate): """ Drop the rows of dicom metadata and pixeldata frames using given predicate Parameters ---------- :param predicate: predicate to apply on filter Examples -------- >>> dicom_path = "../datasets/dicom_uncompressed" >>> dicom = tc.dicom...
63f3a42b7db615b598d697c95772a4108ae8d346
677,182
import os def config_uri(): """Establish configuration uri for initialization.""" parent_dir = os.path.dirname(__file__) gparent_dir = os.path.dirname(parent_dir) ggparent_dir = os.path.dirname(gparent_dir) return os.path.join(ggparent_dir, 'testing.ini')
14b1ae3f3191b88399af594d9639b6795b7a2622
677,183
def T1_sequence(length, target): """ Generate a gate sequence to measure relaxation time in a two-qubit chip. Parameters ---------- length : int Number of Identity gates. target : int Which qubit is measured. Returns ------- list Relaxation sequence. ""...
110a06a96423f0a4d87018c9dfba6a5505bcad32
677,184
import glob import os def _glob_subject_img(subject_path, suffix, first_img=False): """ Get subject image (pet, func, ...) for a given subject and a suffix """ img_files = sorted(glob.glob(os.path.join(subject_path, suffix))) if len(img_files) == 0: raise IndexError('Image not found i...
81f841f91911ce1931a699bbae68916256d5304c
677,185
def create_element(doc, parent, tag, value=None, attributes=None): """ Creates an XML element """ ele = doc.createElement(tag) parent.appendChild(ele) if value: text = doc.createTextNode(u"%s" % value) ele.appendChild(text) if attributes: [ele.setAttribute(k, str(v)) ...
e324e8f5d8395de1d35975457fd3a1692c0e9a35
677,186
def get_min_max_values(data, col1, col2): """ extracts min and max value of two columns :param data: ptcf data frame :param col1: column 1 :param col1: column 2 :return: dict of min and max values of two columns """ return { 'ds1_min' : data[col1].min(), 'ds1_max' : data[col1].max(), 'ds2_...
e28e31d29bcb530404e2e51358cff98e47159f41
677,187
import re def parse_tags_blocks(suite): """Get substrings from the suite string where tags are defined.""" yaml_tag_keys = ["include_with_any_tags", "exclude_with_any_tags"] yaml_tag_keys_regex = "|".join(yaml_tag_keys) all_tags_regex = re.compile(rf"(({yaml_tag_keys_regex}):\n(\s*(-|#)\s*.*)*)") ...
17f1495d7c30452e685133963c93f6bf1e202c1d
677,188
import numpy def get_wavelength_vector(start, end, logstep): """ Get the wavelength vector """ nwave = int((numpy.log10(end)-numpy.log10(start))/logstep + 1) return numpy.power(10., numpy.arange(nwave)*logstep + numpy.log10(start))
6f5e3aae31404f3f0292edd256b3e010d6692ca6
677,189
def extract_eaos(lines): """ extract info of VOT eao """ epochs = [] eaos = [] for line in lines: print(line) # if not line.startswith('[*]'): # matlab version if not line.startswith('| Ocean'): continue temp = line.split('|') epochs.append(i...
b7fd6d04aba14f23425ace35101a71dbbd6dfe94
677,190
def create_dict_node_enode(set_proj_nodes, neighbors_dict, H, node, dict_node_enode, dict_enode_node): """ A function to create useful dictionaries to represent connections between nodes that are in the embedding and nodes that are not in the embedding. :param set_proj_nodes: Set of the nodes that are i...
da2b05648dd200f98e03d3483fd3e80b225a1ee9
677,191
def upper(value): """Uppercase the string passed as argument""" return value.upper() if value else value
a5e109e0174040e06d2784c391d414c753154d5b
677,192
def pwr2modp(k, p): """Return 2**k mod p for any integer k""" if k < 0: assert p & 1 return pow((p + 1) >> 1, -k, p) return pow(2, k, p)
deeda4c153ae9d6b2409cd8047a98289f7bcd47e
677,193
def QuadraticLimbDarkening(Impact, limb1, limb2): """Quadratic limb darkening. Kopal 1950, Harvard Col. Obs. Circ., 454, 1""" return 1 - limb1 * (1 - Impact) - limb2 * (1 - Impact) ** 2
1b271c7afec301331b978e015c085ffaaa335240
677,194
import re def parse_bucket_url(url): """ Parse s3 url to get bucket name and object name. input: s3://test/templates/3.0/post_install.sh output: {"bucket_name": "test", "object_key": "templates/3.0/post_install.sh", "object_name": "post_install.sh"} """ match = re.match(r"s3://(.*?)/(.*)", ur...
eedf1ced909053c4533982e1a37f0f6decc90acb
677,195
def scan_reverse(f, arr): """Scan over a list in reverse, using a function""" r=list(arr) for i in reversed(range(len(r))[1:]): r[i-1] = f(r[i-1],r[i]) return r
db5d8461ec0c3eb9930d77104d7f055fc74b8f44
677,196
import itertools def juxtapose_text(text_a, text_b, buffer_len=15): """Places text_a to the left of text_b with a buffer of spaces in between""" lines_a = text_a.splitlines() lines_b = text_b.splitlines() longest_line_length_a = max(map(len, lines_a)) paired_lines = itertools.zip_longest(lines_a, ...
20cfb54c0e9d5978ecc00312c7a0465294684921
677,197
def walk_process_dictionary(proc_dict, keys_lineage=None, key_lineage=None, level=0, prev_level=0, break_points=None): """ Recursively walks through a dictionary until the specified key is reached and collects the keys lineage/the keys. Parameters ---------- proc_dict : ...
773a2646ee223a5a2c1dd171a37a9b5792448b50
677,198
import queue def catch_empty(func, handle=lambda e: e, *args, **kwargs): """ Returns the empty exception rather than raising it Useful for calling queue.get in a list comprehension """ try: return func(*args, **kwargs) except queue.Empty as e: return handle(e)
59dd483ca28ccc16b9aafec2c1b3926a4a1c3c99
677,199
def validate_params(params): """ Validates MMCM parameters agains legal VCO frequency range. Makes Vivado don't complain. """ # VCO operating ranges [MHz] (for xc7a35tcsg324-1 speed grade -1) vco_range = (600.0, 1200.0) mul = params["clkfbout_mult"] div = params["divclk_divide"] #...
866977b5ab05d1816f23d9969200c3dd4d1a1672
677,200
import re def get_document_type(doc): """ return document type lowercased :param doc: :return: """ type_pattern = re.compile(r'<TYPE>[^\n]+') doc_types = type_pattern.findall(doc)[0][len('<TYPE>'):].lower() return doc_types
44efe5ce68334256a8c4c2376df2fa122fbe13f4
677,201
def fix_span(dic, p): """ changing the span of words from sentence level to step level :rtype: dict """ return {'name': dic['name'], 'span': [i + p for i in dic['span']]}
d36dfa45d039342b8473755b7c0e9440651b08a9
677,202
def color2gray(x): """Convert an RGB or RGBA (Red Green Blue Alpha) color tuple to a grayscale value.""" if len(x) == 3: r, g, b = x a = 1 elif len(x) == 4: r, g, b, a = x else: raise ValueError("Incorrect tuple length") return (r * 0.299 + 0.587*g + 0.114*b) *...
d598a2fa415170ab9242a2d52f2a3b0e0942b600
677,204
def get_variables(deployment_config: dict) -> dict: """Environment variables update to support the 2 level of definition - ope for operational environment variables - app for application level environment variables """ variables = deployment_config.get("variables", {}) app_variables = variables...
5c7118a031dc8ff6096728a959053f8843bf780a
677,205
import os def get_parm_value(parameters, name, env_name, default_value): """ Get parameter value from config :param parameters: parameters :type parameters: dict :param name: parameter name :type name: str :param env_name: environment variable name :type env_name: str :param defa...
a07a7c53396fcc046886286bcab6e4a1635415a8
677,206
from csv import reader def parse_csv(filep): """Parse csv file and return dict containing site code to bandwidth mappings Keyword Arguments: filep -- file path to csv file """ bw_map = dict() with open(filep, 'r') as csvfile: bw_reader = reader(csvfile, delimiter=',', dialect='ex...
cc3ca8a74d08f5aff2dd1fe89a8dc013fbad55dd
677,207
import requests from bs4 import BeautifulSoup def get_user_reviews(movie_title): """The critic reviews is a DataFrame of lists that contain movie metadata such as the string for movie title. :param movie_title: list{movie_title:str} :return: a dictionary of lists that contain metadata regarding movi...
324f761e7e2bdec42bee0700856bbe2a98d76dbc
677,208
def pax_to_human_time(num): """Converts a pax time to a human-readable representation""" for x in ['ns', 'us', 'ms', 's', 'ks', 'Ms', 'G', 'T']: if num < 1000.0: return "%3.3f %s" % (num, x) num /= 1000.0 return "%3.1f %s" % (num, 's')
c0cf037a6a170e9fda15cc68361c38b8e1e7761c
677,209
def check_answer(guess, a_followers, b_followers): """Take the user guess and follower counts and returns if they got it right.""" if a_followers > b_followers: return guess == "a" else: return guess == "b"
16ec16e7c045f5837a31e062c2d100f300cfad32
677,210
def reverse_linklist2(head): """双指针法实现: 原理就是从head开始移动,每移动一个,就放在pre头的位置 需要保存下次的head,temp """ cur= head pre=None while cur: temp = cur.next cur.next =pre pre= cur cur = temp return pre
005a4dafb1d918ae6e45f36e36b9679c5cf3480f
677,211
def to_yellow(string): """ Converts a string to yellow color (8bit) Returns: str: the string in yellow color """ return f"\u001b[33m{string}\u001b[0m"
6ae585485464f3ac6ab1c6862cc9063bb8e672a5
677,212
def get_config(obj, name): """Get a config by name""" config_parts = name.split('.') for part in config_parts: obj = obj.get(part, None) if obj is None: break return obj
2e52fd053b511a3ce968060308c7a056c820748b
677,213
def load_class_distributions(classes_filepath): """ Load file with class information, keep the distribution data. """ with open(classes_filepath) as f: return {line.split(",")[1].strip(): int(line.split(",")[0].strip()) for line in f}
980414b03c490781e96db3480d40d8ba42db858a
677,215