content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def non_neg(x): """ return 0 if x is negative, else return x """ if x < 0: return 0 else: return x
c703b92a9481b44364ce98a64c940674da35f48d
624,885
import glob def get_file_paths_from_glob_patterns(glob_patterns): """ Return a set of files matching the given list of glob patterns (for example ["./test.sql", "./other_tables/*.sql"]) """ file_paths = set() for glob_pattern in glob_patterns: file_paths |= set(glob.glob(glob_pattern)) ...
2ad59e698d08e550b508d7f606e2f48809c49a4b
624,889
def reduce_reflex_angle_deg(angle): """ Given an angle in degrees, normalises in [-179, 180] """ new_angle = angle % 360 if new_angle > 180: new_angle -= 360 return new_angle
10737eba3e6feda3788ea57df676146d65214fd6
624,890
def func(foo, bar): """Return the args.""" return foo, bar
7fe40009d89fbe63ee7f28f32de36e1d64e7ad9b
624,891
def pct_to_kelvin(pct, max_k=6500, min_k=2700): """Convert percent to kelvin.""" kelvin = ((max_k - min_k) * pct / 100) + min_k return kelvin
860a9716733249f3a4ee6076db5fad4926befc04
624,892
def es_par(numero: int) -> bool: """Determina si un número es par o no. :param numero: Número a evaluar. :type numero: int :return: True si el número es par, False si no lo es. :rtype: bool """ return numero % 2 == 0
6beebd3b895c35db5756ee6f6908890579961cdf
624,894
import re def get_step_from_checkpoint_path(checkpoint_path): """Returns the global step for the checkpoint at `checkpoint_path`. **Note**: This function works for checkpoints that are saved in the TF format only. Assumes `checkpoint_path` corresponds to a file which contains the substring model.ckpt-{g...
d0b7bafe211cb0fd118bacd12b7974f0610d33c8
624,897
def merge_dictionaries(a, b): """ merging two dictionaries """ merged = {**a, **b} return merged
60abd66b0c63ed56edf759bf105d4aecfb558b9f
624,899
def make_portfolio(df, date_level='date'): """ Make a portfolio of assets by grouping by date and summing all columns. Note: the caller is responsible for making sure the dates line up across assets and handling when they don't. """ return ( df .groupby(level=date_level) ...
000b543d712c6074a2d447d6ab66071a85d0c1e4
624,902
def mie(r, eps, sig, m=12, n=6): """Mie pair potential. """ prefactor = (m / (m - n)) * (m / n) ** (n / (m - n)) return prefactor * eps * ((sig / r) ** m - (sig / r) ** n)
d9c9349b8b5e4f0544bd56a3000eeb12bf2508d0
624,906
import json def read_config_file(config_file): """ Read a json configuration file :param config_file: path to a json file containing the algorithm parameters :type config_file: string :return: the configuration :rtype: dict """ with open(config_file, "r") as file: user_configu...
136a40ac0d64027387be863727d2566f4896d0b7
624,908
def PrintBox(loc, height, width, style='r-'): """A utility function to help visualizing boxes.""" xmin, ymin, xmax, ymax = loc[0] * width, loc[1] * height, loc[2] * width, loc[3] * height #pyplot.plot([xmin, xmax, xmax, xmin, xmin], [ymin, ymin, ymax, ymax, ymin], style) return [xmin, ymin, xmax, ymax]
4f1b9d40b26c21fd793f7ef9ca6922162723e13c
624,910
from typing import OrderedDict def dictify(od): """Recursively replace OrderedDict with dict""" if isinstance(od, OrderedDict): return dict((k, dictify(v)) for k, v in od.items()) else: return od
886fc727dba02f9029945d5efa947d7573c3df19
624,913
def generate_list(iterable_a, iterable_b): """Return a list of a+b combinations""" result = [] for iter_a in iterable_a: for iter_b in iterable_b: result.append(iter_a+iter_b) return result
7056486507a4ac5810de42e58f5b7822a905de54
624,915
import torch def _roll_by_shifts(src: torch.Tensor, shifts: torch.LongTensor): """Roll tensor with different shifts for each row. Note: We assume the src is a 3 dimensions tensor and roll the last dimension. Example: >>> src = torch.arange(15).reshape((1,3,5)) >>> src tensor([[[...
d919ef903bda42897781efc280eb833d3a6de162
624,916
def alignto(alignment_value: int, bitposition: int) -> int: """ Aligns the bit size to the given alignment value. :param alignment_value: Value to align. :param bitposition: Current bit position where to apply alignment. :returns: Aligned bit position. """ if bitposition <= 0 or alignment_...
651d3d26c1f62192a891b3afd7e4a923d31c5aa2
624,923
def get_digit_b(number, digit): """ Given a number, returns the digit in the specified position, for an out of range digit returns 0 """ return number % 10**digit // 10**(digit-1)
2b444e1270a58bc3dd20525eb428f37ce56a655a
624,925
def _to_np_mode(mode): """Convert padding modes from `ndi.correlate` to `np.pad`.""" mode_translation_dict = dict(nearest='edge', reflect='symmetric', mirror='reflect') if mode in mode_translation_dict: mode = mode_translation_dict[mode] return mode
d568cbb7624c9eb5a8a8939480aeaa2194d91bdf
624,928
def get_abc(V, E, dE, ddE): """ Given the volume, energy, energy first derivative and energy second derivative, return the a,b,c coefficients of a parabola E = a*V^2 + b*V + c """ a = ddE / 2. b = dE - ddE * V c = E - V * dE + V ** 2 * ddE / 2. return a, b, c
b415ef889c6e912842760b5d100f99786c202c20
624,929
from typing import Union from pathlib import Path import hashlib def compute_sha256(filename: Union[Path, str]): """Return SHA256 checksum of a file.""" with open(filename, 'rb') as f: return hashlib.sha256(f.read()).hexdigest()
11831d04e7ec00886bc1ff497c836ca547f041ba
624,936
def is_int_even_v01(num): """ Use the modulo operator to evaluate whether an integer provided by the caller is even or odd, returning either True or False. Parameters: num (int): the integer to be evaluated. Returns: is_even (boolean): True or False depending on the modulo check ...
285f7ead88f3e8ba5e0ff62d52412f0023a9add3
624,941
import torch def get_cuda_memory_used(device): """ Get the free memory info of device. Notice that for CPU, this function will return 1/N of the total free memory, where N is the world size. """ ret = torch.cuda.memory_allocated() # get the peak memory to report correct data, so reset the ...
bf757ff6f3242c83522daa306c240e3cd4bc31fe
624,942
import json def load_templates_dict() -> dict: """Loads template strings dict from 'template_strings.json'. Should be hierarchy of dict->dict>values based on context. Important: Curly braces '{}' in template strings will be replaced with corresponding values using str.format For instance { ...
8c66711bd83ccd84da0735028aed15648a2b5d3b
624,943
def _get_loc_item_node(loc_json: dict, key_to_find: str) -> dict: """ Return the item node of interest within the LOC results """ for node in loc_json: if node.get('@id', '') == key_to_find: return node return {}
8956065f74ea70470a42fbc5a89418b4ce8dee44
624,947
def in_between_points_on_list(points_list, divisions): """ This takes a list of numerical values (floats or ints) and a list of divisions of ints of (points_list) - 1. This method will then uses the number of sub divisions within the list of divisions to add new points to the points list where you have ...
b1d002af6c7dc37964a6d43615d26134bcd61a5f
624,949
def fwhm(lambda_, d, alpha1=1.3): """ The nominal Full Width Half Maximum (FWHM) of a LOFAR Station beam. :param lambda_: wavelength in meters :param d: station diameter. :param alpha1: depends on the tapering intrinsic to the layout of the station, and any additional tapering which...
4dfe8718af7cf9912b31fdd55d6b6f4f8a131a51
624,951
import calendar def datetime_to_unixtime(dt_obj): """Converts datetime timestamp into a unix timestamp (as an int) Args: dt_obj (datetime): a datetime object Returns: A unix timestamp as an int """ return calendar.timegm(dt_obj.utctimetuple())
1b29a12470541623f8e8e6e51670d2b2d39bd288
624,954
import re def is_palindrome(word): """Return if word is palindrome, 'madam' would be one. Case insensitive, so Madam is valid too. It should work for phrases too so strip all but alphanumeric chars. So "No 'x' in 'Nixon'" should pass (see tests for more)""" # [^0-9a-zA-Z]+ equals \W+ ...
a51687586118390464ba39d3df4173b54aaa62ee
624,959
from pathlib import Path def localize_path(path_string): """Localize path for Windows, Unix, i.e. / or \ Args: path_string (str): path using / Returns: str: path depending on OS """ return str(Path(path_string))
71e5c3eaabfcad88001fba52914cf14aa890e34e
624,961
def merged_dict(itr): """ Create a merged dict of dict (of dict) based on input. Input is an iteratable of (keys, value). Return value is root dictionary Keys are successive dictionaries indicies. For example: (('a', 'b', 'c'), 1) would set: output['a']['b']['c'] = 1 This function...
eea694bb55f8af80d3b5018ea2b6201c20fffb41
624,962
def review_rating(review): """Return the number of stars given by the review, which is a floating point number between 1 and 5.""" return review[1]
191ea83d852dea149ba8a360695707080ca66fee
624,963
import codecs def read_vocabulary(vocab_inpath): """ Read a vocabulary file with one word per line. Args: vocab_inpath (str): Path to vocabulary file. Returns: set: Set of all words in vocabulary. """ vocab = set() with codecs.open(vocab_inpath, 'rb', 'utf-8') as vocab_in...
488098be0ae0ae282b04870ae929f2293d4f8aef
624,965
import time def is_entry_added_to_table(switch_inst, table_name, srch_params, timeout=1, expect_count=1, exist=True): """Check if entry with specified fields values is added to table Args: switch_inst(object): Switch instance to work with table_name(str): The name of table to perform search...
295f6de3b122592b1c96083ed23b648277825102
624,966
def probability_sum(probability, token_frequency, n): """Assigns score to document based on summation of probabilities. Args: probability (float): Previously calculated probability. token_frequency (float): Number of appearances of token in text. n (int): Length of text. Returns: ...
a86e8a66019e297805d4251789f71cd9140012ab
624,967
def extract_goal(goal_map): """Returns the goal location.""" for o in range(goal_map.shape[0]): for y in range(goal_map.shape[1]): for x in range(goal_map.shape[2]): if goal_map[o][y][x] == 1.: return (o, y, x) assert False
1642557163f7de95f76e0ffd2189ad8bbcd4f602
624,970
def arqexiste(arq): """ -> Verifica se existe o arquivo arq :param arq: Nome do arquivo a ser testado. :return: retorna True se o arquivo for encontrado, caso contrário False """ try: a = open(arq) except FileNotFoundError: # O arquivo não foi encontrado print('Arquivo não encontrado!') return False els...
0749a3a169e4ce9552c189fb81dae99599697f51
624,971
def calc_pid(seq1, seq2): """ Calculates the percentage ID (still as a decimal) between two sequences. Parameters ---------- seq1: str seq2: str Returns ------- pid: float """ alnlen = len(seq1) identical = 0 for i in range(0, len(seq1)): if seq1[i].isal...
31a82205b9cffa5ec7f566690ca17df635da640f
624,972
def mk_rank(rank, default_rank, level): """Create a rank from a result rank, a default rank, and a level level can be one of: "pass", "warning", "error", "open", "notApplicable", or "note". These don't correspond very well to traditional scoring, but they're all we've got. Note that the Sarif "rank" i...
339f92c186a69790cf2a5052525faf072bcd02fa
624,973
def get_text_colour_analytics_sentiment(score): """ Returns RGB code text to represent the strength of negative or positive sentiment :param score: Sentiment score in range +/- 5.0 :return: Background RGB colour text string to use in sentiment text """ # Get our score into the range [0..4], whi...
c695ee55c97c3318c837390a1c7d505d621247d9
624,976
def duplicate_package_status(original_status, override_version=None): """ Given a status generated by parse_package_status(), duplicate it for a different source package. :param original_status: the status to clone :param override_version: the cloned package version (different) :return: new status (...
2deed6ac018b6f97ddcf4423f8b30fc40996f323
624,980
def is_private(obj): """Return True if object is private.""" if obj is not None: return isinstance(obj, str) and obj.startswith('_')
648c0b765c4f96f7687d97a6ec18779778642648
624,981
def get_board_as_string(game): """ Returns a string representation of the game board in the current state. """ board_str = """ {} | {} | {} -------------- {} | {} | {} -------------- {} | {} | {} """ return board_str.format(game["board"][0][0], game["board"][0][1],game["board"][0][2],ga...
02cdbd8c3867dfee17a39a97855b38ce84bd2ed2
624,982
import re def check_convert_chr_id(chr_id): """ Check and convert chromosome IDs to format: chr1, chr2, chrX, ... If chromosome IDs like 1,2,X, .. given, convert to chr1, chr2, chrX .. Return False if given chr_id not standard and not convertable. Filter out scaffold IDs like: GL000009.2,...
a09d8c49a5c53332bea9d3cdb2e107d5a65241e7
624,983
import collections def merge(qrels, run, queries): """Merge qrels and runs into a single dict of key: query, value: tuple(relevant_doc_ids, candidate_doc_ids)""" data = collections.OrderedDict() for query_id, candidate_doc_ids in run.items(): query = queries[query_id] relevant_doc_ids = set() if ...
59d88262ba69c8dbf71f5c92b114cb5cd9b8bfc9
624,986
def poisson_pipeline(infile, outfile, depth=8): """Makes a dictionary describing PDAL pipeline for generating Poisson surface mesh. Parameters ----------- infile : str, path to file input file to be converted into a mesh outfile : str, path to file output file for storing Poisso...
5a7ba19f815e3bfc5729cf6b02ae150621230f2a
624,990
def gpsfix2str(fix: int) -> str: """ Convert GPS fix integer to descriptive string. :param int fix: GPS fix type (0-5) :return: GPS fix type as string :rtype: str """ if fix == 5: fixs = "TIME ONLY" elif fix == 4: fixs = "GPS + DR" elif fix == 3: fixs = "3D...
5a422dec590e627edef641b2990c1c856c3f4c54
624,991
def _get_exchange_key_ntlm_v2(session_base_key): """ [MS-NLMP] v28.0 2016-07-14 4.3.5.1 KXKEY Calculates the Key Exchange Key for NTLMv2 authentication. Used for signing and sealing messages. According to docs, 'If NTLM v2 is used, KeyExchangeKey MUST be set to the given 128-bit SessionBaseKey ...
e19a1b31b1a0ef638c8dd79dca476b4a3dca9366
624,994
def process_path(module_path): """ Method to obtain module and class_name from a module path Args: module_path(String): path in the format module.class_name Returns: tuple containing class_name and module """ if module_path == 'numpy.ndarray': return 'StorageNumpy', 'hec...
9e29b77351984d5a49562b179c52fe66e888acef
624,995
def _GetProfileInfoDict(profile_info): """Convert profile_info to a dict. Args: profile_info (ArtifactProfileInfo): The artifact profile_info. Returns: A dictionary containing profile info. """ ret = {} which = profile_info.WhichOneof('artifact_profile_info') if which: value = getattr(profil...
bedaa3ea996139ffba4f70c95bfa490b908a1e63
624,996
def form1(x, y, n, ind, ax, line): """Default annotation for plots with 1 line""" return f"x: {x:.5g}\ny: {y:.5g}"
7eee751b7f3b3ea8e892ddffd088f276363d8ea8
624,999
import socket def is_ipv4_address(addr): """ Check if an address is a valid IPv4 address Note that something like '1.1.1' is considered to be valid. Because '1.1.1' can be abbreviation of '1.1.1.0' """ try: socket.inet_aton(addr) return True except (socket.error, ValueErr...
e562d1fc998c156978054da5e193f5ad9827a4b8
625,000
def double_to_single_callable(application): """ Transforms a double-callable ASGI application into a single-callable one. """ async def new_application(scope, receive, send): instance = application(scope) return await instance(receive, send) return new_application
daeb00905912f1a55cf4f4e0a597d2ae2e0146a9
625,003
from typing import Iterable def build_dataset_name(estimate: int, years: Iterable) -> str: """Produce a nicely formatted dataset name.""" unique_years = sorted(set(years)) if len(unique_years) > 1: years_range = f'{min(unique_years)}–{max(unique_years)}' else: years_range = unique_year...
8c21d3dd3079443734143487a9a45f70da596e6a
625,005
from typing import Optional def get_duration(duration: Optional[float]) -> float: """Return 0 if the given duration is negative else, return the duration. >>> get_duration(None) 0 >>> get_duration(-10) 0 >>> get_duration(12) 12.0 """ if duration is None or float(duration) < 0: ...
682adedfe2d352a2413e40ed6f3b39bbf02ea7e2
625,006
def letter_only(guess, abc): """ Checks if the player's guess is a single ASCII letter only. :param abc: the alphabet used in the proverbs :type abc: str :param guess: the player's guess :type guess: str :return: True | False :rtype: bool """ if len(guess) == 1 and guess.upper()...
e6822eab984c6c8d0c15e103ced88bed348620cc
625,007
def klGaussian(mean_1, mean_2, sig2=1.): """Kullback-Leibler divergence for Gaussian distributions.""" return ((mean_1 - mean_2) ** 2) / (2 * sig2)
53d6ddfc1e6794355a532f2bf7ae4d65c828316f
625,010
def generic( target, namespace, pass_cond=None, message="deserialization object", default=None): """Deserialize object similarly to keras .get. Parameters ---------- target : object target deserialization object. namespace : object namespace to search in. Keywor...
d56a36a1b47f9a8233c6b9a40f43e797014f4c97
625,014
import socket def handle_udp_send(data: bytes, sock: socket.socket, ip: str, port: int) -> int: """Handle sending a datagram. This mainly exists so we can make a partial of it. Args: data (bytes): Message payload to send. sock (...
e813b3c91588a79d0debaf85bb6a87689a8e053b
625,016
def get_prefix(headword, length): """ Return the prefix for the given headword, of length length. Note that the procedure implemented here is the result of reverse engineering, since no official specification has been published by Kobo so far. YMMV. :param headword: the headword string ...
be7c36bcb1b46b52bef34be1ec67a7efcccabcca
625,018
def eqrr(registers, a, b, c): """(equal register/register) sets register C to 1 if register A is equal to register B. Otherwise, register C is set to 0.""" registers[c] = int(registers[a] == registers[b]) return registers
bc25cefd642f3fbc2d4aebb1217e4477bdf5b2ce
625,019
def oi_to_args(issues): """ Return a set containing all arguments in the list of open issues.""" res = set() for i in issues: res &= set(i.arguments) return res
17b3568def4e679a606ab6c715d8a37a778b1487
625,023
def to_int(value: str | None) -> int | None: """Safely convert string value to int.""" if value is None: return None try: return int(value) except (ValueError, TypeError): return None
ea64f96fdcc2317283ed9359ea6d5110dde1fc46
625,026
def smart_truncate(text, limit=100, suffix='...'): """ Truncates a text to the end of the last word before reaching `limit`, and adds `suffix` to the end. Since it is using Python's slicing, negative values work, too. :param text: <str> :param limit: <int> :param suffix: <str> :ret...
4b95d3b200f9e54adbb681f3db9206b3c5a9d7e6
625,028
import torch def get_flat_weights(model): """Gets all model weights as a single flat vector.""" return torch.cat([p.data.view(-1, 1) for p in model.parameters()], 0)
b52586d5aa7a8eea7c1adcd89a1e7d9b4ea2ac3e
625,029
def _get_ftype_from_filename(fn, ext_unit_dict=None): """ Returns the boundary flowtype and filetype for a given ModflowFlwob package filename. Parameters ---------- fn : str The filename to be parsed. ext_unit_dict : dictionary, optional If the arrays in the file are specif...
6b76b4797312f045c8bd6673d3aa74128cafbde9
625,031
import string def entry_point_name_to_identifier(entry_point_name): """Transform an entry point name into an identifier suitable for inclusion in a PyPI package name.""" try: entry_point_name.encode('ascii') ascii_name = entry_point_name except UnicodeEncodeError: ascii_name = ...
9af3e32cd0095092e53ac21b78e8233ef377db06
625,035
def get_accounts(how_many=10): """Return list of account names.""" return [f'account-{i}' for i in range(how_many)]
3b6dd6ce31bcc95b8fb4d4685d31668fba971192
625,038
import re def standardizeLocation(s, dic): """ Standardize Locations Args: s: string to standardie dic: dictionary key= pattern, value = to replace with Returns: string: standardized string or not match original string """ for loc in dic: if re.sea...
f361aef160cc4dc2a6da85fee2f7e8abf445aedb
625,039
def get_descriptive_adjectives(tree, gender): """ Returns a list of adjectives describing pronouns for the given gender in the given dependency tree. :param tree: dependency tree for a document, output of **generate_dependency_tree** :param gender: 'male' or 'female', defines which pronouns to search f...
9ce632d1a8d5a9b2cb5f53305acabd9d45ae8acb
625,041
def confirm(prompt): """ Get user confirmation from standard input. Parameters ---------- prompt: str The message to show. Returns ------- True or false depending on whether the user has answered with yes or no. """ answer = '' while answer.lower() != 'y' and answer....
61e9cd6f3626b3fe88cb8ebbf39e5fda7d3e859f
625,042
import torch def get_latent_embedding(model, data_loader, num_classes, device): """ Computes the latent embedding, i.e. z for each element of a dataset. The corresponding z values are directly organized by classes, such that they can readily be used for visualization purposes later. Parameters: ...
e10f9f82c3ddc45a7b5d7cc21fd67e78b952e4e4
625,043
def numerical_filter(df, filter_): """ Compute an boolean condition setting which rows of DataFrame `df` should remain based on the numerical filter defined in the dict `filter_`. :param df: Pandas DataFrame containing core data :param filter_: Dictionary defining the filters :return: condition...
5ddb5deef0a467256c4c2fbf74df20d826528261
625,044
def listAppend(list:list,appendObj): """Syntatic sugar. This appends the obj to the list and returns it.""" if appendObj: list.append(appendObj); return appendObj
23abab209e4ab2b1fc668355c1b366b9908024a5
625,046
import torch def GlobalAvgPooling(x): """ Input: (batch, channels, height, weight) Output: mean, (batch, channels) """ b, c, h, w = x.shape x = x.view(b, c, h*w) mean = torch.mean(x, dim=2) return mean
68e7ad05cf2ddc9cb9c8b851dfc3893b171f0cff
625,052
def epc_calc_hdr(reg_dict): """ Returns True if high dynamic range is enabled, False otherwise Parameters ---------- reg_dict : dict The dictionary that contains all the register information Returns ---------- bool True if HDR enabled, false otherwise """ hdr_en...
257c05cbd6d85a733409faa76b29954d2cf0a1b5
625,055
def get_image_urls(post): """Returns a list of URLs for all images in a scraped Post object""" image_urls = {key: val for key, val in post.flat_json_dict.items() if "display_url" in key} return list(set(image_urls.values()))
9eb09a0988deb33be4a765732a519c6c77be56fe
625,057
from typing import Callable def _get_runname( func: Callable) -> str: """Return run name from function. Args: func (Callable): target function. Return: runname (str): run name string. """ return '.'.join([func.__module__, func.__name__])
c16a9b1407817536f6f523b79f6a75f449032d38
625,058
def get_failed_conditions(conditions): """Get a comma separated string for the conditions that failed.""" if conditions is None: return '' return ', '.join([c.condition.name for c in conditions if not c.nominal])
6b329333d10305cb21dbc11254221e6737f342f5
625,060
def get_uniprot_secondaries(uniprot_result): """ Get secondary accession identifiers from UniProt text result :param uniprot_result: :return: """ accession_lines = [l for l in uniprot_result.split('\n') if l.startswith('AC')] secondaries = [] for ac_line in accession_lines: secon...
bca4cced24d2aa8f1200aee7d4bf0f05c5913bb3
625,066
import yaml def read_config(yaml_in): """ Convert YAML config file into dictionary """ with open(yaml_in) as f: return yaml.safe_load(f)
24a45aee350e9ac038fdc697f5b3dd5c8759a6bf
625,067
def clean_missing_exports_long(exports, fill_na_value=0): """Clean the exports data in long format by removing records with missing product code and then filling missing values with fill_na_value (which is 0 by default). """ return (exports.dropna(subset=['product_code']) .fillna(...
3f92b092cb4a6cae6e13945b0e1a6389cc6b3e34
625,068
def transit_x_axis_intercept(px: float, py: float, ox: float, oy: float) -> float: """Given an object at position px, py and an observer as ox, oy this returns the value on the x axis of the transit line.""" x = px + py * (ox - px) / (py - oy) return x
0903547003586cfa87718adf6a279ece4a065120
625,069
import re def truncate(text, words=25): """Remove tags and truncate text to the specified number of words.""" return ' '.join(re.sub('(?s)<.*?>', ' ', text).split()[:words])
42cc1f0520a92a6bcbc46501e37dcb6832d8f93f
625,070
def count_distinct(collection, key, exclude=None): """Get the number of distinct values for key in the specified database collection""" values = collection.distinct(key) if exclude is not None and exclude in values: values.remove(exclude) return len(values)
894428df0a3d913963c33ce2940c01305a5b700e
625,073
def make_qs(listname: list) -> str: """Create a list of '?'s for use in a query string. This is a convenience function that will take a list and return a string composed of len(list) queston marks joined by commas for use in an sql VALUES() clause. Args: listname: The...
94468ea155d87935ed9df9bf3abea939b2673f20
625,074
import re def filter_text(text): """ Filter out retweet-prefix, urls, html-codes, hashtags, handles, and extra whitespaces :param text: a string :return: cleaned text """ return re.sub( r'(RT @\S+:)|(RT)|(https?:\S+)|(&\S+;)|(@\S+)|(#\S+)', '', text )
d1b5763e62622ff3a8c87d0ade9b72b8e77ce55e
625,075
from pathlib import Path def create_hdf_dir(experiment_dir: Path, create_on_work: bool = False) -> Path: """ Create a directory in which the HDF results files for an HSR experiment can be stores and return the Path to the directory. .. attention:: Unless you are working on the MPI-IS cluster ...
6cb9c2731cba53e033b4c248f68b09f2246abb62
625,076
def requires_replacement(changeset): """Return the changes within the changeset that require replacement. Args: changeset (list): List of changes Returns: list: A list of changes that require replacement, if any. """ return [r for r in changeset if r["ResourceChange"].get( ...
6f58f9428845df630cec287f54b749cc87a489d4
625,085
import sqlite3 from typing import List def get_columns(conn: sqlite3.Connection) -> List[str]: """Get column names in the order just like it is returned from the DB. :param conn: Connection to the database :type conn: sqlite3.Connection :return: A list of column names in the database. :rtype: Lis...
0a77342e40f9f80f7ac62b3767fd7e93913a3ef5
625,089
import math def round_repeats(repeats, global_params): """Round number of filters based on depth multiplier.""" multiplier = global_params.depth_coefficient if not multiplier: return repeats return int(math.ceil(multiplier * repeats))
76f47f5ae407d252fc4343acfdbfe1c158b812dd
625,090
def get_spawn_weight(mod, tags): """ Calculates the spawn weight of the given mod for the given tags. Parameters ---------- mod : DatRecord The mod to calculate the spawn weight for. tags : list[str] List of applicable tag identifiers. Returns ------- int C...
508cc49e2f68d27492989e7acb81c874f2de4a4d
625,098
def humantime(ms): # Docstring """ Converts timespan in milliseconds to a humanly readable string. -------------- ms : int or float Time in milliseconds -------------- Examples : >>> humantime(194159) '3 min, 14 sec, 159 ms' """ time_dict = {'ms' : ...
c381cbc30c882f5bbe3ddf7ba1668b8a2211bb31
625,101
import torch def calculate_dihedrals(p, alphabet): """Converts the given input of weigths over the alphabet into a triple of dihederal angles Args: p: [BATCH_SIZE, NUM_ANGLES] alphabet: [NUM_ANGLES, NUM_DIHEDRALS] Returns: [BATCH_SIZE, NUM_DIHEDRALS] """ sins = torch.s...
381add4de653ba30b1049248666296520530a539
625,103
def find_pivot_index(nums): """ Suppose a sorted array A is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Find the minimum element. NOTE: The array will not contain duplicates. """ min_num = nums[0] pivot_index = 0 left = 0 right =...
ecfc5c3202d65d206a1d80b3aaec8de890c8b9b0
625,104
def s3_md5(s3key, blocksize=65536): """Hexadecimal md5 hash of a file stored in Amazon S3""" return s3key.etag.strip('"').strip("'")
d0d0258001fab054d26854526213015987d46bb2
625,108
def all_type(dataframe): """ Find all availble EV connector types in column ['EV Connector Types'] Attributes -------------------------- dataframe: DataFrame The DataFrame to deal Return -------------------------- type_dict: dict A list of all availible connector types ...
76907de262e9120959524a87a348a80eab1c3dfb
625,110
def find_prefix_cols(df, prefix): """List all df columns with the given prefix.""" sel = [colname.startswith(prefix) for colname in df.columns] return df.columns[sel]
1c0bec2f1f4dff4fb0e49432f51c76ff11b72c0a
625,113
import re def get_static_pattern(static_url_prefix): """Builds a regular expression we can use to find static asset references that start with the given static URL prefix. Used for finding static dependencies inside JS and CSS files and for rewriting static references in compiled assets. """ ...
6e7f089ddcc4d8229f64296723a5d6533d0a38e0
625,117
import ast def chromosomesInCluster(hotspots): """ Determine chromosomes in a hotspots file :param hotspots: str Hotspots filename :return: dict Chromosomes and first last positions within the chromosomes in the cluster """ chromosomes = dict(); with open(hotspots, 'r') ...
62d702fe4e1358dbc1c2fc62a8254a3579b34be8
625,118
def find_end_paren(function_code: str, start: int): """ Find the end location given a starting parenthesis location :param function_code: :param start: :return: """ parentheses = [] for i, character in enumerate(function_code[start:]): if character == "(": parentheses...
7644fa8f9763f98178df0da2d75825929b88a169
625,122