content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def break_name(name, length): """Take a long technology name string and break it across multiple lines""" name_breaks = len(name) / length if name_breaks > 1: initial_name = name break_buffer = 0 for name_break in range(1, int(name_breaks) + 1): # preferably break at a s...
9495d574b2ce9aad24853f21987845e5cc66211b
683,388
import re def could_be_content_page(url: str) -> bool: """ Try to guess if the link is a content page. It's not a perfect check, but it can identify URLs that are obviously not content. """ url = url.lower().rstrip('/') if url.endswith('/signin') or url.endswith('/login') or \ url....
8aa139abe5d8b5b185bfdb65d9defcb4be00e068
683,389
import re def _automatic_resolve_to_location(_from_location: str, _will_decompress: bool) -> str: """Holds logic for automatic destination assignment/file suffix cleanup.""" last_term = _from_location.split("/")[-1] if _will_decompress: return re.compile(r"(?:\.gz|\.bz2)$").sub("", last_term, co...
45c1873cd24b65b33d2ba1e9f882616311413818
683,390
import sys import re def is_managed(): """ Check if a Django project is being managed with ``manage.py`` or ``django-admin`` scripts :return: Check result :rtype: bool """ for item in sys.argv: if re.search(r'manage.py|django-admin|django', item) is not None: return Tru...
b05858aefe16e23df23ad68ec49af8b301046028
683,391
def collide_rect(sprite1, sprite2): """ **pyj2d.sprite.collide_rect** Check if the rects of the two sprites intersect. Can be used as spritecollide callback function. """ return sprite1.rect.intersects(sprite2.rect)
9fdb79f31b06f350c2e6f2b9d55f45d0ffb2c1b4
683,392
def compute_image_data_statistics(data_loader): """ Return the channel wise mean and std deviation for images loaded by `data_loader` (loads WebDataset defined in `datasets.py`) """ mean = 0. std = 0. n_samples = 0. for images, bboxes, labels in data_loader: batch_samples = images.s...
7ba1f73fc663d428586113cc5f9629e3bd57656f
683,393
def get_delete_nodes_query(node_label: str, id_name: str): """ build the query to delete a node by matching the node with the given property (id_name). The query will have a parameter $id which is the matched value for the "id_name" property :param node_label: the label of the node to be deleted :p...
2daff73f941fc48bf725c99c76e298267fe717ee
683,394
import argparse def make_parser(parser=None): """ Generate an `argparse.ArgumentParser` for nbpages """ if parser is None: parser = argparse.ArgumentParser() parser.description = ('A command-line tool leveraging nbconvert to execute ' 'a set of notebooks and conve...
f6b5be134f9eae01376d420ec662dbd615903121
683,395
def int_to_roman(n): """ Convert an integer to its standard Roman Numeral representation """ V = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] S = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] out = "" for val,sym in zip(V,S): while n >= v...
3127e7d7097758872f559ef918d790f282320669
683,396
def _get_module_ver_hash(prov): """Get module commit hash, falling back to semantic version, and finally 'UNKNOWN'""" ver = None subacts = prov[0].get('subactions') if subacts: ver = subacts[0].get('commit') if not ver: ver = prov[0].get('service_ver', 'UNKNOWN') return ver
7e80448df01512d69256c71efd24b4a69f736fc8
683,397
import json def get_resource_data(resource, method='get', *args, **kwargs): """ Helper function to get data from Restful endpoints for internal use""" response = getattr(resource(), 'get')(*args, **kwargs) data = json.loads(response.get_data(as_text=True)) return data
970d82df347ca220b830d0280e0321192a742144
683,398
def NLatticeDerivativesSolver(t, x, k=([50] * 5), m=([1] * 4)): """ Returns time derivative of N-lattice phase space vector (x1, v1, ...), solve_ivp compatible """ z = [0, 0] z.extend(x) z.extend([0, 0]) return [z[i+1] if i % 2 == 0 else ((.1 / m[int((i-1)/2) - 1]) * ( ...
3898f0c8ef5abc9b1c762532284eddd61ebb46c1
683,399
def perform_bucketing(opt, labeled_pair_list): """ Groups the corpus content into the specified number of buckets of similar size; the desired number of buckets needs to be specified, whereas sentence lengths included in each bucket are inferred automatically. """ # Obtain sentence lengths sentence_...
a9e803d62e9150189060675b09eb5765c66ce8b9
683,400
def is_sane_module_spec(net): """Check if specifications of modules in net is sane. """ is_sane = True if "modules" in net: if not isinstance(net["modules"], dict): print("\nError: Modules specification in st_graph must be a dict.") is_sane = False else: ...
a40473742a1a8f5788995767cb5d772afc25a2ac
683,402
def report_type_set(): """A way to fragment the bulk data pull.""" return 'ANALYTICS,BIDMANAGER,DISPLAY,FLOODLIGHT,SEARCH,DIMENSION'
86dd853427a4b5bd6121ddb006b91210683d9fd6
683,403
def get_nominal_conc(df, species): """ Get the nominal hector concentration for a given species Parameters ---------- df : Pandas DataFrame DataFrame containing output from a nominal hector run species : str Species to retrieve output for Return ------ speci...
ee483789de7c46e7d22568c48a15f039bce7a5f1
683,406
import argparse as ap def parse_cli(): """parse commandline arguments Defines: --nodefile [nodes.dyn] --elefile [elems.dyn] --partid [1] --xyz [(xmin, xmax, ymin, ymax,...)] --numElem [(x, y, z)] Returns: args: CLI arguments """ par = ap.Argumen...
c238e6ca8f69f58e0c29de54e3044b199181a0da
683,407
def normalizeNuclideList(nuclideVector, normalization=1.0): """ normalize the nuclide vector. Parameters ---------- nuclideVector : dict dictionary of values -- e.g. floats, ints -- indexed by nuclide identifiers -- e.g. nucNames or nuclideBases normalization : float Returns -...
478496e0d84a9423ea85f7f7d20bbf9090dec042
683,408
def gpib_control_ren(library, session, mode): """Controls the state of the GPIB Remote Enable (REN) interface line, and optionally the remote/local state of the device. Corresponds to viGpibControlREN function of the VISA library. :param library: the visa library wrapped by ctypes. :param session:...
4d9fc21bb3bca7cbd98c94c064500d0ce319e5cc
683,409
def drop_id_column(train, test): """Return a tuple containing train and test dataframes without id column. Keyword arguments: train -- the train dataframe test -- the test dataframe """ train = train.drop(['SK_ID_CURR'], axis=1) test = test.drop(['SK_ID_CURR'], axis=1) return train, test
caba705644b0d9c8c1577d35845bba60fbba99e5
683,410
def MinMaxnormalization(train, val, test): """ Parameters ---------- train, val, test: np.ndarray (B,N,F,T) Returns ---------- stats: dict, two keys: mean and std train_norm, val_norm, test_norm: np.ndarray, shape is the same as original """ ...
9ff70afe5540ba718dd4f97ce83ca7fc540f5b63
683,411
def generate_crc(binary: str) -> int: """对任意长的 01 字符串生成 CRC-16 校验码。 Args: binary: 任意 01 字符串。 Returns: CRC-16 校验码对应的整型数。 """ cur = 0xFFFF poly = 0xA001 for byte in hex(int(binary, 2))[2:]: cur ^= ord(byte) for _ in range(8): last = cur % 2 ...
ac6d79e20cb617f6837bd6eb9fd5af2b7928f3a3
683,412
def truncate(string: str, width: int, ending: str = "...") -> str: """Truncate string to be no longer than provided width. When truncated, add add `ending` to shortened string as indication of truncation. Parameters ---------- string: str String to be truncated. width: int Maxim...
66dd6ca833b6290c51eb3804792b35d291fffb2d
683,413
def split_ver_str(ver_str): """Split version string into numeric components. Return list of components as numbers additionally checking that all components are correct (i.e. can be converted to numbers). """ ver_list = [] for c in ver_str.split('.')[0:3]: if not c.isdecimal(): ...
11b204dbdbe89d5eb35422525b36b27600fb5945
683,414
def get_top_decorator(code, decoratorKeys): """ Retrieves the decorator which is on top of the current task decorators stack. :param code: Tuple which contains the task code to analyse and the number of lines of the code. :param decoratorKeys: Typle which contains the available decorator keys :retur...
23973edb61eb6c78ae81031d695a8012a785d56b
683,415
import torch def get_first_idx(numel_per_tensor): """Returns the first indices of each tensor in the :ref:`packed tensor <packed>`. See :ref:`first_idx definition <packed_first_idx>` for more information. Args: numel_per_tensor (torch.LongTensor): The number of elements (vertices, fa...
4288a45facef5ba39e9f8c82b69cb245e3a77515
683,416
def shipping_charge(method, basket, postcode): """ Template tag for calculating the shipping charge for a given shipping method and basket, and injecting it into the template context. """ return method.calculate(basket, postcode)
ced6bb9b0029a81540ae3816e5002e376a4b5a3b
683,417
import sys def get_neo_file_path(): """ 针对不同平台获取不同的卷组路径 Returns: """ if sys.platform == "darwin": return "/Users/zhangxinjian/docker-data/neo-data" else: return "/root/neo4j-data/"
17683e5b1e0148b266a0eac79e8712f7035974d6
683,418
import sys def lambda_response_ok(response: dict) -> bool: """ Check lambda function response, printing body if the call failed """ # import pdb; pdb.set_trace() failed = response.get("FunctionError") if failed: print(response["Payload"].read().decode("utf-8"), file=sys.stderr) ...
5884898d72dceb077132a53016cdb7219e0c9bca
683,419
def get_element(root, childElementName): """ parameters: root: 根节点 childElementName: 字节点tag名称 return: elements:根节点下第一个符合的子元素对象 """ element = root.find(childElementName) return element
25c80ebd45df9518c802332546508f9951c59708
683,420
import re def _re_compile(regex): """Compile a string to regex, I and UNICODE.""" return re.compile(regex, re.I | re.UNICODE)
ae312d1f3519171161ce394770c5d7115d8ac348
683,422
import re def string_found(string1, string2): """ This function looks for a string :param string1: :param string2: :return: """ if re.search(r"\b" + re.escape(string1) + r"\b", string2): return True return False
d2ec6fc27318cf5be6aa390ba8f3432f1c67978b
683,423
from io import StringIO def df_to_csv_string(df): """Converts pandas DataFrame to a CSV string.""" out = StringIO() df.to_csv(out, encoding='utf-8') return out.getvalue()
9445a71583a7458bbffae2950097b371b02d89c4
683,424
def left_shift(number, n): """ Left shift on 10 base number. Parameters ---------- number : integer the number to be shift n : integer the number of digit to shift Returns ------- shifted number : integer the number left shifted by n digit Examples ...
e1d088fbfc2c64d8a976a15c26ce33b89824ad79
683,425
import math def calculate_distance(location1, location2): """ Calculates the distance between two pairs of lat, long coordinates using the Haversine formula Inputs: location1 - [lat, lon] array with first location location2 - [lat, lon] array with second location Outputs: ...
7cca5bc7b06440eb548d41879f5c4f2b876c9076
683,426
import re def rmsp(s): """Replace multiple spaces with one. """ return re.sub(r"\ +", ' ', s.strip())
f65a345cb60e012d7ec6a02276f3aff5bf8fb938
683,427
def ir(some_value): """ Rounds and casts to int Useful for pixel values that cannot be floats Parameters ---------- some_value : float numeric value Returns -------- Rounded integer Raises ------ ValueError for non scalar types """ return int(round(so...
8b487dd1b3c7a4d1095c70d6112916002642fd73
683,428
def decibels_to_amplitude_ratio(decibels): """The ratio between two amplitudes given a decibel change""" return 2 ** (decibels/10)
89940e9dfa38f45332159f34ade2e6bc4344daf1
683,430
def alo_mundo(): """ https://wiki.python.org.br/ListaDeExercicios Faça um Programa que mostre a mensagem "Alo mundo" na tela. :return: String """ return print('Alo Mundo')
ef10401f542440efc81db8355d25300fb85a5a40
683,431
import random def randomPort(): """Get a random integer in the range ``[1026, 65530]``. The reason that port 1025 is missing is because the IPv6 port (in the ``or-address``/``a`` lines), if there will be one, will be whatever the random ORPort is, minus one. The pluggable transport in the extrai...
c4b5a215d8af68f4a82b2d3a9c8aecae5e47953f
683,432
import numpy as np def unlist(nestedList): """Take a nested-list as input and return a 1d list of all elements in it""" outList = [] for i in nestedList: if type(i) in (list, np.ndarray): outList.extend(unlist(i)) else: outList.append(i) return outList
9c17aae9e5233ad63155bd73787970022e3b0aa0
683,433
def _validate_chapter(chap): """ Checks that chapter is valid (i.e has valid length) """ start = chap['start'] end = chap['end'] if (end - start) <= 0: msg = "WARNING: chapter {0} duration <= 0 (start: {1}, end: {2}), skipping..." print(msg.format(chap['id'], start, end)) ...
380df3470148ad42ee945b869872ffc731eec294
683,434
import requests def get_stock_data(symbol, token): """Send a request to the API with the symbol and token. Return the stock data we want: Symbol, Company Name, Current Price""" url = f"https://cloud.iexapis.com/stable/stock/{symbol}/quote?token={token}" response = requests.get(url) if response.st...
ec90c7147b3d1c0c88455ee5ccc159b354deef27
683,435
import hashlib def gen_hash_key(file): """ Args: file: file that need to be computed by hash values """ try: hash_obj = hashlib.md5() with open(file, 'rb') as a_file: hash_obj.update(a_file.read()) except (PermissionError, IsADirectoryError, FileNotFoundError) a...
abc186261e52dfbb6eaddd665ae6b6af17676f2a
683,436
import numpy as np def sampler(X, y, size=1, replace=True, seed=None): """Generates a random sample of a given size from a data set. Parameters ---------- X : array_like of shape (m, n_features) Input data y : array_like of shape (m,) Target data size : int T...
38aa11b23500c8c195ed9958ac9b6c65936a6bb9
683,437
def handle_exhibition_desc(company: str, desc: str) -> str: """ Handles exhibition description special formatting needs. Returns the updated description. :param company: company name :param desc: company description """ if company.lower() == "mathworks": desc = desc.replace(" o ", "\...
d4b2de017095c375b1942c20dd00ccc64ca78ab0
683,438
import click def soft_nprocs(soft, nprocs): """Reduce the number of ranks to the largest acceptable soft value""" # If no soft specification given, use -n value if not soft: return nprocs # Filter to values between 1 and nprocs try: return max([x for x in soft if 0 < x <= nprocs])...
84c60c73cbb5d9e8436ddbef402f2c8ea1d8c096
683,439
def prox_empty(w, lamb): """! Empty function used for non-composite settings Parameters ---------- @param w : input vector @param lamb : penalty paramemeter Returns ------- @retval : return same input """ return w
65c22c46222897ce4106a9128e7c3f486cf61426
683,440
def xloop(x, lo=0): """ lo = 1 means return a loop, else just ondicate if a loop or not """ Lx = len(x) ly = [0]*Lx tbd = set(range(Lx)) lp = False while not len(tbd) == 0: i = tbd.pop() if x[i] == []: continue for j in x[i]: if ly[j] > ly[i]: ...
c92a2347b2931e42102c5cd03e6df69e36172f20
683,441
def acc(predictions, targets): """ Description ---------- Calculate the accuracy of univariate classification problem. Parameters ---------- Returns ---------- """ return 1.0 * targets[targets == predictions].shape[0] / targets.shape[0]
f3fef9c3ba8f3cab24ccda821dbc0da8e8fffe10
683,442
def _IsOverlapping(alert_entity, start, end): """Whether |alert_entity| overlaps with |start| and |end| revision range.""" return (alert_entity.start_revision <= end and alert_entity.end_revision >= start)
9d9b99fab4a481198d1aaf62bef2c951951f8f91
683,443
import torch def GTA_prop_to_hot(img, n_classes: int, width: int, height: int): """ This function turns the output of the network (given in probability format) into the most likely onehot encoded output. Args: img (tensor): The tensor with probabilities. n_classes (int): Amount of cla...
814eed702809edadc37d8d8a38085f5b2ad653c0
683,445
def geometric(n, p): """ Calculate the distribution of trials until the first success/fail Args: n (int): the total number of trials p (float): the probability of success of 1 trial Returns: float: the probability of occurance """ return (1-p)**(n-1) * p
06cbc90ad1ba1cde7286471c6eb742440a2e122a
683,446
import numpy def ilogit(x): """The reverse logit""" return 1./(1.+numpy.exp(-x))
f270ee6f49a0c33e320513da15e0198eb5607a75
683,447
import math def polar2cart(r, x0, y0, theta): """Changes polar coordinates to cartesian coordinate system. :param r: Radius :param x0: x coordinate of the origin :param y0: y coordinate of the origin :param theta: Angle :return: Cartesian coordinates :rtype: tuple (int, int) """ x...
92f55ebefb1c34989eebf008b8e371567f9adb80
683,448
def binary_search(query, array): """ Determine whether the query is in an sorted array. Return the index of the query if it is present in the array. If the query is not in the array, return -1 >>> binary_search(4, [1, 2, 3, 4, 5, 6, 7, 8, 9]) 3 >>> binary_search(8, [1, 2, 3, 4, 5, 6, 7, 8, 9...
4ce1be839b46c71671d7fe2053276fd55c8183e1
683,449
import math def magic(date: str): """Determine if date entered is a magic date. Uses math.log10 to determine the length of digits in product. """ month, date_, year = date.split(' ') month, date_ = int(month), int(date_) mm_dd_product = month * date_ lenth_product = (int(math.log10(mm_dd_...
84087607fba84bc4f4b076af812b40515766c694
683,450
def convert_to_str(d): """ Recursively convert all values in a dictionary to strings This is required because setup() does not like unicode in the values it is supplied. """ d2 = {} for k, v in d.items(): k = str(k) if type(v) in [list, tuple]: d2[k] = [str(a) fo...
ab10343e5494175567128e2f689614b7187eba08
683,451
import torch def gather(consts: torch.Tensor, t: torch.Tensor): """Gather consts for $t$ and reshape to feature map shape""" c = consts.gather(-1, t) return c.reshape(-1, 1, 1, 1)
3219f52b9fa4fb122b26cdce945732cb171157a6
683,452
def build_likes_page_from_id(user_id): """ >>> build_likes_page_from_id(123) 'https://mbasic.facebook.com/profile.php?v=likes&id=123' """ return "https://mbasic.facebook.com/profile.php?v=likes&" + \ "id={0}".format(user_id)
4fd46081e4d3d0d440aa14d48a1d0bb9a08b9412
683,453
def format_data(data: dict) -> str: """ join each title by `\\n` Args: data: json data Returns: formatted text """ raw: list = ['日期: ' + i.get('date', '') + ', 内容: ' + i.get('title', '') for i in data.get('result', [])] result = '\n'.join(raw) return re...
5a4380e94ee3fe7ac2f1ec2934749c6fa0bfc67e
683,454
def unescape_latex_entities(text): """Limit ourselves as this is only used for maths stuff.""" out = text out = out.replace('\\&', '&') return out
4f61cb0388d83e263e84a622a5cd9f9795a044fe
683,455
import torch def calculate_output_dim(net, input_shape): """Calculates the resulting output shape for a given input shape and network. Args: net (torch.nn.Module): The network which you want to calculate the output dimension for. input_shape (int | tuple[int]): The shape of the in...
d0eea20892c9f90578a6c23296cb59998d8b37aa
683,456
def genotype_prob_parser(snp, threshold): """ Filters genotypes with genotype probability lower than the threshold provided. """ changed_snps=0 snps2=0 empty_individual_snp="./." new_snp=[] for individual_snp in snp: #is it a phased genotype? if "|" not in individual_snp: new_snp.append(individual_snp) ...
d769e93070e2f9d65b5a9c225a2e8ceebd28b1e7
683,457
import time def tickcountms(): """ Returns the current value of the milliseconds counter. Returns: int: time, in milliseconds, as reported by the high-precision counter (if available). """ return int(time.perf_counter() * 10 ** 3)
0e38168801bd159e25d15762423ad190732f9f1f
683,458
import os def in_slurm_allocation(): """Check if program has been run inside slurm allocation. We detect some environment variables (like SLURM_NODELIST) that are always set by slurm. :return: true if we are inside slurm allocation, otherwise false """ return 'SLURM_NODELIST' in os.environ and 'S...
9d985d96e5a3ffecd34898af64f519bd5d8d6bb4
683,459
def markdown_escape_filter(text): """Escape special characters in Markdown.""" return text.replace("\\", "\\\\").replace("`", "\\`").replace( "*", "\\*").replace("_", "\\_").replace("{", "\\{").replace( "}", "\\}").replace("[", "\\[").replace("]", "\\]").replace( "(", "\\(")....
a3e3df8ab1d5e374b45cc75dfb92faf984e65b03
683,460
def remove_leading_zeros(numeric_string): """ >>> remove_leading_zeros("0033") '33' """ ret_val = "" for n in numeric_string: if n != "0": ret_val += n return ret_val
21460a01a34e9df68636d674c594ac3c93cc99f5
683,461
import os def check_for_completion(lis): """ Check for errored image downloads and returns the error count Parameters ---------- lis : list list of dict of input data Returns: -------- error : int the error count """ error = 0 for n in lis: if not...
cea1d6d2e73370a55fdaf4022d2453ddc5dfef43
683,462
def thousands_separator(value): """ 千位分隔符 例如传入 1000000000,返回 1,000,000,000 :param value: 需要转换的数字 :return: 格式化后的字符串 """ return '{:,}'.format(value)
c8db64e5f35df2a067ecdc8bbcb19633f8fecb88
683,463
from typing import List import math def equal_split(s: str, width: int) -> List[str]: """ Split the string, each split has length `width` except the last one. """ num = int(math.ceil(len(s) / width)) # python3 return [s[i * width: (i + 1) * width] for i in range(num)]
46ae233f314136e36913834f40576a78fdab7bdf
683,464
def checkIfUnknowElementsinList(referenceList,listToTest): """ Method to check if a list contains elements not contained in another @ In, referenceList, list, reference list @ In, listToTest, list, list to test @ Out, unknownElements, list, list of elements of 'listToTest' not contained in 'referenceL...
485370f3403546837f495a71508e032f3955b18f
683,465
import torch def onehot(indices, num_targets=None): """ To avoid `AssertionError: input and target must have the same size` Converts index vector into one-hot matrix. """ assert indices.dtype == torch.long, "indices must be long integers" assert indices.min() >= 0, "indices must be non-ne...
c44d18b07c5fac77d0fccdc69b344a79b1508391
683,466
def remove_duplicates(string): """Remove duplicate characters in a string.""" return set(string)
94dcbf21a606f86282f48ffd85622ff078c2d0f9
683,467
import re def is_valid_text(param, required=True): """Checks if the parameter is a valid field text and should follow the format of [A-Za-z] and special characters hyphen and underline. @param param: Value to be validated. @param required: Check if the value can be None @return True if the parameter...
b737e3a61828437319b4608374c9dd79a530a65a
683,468
def fuzzy_equal(d1, d2, precision=0.1): """ Compare two objects recursively (just as standard '==' except floating point values are compared within given precision. Based on https://gist.github.com/durden/4236551, modified to handle lists """ if len(d1) != len(d2): print("Length of obj...
e21fbf8f1ed8c0e313ea5bab37211126480e8cc5
683,469
def atom_is_in_ring(atom): """Get whether the atom is in ring. Parameters ---------- atom : rdkit.Chem.rdchem.Atom RDKit atom instance. Returns ------- list List containing one bool only. """ return [atom.IsInRing()]
4759a824abe5c61e0e327cacf7c449f098ad2bed
683,470
def prob1(l): """Accept a list 'l' of numbers as input and return a list with the minimum, maximum, and average of the original list. """ ans = [] ans.append(min(l)) ans.append(max(l)) ans.append(float(sum(l))/len(l)) return ans
9089518d0cbdca7c9f99e32f74d77f9a3c191c5c
683,471
import ipaddress def is_remote_local_connection(first: str, second: str): """ Decides, whether ``first`` is remote host and ``second`` is localhost :param first: the ip or host name of the first runtime :param second: the ip or host name of the second runtime :return: True, if first is remote and...
4f656bc4641065046d0dc4a58f9b466cab9b3495
683,472
import importlib from warnings import warn import imp def find_related_module(app, related_name): """Given an application name and a module name, tries to find that module in the application.""" try: app_path = importlib.import_module(app).__path__ except ImportError as exc: warn('Aut...
972f374abe7019607919cc24264f2ffe6e8b8357
683,473
def square(last, current): """last is never used, but must be included based on interface requirements of tf.scan""" return current*current
730443a6e98c4d94f508a18afaad94cdc3914fee
683,474
def wait(self): """wait for previous async exec to finish; wait is needed (i.e. the function runs in async mode) only when there is no output callback (i.e. all outputs are given by dest symvar only), or :meth:`disable_auto_wait` is called explicitly. :return: self""" self._wait() return se...
4681d396f554da58f9824b4bd6ac17f563cde4d2
683,475
def get_ns_name(uri): """ Get the namespace (the namespace is placed before the first '#' character or the last '/' character) """ hash_index = uri.find('#') index = hash_index if hash_index != -1 else uri.rfind('/') namespace = uri[0: index + 1] return namespace
faa29e28d448b6d0b571bc6cc4a62bf8840b0973
683,476
import struct def pack_date(date): """ Packs a date (assumed to be UTC) as a struct with of 16-bit, unsigned `year` (big endian), 1 byte `month`, and 1 byte `day`. """ return struct.pack("!HBB", date.year, date.month, date.day)
7b7c51d2b75b767bf2f90dbe71af65c110e02ac7
683,477
from typing import Set def allocate_mid(mids: Set[str]) -> str: """ Allocate a MID which has not been used yet. """ i = 0 while True: mid = str(i) if mid not in mids: mids.add(mid) return mid i += 1
994b871a19edde7d8551dc641884e973f427889d
683,478
def _xor(a,b): """Return true iff exactly one of and b are true. Used to check some conditions.""" return bool(a) ^ bool(b)
184ded6a4d06e586cdfcf2976e2199f1393c56a0
683,479
from typing import Any from typing import get_args from typing import get_origin from typing import Literal def is_str_literal(hint: Any) -> bool: """Check if a type hint is Literal[str].""" args = get_args(hint) origin = get_origin(hint) if origin is not Literal: return False if not len...
20e4654ba6c0459f7b664a89b4f67d5d807c3f33
683,480
from typing import Dict import copy from typing import List def _flatten_attributes(dictionary: Dict, key: str) -> Dict: """Group the key values by layer.""" copied_dict = copy.deepcopy(dictionary) entity_list: List[Dict] = copied_dict[key] grouped_by_layer = {e["layer"]: e for e in entity_list} ...
86621212bfc183dd6ab06bb3c4cc033191848e76
683,481
def get_pitch_at_time(genotype, time): """given genotype and durk time point, returns pitch being played at that durk point and whether or not pitch ends perfectly on time Args: genotype ((int, int)[]): genotype of chromosome, which is list of (pitch, dur) time (int): time point in durks ...
f38bf6b8245b5169b20abf1f3caad43fee6b7356
683,482
def fallback_handler(handler_input): """ This handler will not be triggered except in supported locales, so it is safe to deploy on any locale. """ # type: (HandlerInput) -> Response speech = ( "The Transit Time skill can't help you with that. " "You can ask when the next bus is...
040a29e136bd53609059dc6b84b86f1487320149
683,483
import os def check_file_extension(file_name, accept_ext_list): """ Return False if file's extension is not in the accept_ext_list """ if not file_name: return False _, extension = os.path.splitext(file_name) return extension.lower() in (accept_ext_list or [])
03686a8d3d13074e1f156eaf6fa99772ef063d21
683,486
def _get_source_files(commands): """Return a list of all source files in the compilation.""" return list(commands.keys())
1d4307e19acdadf06c0d54ba3c984ebcb6604f8b
683,487
from typing import Optional def str_strip_punct(token: str) -> Optional[str]: """Remove any punctuation characters.""" return None
a15c9e144516ee863c89b7988a7a0005507c0aaa
683,488
import os def _determine_project_paths(data_root): """ Map project name (subfolder) to config path, from root of examples projects. This function will initially interpret each folder immediately within the given root as a folder in which project config files are stored, and thus use that subfolde...
b9c333ddec446daeb1367dca2158e50891e80e57
683,489
def stax_conv_wrapper(fun): """ Convenience wrapper around existing stax functions that work on images """ def ret(*args, name='unnamed', **kwargs): # Some stax layers don't need to be called if(isinstance(fun, tuple)): _init_fun, _apply_fun = fun else: _init_fun...
554277201ea5aaff97bfb219b1af61f2ede7c8d9
683,490
def getIsotropicFactor(tags): """ factor to get x_resolution to equal z resolution. """ x = tags['x_resolution'] sp = tags['spacing'] return x*sp
5e2f5ad6f9b034929d5f612565c88ab17de7e8ce
683,491
def dnode(period): """ Orbit nodal precession on each rev. Orbits below GEO move (drift) Westerly while orbits above GEO move Easterly. Orbits at GEO are stationary, 0 deg drift. Use siderial day rotation for better accuracy. Arg: period [sec] Return: node precession (dn) [deg] """ ...
2933fe77fd42c3f8899db898493d0549b82e223f
683,492
def process_search_term(lookup): """ Removes any whitespace from the search string, and replaces them with the appropriate character to pass as a URL :param lookup: :return: lookup """ lookup = lookup.replace(" ", "+") return lookup
51b3d2b38aa6d538f90a855df861b674041035b1
683,493
import torch def check_gpu(gpu): """ Fuction takes one argument as boolean and provides support for gpu or cpu selection and print out the current device being used. Command Line Arguments: 1. GPU as True value that enables GPU support and use cuda for calculation, and False to enable CPU. Functio...
6b3d42843dbe9e7f287024c12233abc130ede29d
683,494
import csv import re def load_peptides(input_file, peptide_column, column_separator): """ Parses the input file and extracts all peptides occuring within the file. Peptide strings are cleaned (only valid characters retained) and returned as a set. :param input_file: The file to parse :param pepti...
2c569815cb6fe2cd3c900abd28df0d20d592a131
683,495