content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_genes_from_file(genes_fpath): """ Read a list from 1-column file """ with open(genes_fpath) as f: gene_names = set([l.strip() for l in f.readlines() if l.strip() != '']) return gene_names
635bfed7dc73c6691f95b5208041bc296fe1f0f1
599,128
def partition_by_cut(cut, rag): """Compute resulting subgraphs from given bi-partition. Parameters ---------- cut : array A array of booleans. Elements set to `True` belong to one set. rag : RAG The Region Adjacency Graph. Returns ------- sub1, sub2 : RAG ...
93e707e1223ad591d92276c4ae3397e0f4f4badb
599,130
def indeed_url(job, location, posting_offset): """Returns Indeed.com API url for job query Args: job (str): Title of job location (str): Location of job posting_offset (str): Index of first posting Return (str): Indeed url """ url = (f"https://www.indeed.com/jobs" ...
0b0be1e2409846b634b4d446f56656f1d1a344cd
599,131
import logging def contains_valid_dockercfg(config): """ Check if a given config dict contains valid dockercfg :param config: dict :return: True / False """ docker_config = config.get('dockercfg') if not docker_config: return False if not isinstance(docker_config, dict): ...
19ac2326e1d07cf94f9718b8c0f5058692ca38e8
599,135
def expand_value(value, params): """Expand str / list value with parameters by using str.format() """ if not value: return value if isinstance(value, list): value = list(map( lambda s: s.format(**params), value )) else: value = value.format(**p...
f8fe0633beb4073d16aae2a56fca70e8701778e5
599,138
def of_type(param, valid_types): """Function to check the type of a parameter. It tries to match the type of the parameter with the types passed through `valid_types` list. Args: param: A value of any type. valid_types (list): A list of acceptable types. Returns: bool: Tru...
470e8eba1935bde4bd35f2a6c6015ada2556cecf
599,141
def read_log(log_file, headers='Step Temp E_pair E_mol TotEng Press'): """Read log.lammps file and return lines for multiple thermo data Args: - log_file (str): Lammps simulation log file path - headers (str): The headers for thermo data ('Step Temp E_pair E_mol TotEng Press') Returns: ...
24b41784caee6d2c0ef0e31583f7b8a1459f012a
599,146
import math def windchillF(T_F, V_mph): """Calculate wind chill. http://www.nws.noaa.gov/om/cold/wind_chill.shtml T_F: Temperature in Fahrenheit V_mph: Wind speed in mph Returns Wind Chill in Fahrenheit """ if T_F is None or V_mph is None: return None # only va...
0d8e934bfdb2c7ce7d4f102cd1b0704193f91dd4
599,148
def layer_config(config, layer, layer_type='conv'): """layerwise configuration for a given layer-number, type and config Args: config: training configuration sampled from hyperband search space layer: layer number layer_type: whether conv layer or fc layer Returns: 1. activation name ...
3ae1e985820b733331af6dfe6c7fc1f9d42006e6
599,151
def paramToPython(p): """ >>> paramToPython(dict(name="foo")) 'foo' >>> paramToPython(dict(name="foo", optional=True)) 'foo=None' >>> paramToPython(dict(name="foo", type="integer")) 'foo: int' >>> paramToPython(dict(name="foo", type="integer", optional=True)) 'foo: int=None' """ ...
f04edda6bf5ec6bfbb9ff37a674d16dd750b7e6c
599,152
import torch def predict(images, model, decoder, device): """Make model prediction. Args: images (torch.Tensor): Batch with tensor images. model (ocr.src.models.CRNN): OCR model. decoder: BeamSearcDecoder or BestPathDecoder class from ocr.tokenizer. device (torch.device): Torc...
f489a8954cf7082ced6af53bd37e46800f169534
599,157
import re def is_valid_email(email): """Return True if email is valid There is no perfect regex match for email. Using the email regex pattern from http://emailregex.com Args: email (str): The email address to check validity for """ pattern = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-...
91dcc44acdc0014cb7c5694c4242e76551da4365
599,161
def flatten_lists(dict_item): """Flatten lists in dictionary values for better formatting.""" flat_dict = {} for k, v in dict_item.items(): flat_dict[k] = ",".join(v) if type(v) is list else v return flat_dict
9ed63a04bf1186af3c7a4eb24d5edd2108c7bd2f
599,166
def _merge_duplicate_rows(rows, metrics, key): """ Given a list of query rows, merge all duplicate rows as determined by the key function into a single row with the sum of the stats of all duplicates. This is motivated by database integrations such as postgres that can report many instances of a query t...
1d2c2509fe122bdca59cf099ed59ebfbb1ec5196
599,170
def dfs(self): """ Computes the initial source vertices for each connected component and the parents for each vertex as determined through depth-first-search :return: initial source vertices for each connected component, parents for each vertex :rtype: set, dict """ parents = {} componen...
092457d953b4d6a7377bcf4c5191cac1ac72350b
599,174
def is_attorney(descr): """ If a string description is a attorney description """ return any(map(lambda s: s in descr.upper(), ('ATTORNEY','ATTNY')))
aa45fcada75e74abb9dee686d2b662f527f0f883
599,176
def reduce_string(string_to_reduce): """Reduces a string by removing spaces and adjacent duplicate characters. Note that although I transform the string into a list and transform it back into a string before returning it, that the operations are done in-place. I perform this transformation since the operation...
8a994f103626a35cf576f92861648d46303bf645
599,177
def binary2str(b): """ Transfer binary to string :param b: binary content to be transformed to string :return: string """ return b.decode('utf-8')
bc199967a3250d4169900298a86950a6dde9d3d5
599,178
def ssln(self, fact="", size="", **kwargs): """Selects and displays small lines in the model. APDL Command: SSLN Parameters ---------- fact Factor used to determine small lines. FACT times the average line length in the model is used as the line length limit below which li...
b3cb11a699b298caf9dc9820ac83346eb10e1636
599,181
from sympy import symbols def cse_release_variables(r, e): """ Return tuples giving ``(a, b)`` where ``a`` is a symbol and ``b`` is either an expression or None. The value of None is used when a symbol is no longer needed for subsequent expressions. Use of such output can reduce the memory footpr...
151399a05e3337794876c332d667140a284fd3de
599,182
def is_leap(year): """This function takes a year and returns if it is a leap year. Param: year (positive integer) Return: boolean """ return year % 400 == 0 or year % 4 == 0 and year % 100 != 0
e14b2ef9b1a7cd719e2ce39682e0d76d9f2f30eb
599,187
import string def get_character_type(character): """ >>> get_character_type('a') 'alpha' >>> get_character_type('1') 'numeric' >>> get_character_type('.') 'punctuation' >>> get_character_type(' ') """ if character.isalpha(): return 'alpha' elif character.isnumeric()...
99e27e6f935dfc4c66068913c6b938425dc9f10d
599,192
import random def random_options(data_options, customer): """Generate a random set of four options for the problem""" options_list = data_options[customer.issue_type] options = [] for _ in range(0, 4): opt = random.choice(options_list) options.append(opt) options_list.remove(op...
28134b769ead639493355ca3c46e52989cf5bdf6
599,195
import turtle def make_window(color, title): """ Set up the window with the given background color and title. Returns the new window. """ window = turtle.Screen() window.bgcolor(color) window.title(title) return window
e3a23fddbbffd0f4851a28c327b37cebf1bcda5d
599,196
import re def get_source_mapping_url(css): """Extract the sourceMappingURL from a css string.""" # /*# sourceMappingURL=main.scss.map */ match = re.search( r'^\s*/\*# sourceMappingURL=(.*?)\s*\*/', css, flags=re.RegexFlag.MULTILINE | re.RegexFlag.IGNORECASE) if match: r...
81ba38b918f31af2745a72650d1c409790a92958
599,197
async def get_otu_count(db, ref_id: str) -> int: """ Get the number of OTUs associated with the given `ref_id`. :param db: the application database client :param ref_id: the id of the reference to get the current index for :return: the OTU count """ return await db.otus.count_documents({ ...
c43c63ea2679989aeac04a3d1577efeab07625f2
599,198
def convert_github_url_into_raw_url(github_url:str) -> str: """Convert github url into raw github url. Args github_url: github url Returns raw github url """ github_url = github_url.split("#L")[0] raw_github_url = github_url.replace("github.com", "raw.githubusercontent.com"). \ ...
9fe80a7d5c7254253a22b6fe72707c6c470350c2
599,200
def make_call_key(args, kwargs): """Stable id for function calls, can be used for caching.""" key = args if kwargs: key += "##kwargs##", tuple(sorted(kwargs.items())) return key
2ebb116b0b4bd1929de70a86c2c62bff2fb5df13
599,203
def pipeline(value, *funcs): """ Given an initial value and a list of functions, apply the functions repeatedly and return the final result.""" ret = value for func in funcs: ret = func(ret) return ret
ba9c99c557b4793b8892f4e9666c2539d12b1316
599,204
def _value_or_none(data, key): """Returns the value of data at key or None if they key does not exist or if data is not subscriptable.""" try: return data[key] except KeyError: return None except TypeError: return None
801596d37b2869967ebb864f1ec5104bd8e1a8d2
599,206
def transcribe(dna_seq): """ Transcribes the DNA sequence into RNA. """ tmpseq = dna_seq.upper(); rna_seq = '' for nucleotide in tmpseq: if nucleotide == 'T': rna_seq += 'U' else: rna_seq += nucleotide return rna_seq
f499e77fd82f92863da4d64dff60bed640cdd7c9
599,210
def dispatch(split, *funcs): """takes a tuple of items and delivers each item to a different function /--> item1 --> double(item1) -----> \ / \ split ----> item2 --> triple(item2) -----> _OUTPUT \\ / ...
5a04ea68cc218c116436783a9c27866e4297b0fd
599,211
from typing import List def tokens_to_smiles(tokens: List[str], special_tokens: List[str]) -> str: """Combine tokens into valid SMILES string, filtering out special tokens Args: tokens: Tokenized SMILES special_tokens: Tokens to not count as atoms Returns: SMILES representation o...
6579b1645f137119eb5dd226f80d7bd0302d4f9a
599,212
def get_name(line): """ Returns package name (str) of a Package: line in a control file. Parameters line : str, current line """ return line[9:].strip("\n")
8197e6449b91fb8ab30264302369ef08c4ce8e84
599,213
def valiant_app_title() -> str: """The expected app title.""" return "Valiant"
c16193dab99a5756e0ec42e8042e9e0c331f56ff
599,215
def complete_irf_name(irfs, site, exposure, azimuth=None): """ Given a list of IRFs zenith angles, the chosen site, exposure and NBS, it returns the completed name of the IRFs :param irfs: <z20|z40|z60> str (list of str) :param site: <North|South> (str) :param exposure: <100s|0.5h|5h|50h> (str) ...
3911461fb2d290c5d0f46144fd27a3c10cfc6758
599,216
from bs4 import BeautifulSoup import logging def search_product(page_content): """ Extracting product data from page. Example result: { 'Underlying Information': {'Description/Name': 'E-mini S&P 500 (ES@)'}, 'Contract Information': { 'Description/Name': 'E-mini S&P 500', ...
d821e5f5537901a0db2dbfa14758bf563b5465e3
599,218
import re def get_words_from_file(filepath): """Return the set of all words at least three letters long from within a named file. """ with open(filepath) as f: # # re.findall returns a list of all instances matching a pattern # The pattern \w{3,} matches a word at least three l...
7021e5c20b0a64ca07ca25cd20ff5e44373e8465
599,220
import re def is_slack_id(slack_id: str) -> bool: """ Check if id given is a valid slack id. :param id: string of the object you want to check :return: true if object is a slack id, false otherwise """ return re.match("^[UW][A-Z0-9]{8}$", slack_id) is not None
573dabea9a6e814d17cc91758d4a694f4737e7c0
599,221
def normalize(p): """ Naive renormalization of probabilities """ S = sum(p) return [pr / S for pr in p]
40cf1f54a74d057d2f474a476ea9d30bc3340b07
599,229
def move_exists(b): """ Check whether or not a move exists on the board Args: b (list) two dimensional board to merge Returns: list >>> b = [[1, 2, 3, 4], [5, 6, 7, 8]] >>> move_exists(b) False >>> move_exists(test) True """ for row in b: for x, y in zip(row[:-1], row...
77056abc0587f74d9cc270e548f68156c5335d9f
599,231
def compare_dicts(dict1, dict2): """Compare two dictionaries and return a dictionary of added, deleted, and replaced items.""" if not isinstance(dict1, dict) or not isinstance(dict2, dict): return (dict1, dict2) deleted = { key: dict1[key] for key in dict1 if key not in dict2 } added = { key: di...
4b7620aa4d54ef2758a10f4ffa56b5e08fb2402c
599,234
def stripUnderline(s): """Returns the string s, with underlining removed.""" return s.replace('\x1f', '').replace('\x1F', '')
2a54019d0e591490d91ef5deade97554f1e79ee5
599,236
def _or(newscore: float, oldscore: float, howold: int) -> float: """Logical 'or', but with float scores An internal utility function to weight old scores and 'or' them, i.e., add them to new scores to calculate the matches if there are misses Adds the two scores, but limits the return value to...
942d0c8286d14fd5a0ae2e4ce087fd61ff6e9316
599,237
import torch def sgd_momentum_old(w, dw, config=None): """ Performs stochastic gradient descent with momentum. config format: - learning_rate: Scalar learning rate. - momentum: Scalar between 0 and 1 giving the momentum value. Setting momentum = 0 reduces to sgd. - velocity: A numpy arr...
e4aac5fc171f98f546317b1d2c4b8bdf0dd08e3e
599,240
def facebook_recon(email): """Find facebook account if linked via email.""" if not email: return None return {'site': 'Facebook', 'url': 'https://www.facebook.com/search/people?q={}'.format(email) }
88371883ac908c81638c3e9e633e37fec46f76ac
599,241
import torch def split(input_, indices_or_sections, axis=0): """Wrapper of `torch.split`. Parameters ---------- input_ : DTensor Input dense tensor. indices_or_sections : int or DTensor If integer, specifing part of splits. Else specifing the positions where the splits tak...
f2fa0811d039b64cb303e826ff657d9510976705
599,242
def conjoin(functions, *args, **kwargs): """Returns True if all functions return True when applied to args.""" for f in functions: if not f(*args, **kwargs): return False return True
b84746e9f14373153c277727612241a2b11d20de
599,244
def map_keys(f, d): """Map a function over all keys in the dict.""" return dict((f(k), v) for k, v in d.iteritems())
8c2cf6b71d53f7128f4d066a87f88cadfa28cd6b
599,249
def for_all_test_methods(decorator, *args, **kwargs): """Generate class-level decorator from given method-level decorator. It is expected for the given decorator to take some arguments and return a method that is then called on the test method to produce a decorated method. Args: decorator: The decorato...
6878d8f6d613aa5e7267930edfe0896d54af89b6
599,251
def find_max(data): """Return the maximum value in sublist of list.""" return max([max(sublist) for sublist in data])
099ca473d7c0e8f9a2adff502b7871b2bce1b73b
599,265
import io def tourtypeday_to_tourskeleton(inst, isStringIO=True): """ Use values of TourTypeDay variables to create a "tour skeleton" which indicates days worked and days off. :param inst: Model instance :param isStringIO: True (default) to return StringIO object, False to return string :retu...
551107f8dc0d590b9ded860725a6985d35195e52
599,272
def rev_cohort_interleave(inner, cohort_size): """ Inverse of `cohort_interleave`. """ if inner % 2: return cohort_size - 1 - inner // 2 else: return inner // 2
a956e77110257951a4589c637fa35d2992d643d1
599,276
def calculate_iou(box_1, box_2): """ calculate iou :param box_1: (x0, y0, x1, y1) :param box_2: (x0, y0, x1, y1) :return: value of iou """ # calculate area of each box area_1 = (box_1[2] - box_1[0]) * (box_1[3] - box_1[1]) area_2 = (box_2[2] - box_2[0]) * (box_1[3] - box_1[1]) #...
37e4f657f24af3192be2ad408ecc62f7c1807f5b
599,280
import torch def ebased_vad(mag_spec, th_db: int = 40): """Compute energy-based VAD from a magnitude spectrogram (or equivalent). Args: mag_spec (torch.Tensor): the spectrogram to perform VAD on. Expected shape (batch, *, freq, time). The VAD mask will be computed independentl...
b5ca30d17a200141dfc985677906a7547cc81d0a
599,282
def dict_invert(d): """inverts a dictionary with immutable values Takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is ...
270b293c453f0e0fc1ad1020e83a93ea357706d4
599,285
import calendar from datetime import datetime def add_gigasecond(birth_date): """ Calculates date when the person will live 10^9 seconds. """ # this line makes me appreciating JS implementation birth_timestamp = calendar.timegm(birth_date.timetuple()) after_timestamp = birth_timestamp + 10 **...
a83bf199be30b39491a11542754fc87f0b03f6c8
599,286
def coco_category_to_parts(coco_category): """Gets list of parts name from a COCO category """ return coco_category['keypoints']
51421af7a06f0da6b41e2790d463b1a0cd9c298b
599,287
def uniform_pdf(x: float) -> float: """Uniform probability density function (PDF)""" return 1 if 0 <= x < 1 else 0
4ab59b1e71fb11300a7d7de205c74c7599cab2f0
599,289
def number_of_violated_constraints(solution): """ Returns the number of violated constraints of a solution :param solution: :return: """ return sum([1 for _ in solution.constraints if _ < 0])
e88ece652f4118bd6e9848c645be04ad4a7c99ec
599,290
def get_data(query_result): """ Retrive lists of SMILES, compound unique ids and parameters from SQL query result Args: query_result: result for SQL query containing molecular information and property Returns: lists of smiles, compound uIDs and parameters """ smiles = [item[1].rstrip()...
8a4580ced5760aab2d7530008ded3258c21afbd5
599,292
def _rid_to_ptid(rid, roster): """Returns patient id for a given rid """ ptid = roster[roster.RID == rid]['PTID'].values if len(ptid) > 0: return ptid[0] else: return ''
4457809ca3d3dea222d3f72844c5cb9e1055a540
599,294
def flatten_dict(product_model_dict): """ Converts a dict with nested attributes into a flattened dict, where the path to each attribute in the original dict maps to a key in the new dict. > d = {'a': 1, 'b': {'c': 2, 'd': {'e': 3, 'f': 4}}} > ProductModel._flatten_dict(d) ...
a1072776519b314dc971bc3447a26f828fbb60be
599,296
def portfolio_name(group_name, tag): """ Return the name of the portfolio. Parameters ---------- group_name : str The group represented in the portfolio. tag : str A unique identifier. Returns ------- port_name : str Portfolio name. """ port_name = ...
793f6f0a8d91f18a3e1e40a0e2ab52d246d36456
599,299
def getLine(x1, y1, x2, y2): """Returns a list of (x, y) tuples of every point on a line between (x1, y1) and (x2, y2). The x and y values inside the tuple are integers. Line generated with the Bresenham algorithm. Args: x1 (int, float): The x coordinate of the line's start point. y1 (int,...
b8ef483ad2686eec2494b990036abf3f6f57c951
599,302
def geologic_color_map(aquifers): """Map the aquifer codes to colors. This mapping of colors is based on the recommendations of numerous geologists and academics. Parameters ---------- aquifers : list List of four-character aquifer abbreviation strings, as defined in Minnesota ...
6687b65e0ab9b143a673e49f01c89f4e81fb0033
599,304
def binary_search(list, target): """ Search a sorted list. :param list: the input sorted list :param target: the value that is to be found :return: index of target in list, or -1 if not found """ # the initial left and right index l = 0 r = len(list) # while left is less t...
9d636e105fd8b2bf1817dde27d509952c18d0723
599,305
def interact_features(feature_df, interact_list, drop_original_columns=True): """ This function create interactions between pairs of features :param feature_df: a pandas dataframe :param interact_list: list of lists or tuples with two strings each, representing columns to be interacted. :param drop_...
97de16f1d9179d74fe2eaaa15e75ec903948814f
599,307
import math def circle_area(radius: float) -> float: """calculates the area of a circle Parameters ---------- radius : float the radius of the circle Returns ------- float the area of the circle """ return radius ** 2 * math.pi
e0a45b6fa17fbe93f98f129b1cb09ec222e66637
599,309
def wc(file_): """Takes an absolute file path/name, calculates the number of lines/words/chars, and returns a string of these numbers + file, e.g.: 3 12 60 /tmp/somefile (both tabs and spaces are allowed as separator)""" with open(file_) as f: text = f.read() filename =...
acaaa5c5a66c8eae10d97fc79cc87922334cd23d
599,310
def euclidean_algorithm(a, b, x=0, prev_x=1, y=1, prev_y=0, extended=False, step=1): """ Run the euclidean algorithm to calculate the gcd of a and b If extended is True, calculate x and y for the Bézout's identity Step is usefull to know which factor is negative => if even, it's 'y' else it's 'x' a --...
033c7762d1bf019ccc4b932f7d2084c62e68bc33
599,313
def findconnector(cycle_sets): """Determine the index of the connector cycle for a Type-II-like motif, or None if the cycles do not comprise such a motif.""" for connector_c, connector in enumerate(cycle_sets): other1 = cycle_sets[(connector_c + 1) % 3] other2 = cycle_sets[(connector_c + 2) % 3]...
e5c8657148fcd71c5a4cb4edcb9964d82a119414
599,314
def _rename_variables(ds, variableMap): # {{{ """ Given an `xarray.DataSet` object `ds` and a dictionary mapping variable names `variableMap`, returns a new data set in which variables from `ds` with names equal to values in `variableMap` are renamed to the corresponding key in `variableMap`. ...
49ea6d8a06d01061f013c829c58791746947dc39
599,320
def read_file(filename: str, ignore_char: str = "#") -> list: """ Read the file "filename" and stores it into a list of string where each element is a line of the file. For each lines, the characters after the "ignore_char" character (if present) are discarded. If the line is empty, i.e. a real empty li...
ea30ae7b2a789e4f43c69d8bcc761227072a3314
599,321
def copy_docs(original): """ Decorator function to copy docs from one function to another """ def wrapper(target): target.__doc__ = original.__doc__ return target return wrapper
05e3a22ffb4e041865fb305ca383aaeeef811051
599,322
def side_effects_factor(a: set, b: set, c: set): """ Side effect factor is similar to misses cost and is used to quantify the number of non-sensitive rules which are removed by the sanitation process. Given a transactional database D and an associated sanitised database D′ a is the set of itemsets ...
b382456049cf6e398d6d2985a1f09e37d5e7bfc2
599,326
from pathlib import Path def cache_path(archive, root_dir, build_id): """Returns a ~/.shiv cache directory for unzipping site-packages during bootstrap. :param ZipFile archive: The zipfile object we are bootstrapping from. :param str buidl_id: The build id generated at zip creation. """ root = ro...
a88b9bbb365b255e1aafb95aeaaee9b751facf5a
599,327
import pathlib def resolve_path(benchmark_path, url): """Fix a relative path from the simulation_list.yaml file Relative paths are allowed in the simulation_list.yaml. This turns those relative paths into correct URIs if not already a URI. Args: benchmark_path: path to the file with the benchm...
91a2a12d85ff96db68b9be77f7d17fdf2a54e516
599,328
def make_diff_header(path, old_tag, new_tag, src_label=None, dst_label=None): """Generate the expected diff header for file PATH, with its old and new versions described in parentheses by OLD_TAG and NEW_TAG. SRC_LABEL and DST_LABEL are paths or urls that are added to the diff labels if we're diffing against th...
aedc6ceeb5fd2c438164c0986a47a40b14331ab2
599,330
def get_outlier_regions(regions, area_threshold=3101, eccen_threshold=(0.33, 0.95)): """ Get regions of a prediction whose areas and eccentricities fall outside of the 99-th quantile of the distribution from the training dataset Parameters --------------- regions: ...
ee574ff273d38f76a41a27e9ddebfd7749413416
599,335
import random def get_random_row(queryset): """ return a single, random entry from a queryset """ random_index = random.randint(0, queryset.count() - 1) return queryset[random_index]
4cf8dcd66c77d452a66c7947a4e36f86b999858d
599,338
def getRowLocations(rowNumber): """ Return a list of all nine locations in a row. :param int rowNumber: Row :return: List of tuples :rtype: list """ return [(rowNumber, col) for col in range(9)]
5e81f1ed308e0bfa591b11b5339008a9ca7b6c0f
599,342
import torch def subsequent_mask(max_length: int) -> torch.Tensor: """Generate subsequent (lower triangular) mask for transformer autoregressive tasks Args: max_length (int): Maximum sequence length Returns: torch.Tensor: The subsequent mask """ mask = torch.ones(max_length, max_...
9612080c900e282a49e6e6e99e6fe756ba5022e1
599,344
import re def find_keywords(df, reg_dict): """ Per domain in `reg_dict`, find all matches for the "joined domain regex" in the `all_text` column of the dataframe. Store the matches in a column with the domain name. Parameters ---------- df: DataFrame dataframe with the column `all_text` ...
87aca5d3e52e294ef689978143ad528619d65809
599,347
from typing import Any def get_dict_value(d: dict, keys: list) -> Any: """Get dict value with keys. Args: d (dict): Dict. keys (list): Keys. Raises: KeyError Returns: Any: Result. """ for k in keys: # Raise KeyError. d2 = d[k] if d2 i...
a4c33ebad65ec9decefeacc53e1ce50b1aeb3e3c
599,348
def create_potential_duplicate_groups(name_instance_dict): """ Create potential duplicate groups for local clustering algorithm to analyse. Parameters: name_instance_dict: A dictionary with key: author's name string and value: name instance. Note that the author's name is cl...
d2060372c6c24f6b864a0cea9769ab1f776e17fc
599,354
def get_month_start(date): """Gets a date object with the date of the first of the month. Args: date (datetime) Returns: datetime """ return date.replace(day=1)
ff663a9c70bb45597f286f2f0a3e838242809a78
599,356
def structural_imbalance_ising(S): """Construct the Ising problem to calculate the structural imbalance of a signed social network. A signed social network graph is a graph whose signed edges represent friendly/hostile interactions between nodes. A signed social network is considered balanced if it can...
dff65964ce565c81c1182b069de112e1489adc05
599,357
def filter_frontier(frontier, pred_fns, cfg_pred_fns=None): """Filter out points from the frontier that don't pass all the pred_fns. If a pred_fn is None, ignore that metric. """ new_frontier = [] for result in frontier: cfg, qos = result keep = True if not all(f(x) for x, f ...
9719fb563271957eb64f65d4c1025d970f93478d
599,358
def QueryHasAggregateStats(result): """Checks if the given results have aggregate statistics. Args: result (spanner_v1_messages.ResultSetStats): The stats for a query. Returns: A boolean indicating whether 'results' contain aggregate statistics. """ return hasattr( result, 'stats') and getattr...
26795b69f9a8c4c90caccab78210a83fc3aa6315
599,362
from typing import List import re def filter_services(services: List[str], pattern: str) -> List[str]: """Return the list of services matching the given pattern.""" r = re.compile(pattern) return [s for s in services if r.search(s)]
05f12bab24c568bed25163d47af0af161b8b7c7e
599,364
def create_mock_resource_resp(dm): """Given an instance of Deployment, transforms into resource info as API response.""" return { "name": dm.name, "insertTime": dm.insert_time, "properties": "zone: " + dm.zone, }
6c140a2389b220b26f231c066e2d7fe108f7b117
599,368
def make_query_list(field='age', value_list=[], general_query={}): """ returns a list of queries (dicts) that all have different values for the same field. :param field: the query field for which all queries will have different values :param value_list: the list of values that makes each query distinct...
aec5b7073f3472c2efbe5c1d17b2fca5a31bab14
599,371
from typing import Any def tdub_train_axes( learning_rate: float = 0.1, max_depth: int = 5, min_child_samples: int = 50, num_leaves: int = 31, reg_lambda: float = 0.0, **kwargs, ) -> dict[str, Any]: """Construct a dictionary of default tdub training tune. Extra keyword arguments are s...
f486ecfb19138d9b8fb33fb7d371f4ef45b5a6c3
599,372
def deal_hand(deck, handSize=5): """Deals out supplied deck to the hand array and returns it.""" hand = [] for i in range(handSize): hand.append(deck.pop()) return hand
6ad1f78831f1ebfbf062c38ae02923f9b9c736c2
599,375
import re def validateEmailAddress(address): """ Determines whether a string is a valid email address. This implements the grammar from 4.10.5.1.5 of the HTML Standard. :param address: The string to test. :type address: str :rtype: bool """ # https://html.spec.whatwg.org/multipage/in...
5879ffc2b0761b28129099f16f0630f94ae4f843
599,377
import time def fetch_retry(headers, func, *args): """Error 429 from Azure is from throttling. This will wait the allotted time and retry the fetch.""" if "Retry-After" in headers: time.sleep(headers["Retry-After"]) return func(*args) else: time.sleep(30) return func(*args...
749e0c59be906291f0714576b32f80965228cce1
599,378
import torch def huber_function(x: torch.Tensor, delta: float = 1.0): """Huber function. Args: x: difference between the observed and predicted values delta: the threshold at which to change between delta-scaled L1 and L2 loss, must be positive. Default value is 1.0 Returns: ...
8e95a3cc32e14578aa3c3629667bb7a87a6e9f89
599,385
def CompareStat(tup1, tup2): """ Test equality of two stat-tuples, content-related parts only """ if tup1.st_ino != tup2.st_ino: return False if tup1.st_size != tup2.st_size: return False if tup1.st_mtime != tup2.st_mtime: return False if tup1.st_ctime != tup2.st_ctime: ...
5bccebf7c181f215ad4957feadc5cfd57beee179
599,387
import requests def fetch(path, json_file=True): """ Fetch data at a given path assuming that target match a json file and is located on the OFF API. """ if json_file: path = "%s.json" % (path) response = requests.get(path) return response.json()
f5caa75c7dccd8964240c95264a7233285fea4d4
599,388