content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def normalize_name(name): """ Given a test name, remove [...]/{...}. Matches code in testgrid and kubernetes/hack/update_owners.py. """ name = re.sub(r'\[.*?\]|\{.*?\}', '', name) name = re.sub(r'\s+', ' ', name) return name.strip()
161a217ce940e759a34be8ff5c2a14de688cdaa1
674,201
def youngs(vp=None, vs=None, rho=None, mu=None, lam=None, bulk=None, pr=None, pmod=None): """ Computes Young's modulus given either Vp, Vs, and rho, or any two elastic moduli (e.g. lambda and mu, or bulk and P moduli). SI units only. Args: vp, vs, and rho or any 2 from la...
127d0598a4e8d53c2e31b10c53ab1fddfedc4987
674,202
def initial_workload_is_ready(ops_test, app_names) -> bool: """Checks that the initial workload (ie. x/0) is ready. Args: ops_test: pytest-operator plugin app_names: array of application names to check for Returns: whether the workloads are active or not """ return all( ...
fa789c7993f3773c125bf95989e24d7ab7f09278
674,203
def _judge_trend(df_code): """ 判断收盘价趋势 :param df_code: :return: 1:上升; -1:下降; 0:震荡 """ pct_changes = df_code.close.pct_change() if len(pct_changes[pct_changes > 0]) == 0: # 下降趋势 return -1 elif len(pct_changes[pct_changes < 0]) == 0: # 上升趋势 return 1 else: retur...
ff2d9880c086166fac9195f536a368d62d44a0c7
674,204
import collections def counter_operations(): """+, -, &, |: Numerical operations with counter elements.""" occurences_a = collections.Counter('Toad') occurences_b = collections.Counter('Roy') # a + b -> a[x] + b[x] , x € keys(a, b) # a - b -> a[x] - b[x] , x € keys(a, b) # a & b...
7d6b64f94a4811e4b8b1f459b110c88e6510d817
674,206
def _get_meeting_subject(sender, contacts, secondary_advisers): """ Construct and return a meeting subject given a sender, contacts and secondary advisers (if present). """ adviser_names = [ adviser.name for adviser in (sender, *secondary_advisers) if adviser.name ] i...
15b728b357905707c32052b7000819a8eb91382d
674,208
import logging import unittest def main(): """ Runs all unit tests :return: 0 on success """ logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') logging.info("Starting Unit Tests for CE objective..") unittest.main() return 0
38099cb48b6beb7980bc3684cc3317be14edf5f3
674,209
import hashlib def hash_password(password, salt): """ Função para encodar a senha em hash :param password: :param salt: :return: Codificação hash Hex SHA512 da senha fornecida """ password = str(password).encode('utf-8') salt = str(salt).encode('utf-8') return hashlib.sha512(passwo...
d3d26a42361407ebcb316c0a48071a2aee9c6fe6
674,210
def fib(n): """ Functional definition of Fibonacci numbers with initial terms cached. fib(0) == 0 fib(1) == 1 ... fib(n) == fib(n - 1) + fib(n - 2) """ return fib(n - 1) + fib(n - 2)
1a60a50bd01ae3c893d67a89ee0c26fb798dfecd
674,211
def duplication_consistency(set_one, set_two): """ Calculates the duplication consistency score for two sets of species :param set_one: set/list of species :param set_two: set/list of species :return: float with duplication consistency score """ union_size = len(set(set_one).union(set(set_t...
e5f84fd15d75b8dc3046e17efdc69ef4848adf3e
674,213
def fvs4(graph, k): """ fvs4 """ modif = False for v, e in graph.items(): if len(e) == 2: graph[e[0]][graph[e[0]].index(v)] = e[1] graph[e[1]][graph[e[1]].index(v)] = e[0] graph.pop(v) modif = True break return k, modif
020011556078a8c4a5bcb8e62ba4b6c22ba63a87
674,214
def _auto_correlations(n_states): """Returns list of autocorrelations Args: n_states: number of local states Returns: list of tuples for autocorrelations >>> l = _auto_correlations(np.arange(3)) >>> assert l == [(0, 0), (1, 1), (2, 2)] """ local_states = n_states retur...
f908a30d2942a5d8c305fffa54752a528a45ba7f
674,216
import re def process_clinical_significance(clin_sig): """ Processes ClinVar clinical significance string into a format suitable for OT JSON schema. Namely, splits multiple clinical significance levels into an array and normalises names (to lowercase, using only spaces for delimiters). Multiple level...
d266ca548455a50dba3c9ec0aa08a11a52eab53b
674,217
def ParseArgs(locals): """Parse all the arguments into a dict.""" __all__ = locals kwargs = __all__['kwargs']; del __all__['kwargs'] desc_generators = {} for k, v in kwargs.items(): if 'gen_desc' in k: desc_generators[k] = v for k in desc_generators.keys(): del kwargs[k] for v in des...
d850645748f24b3f50b578a56a3a6a3c12ff692a
674,218
from typing import Dict def linear_utility( exchange_params_by_currency_id: Dict[str, float], balance_by_currency_id: Dict[str, int], ) -> float: """ Compute agent's utility given her utility function params and a good bundle. :param exchange_params_by_currency_id: exchange params by currency ...
0d8346d35862a88c117d50919889735e3ef7b626
674,219
def valid_sort(sort, allow_empty=False): """Returns validated sort name or throws Assert.""" if not sort: assert allow_empty, 'sort must be specified' return "" assert isinstance(sort, str), 'sort must be a string' valid_sorts = ['trending', 'promoted', 'hot', 'created', ...
e0d45fabbe04212c8a9ca4f993c06bcd8969079d
674,220
import sys def build_mapping(prefix, allele_combinations): """ Builds an allele mapping string for pseudo-diploids. For each non-empty subset of alleles one hypothetical species is created. Args: prefix: controls name of created pseudo-diploids allele_combinations: list of string...
2ab09e5b3c7c08bc2e01dacdfdbae629984a72c0
674,221
from typing import Optional from typing import Mapping from typing import Any from typing import List def get_requires_for_build_sdist( config_settings: Optional[Mapping[str, Any]] = None ) -> List[str]: """There isn't any requirement for building a sdist at this point.""" return []
ab9ce9205bc1f394b29c88629663888a38a69b0f
674,222
def _escape_char(m): """Backslash-escape. """ c = m.group(0) if c in (",", "\\", "/"): return "\\" + c return "\\x%02x" % ord(c)
944c159697d68b321ba4a8229792b459d9a7f363
674,223
import os def config(): """ The path to all SageMaker configuration files. The directory where standard SageMaker configuration files are located SageMaker training creates the following files in this folder when training starts: - `hyperparameters.json`: Amazon SageMaker makes the hyper...
084f034fb0813181d1da96ac3a639e3641f19a16
674,224
def sum_of_square_deviations(data, c): """Return sum of square deviations of sequence data.""" ss = sum((float(x) - c)**2 for x in data) return ss
866376cd9c2426c580f7bd75980e452cff2de588
674,225
def DataArray_to_dictionary(da, include_data=True): """ Convert DataArray to dictionary Args: da (DataArray): data to convert include_data (bool): If True then include the .ndarray field Returns: dict: dictionary containing the serialized data """ fields = ['label', 'name',...
cad39855f269ab8f1c98362fecd9da02633c0ab8
674,227
import torch def _hinge_loss(positive_predictions, negative_predictions, weights, gap): """Hinge pairwise loss function. Parameters ---------- positive_predictions: torch.FloatTensor | torch.cuda.FloatTensor Tensor containing predictions for kno...
9495c63738fb23063dabc99c36c1e113c96ff845
674,228
from torch.utils.data._utils.collate import default_collate from typing import Sequence from typing import Dict def multi_supervision_collate_fn(batch: Sequence[Dict]) -> Dict: """ Custom collate_fn for K2SpeechRecognitionDataset. It merges the items provided by K2SpeechRecognitionDataset into the follow...
3b85c2ca4dcdbbd3b5d902bb2b061562401422ae
674,230
import re def reformat_original_reference(original_reference): """Remove newlines, newblocks and extraneous whitespace from the original refere.""" text = re.sub(r"\\bibitem{(.*?)}|\\newblock", " ", original_reference) text = re.sub(r"\n", " ", text) text = re.sub(r" +", " ", text.strip()) # text ...
6a38dd700238286a6667fda58727cd60eb16e0fa
674,231
def ebc_to_srm(ebc): """ Convert EBC to SRM Color :param float ebc: EBC Color :return: SRM Color :rtype: float """ return ebc / 1.97
f5a2411f2ee89d979950fe7c7fdcdf5531a4203d
674,232
def segementation_grid(img, windows): """ segment the image based on the grids :param img: object, image :param windows: list, grids coordinates :return: img buffer, the list to save the fragment images """ img_buffer = [] for windows_line in windows: img_line = [] for wi...
1933f85abcfd89ad47e010f98c5f5add45cb5f32
674,233
def _unique_id_to_host_id(unique_id): """Return the chip id unique to the daplink host procesor Unique ID has the following fomat Board ID - 4 bytes Version - 4 bytes Host ID - Everything else """ return unique_id[8:8 + 32]
d59dcbcdfe5a6e14dced44736efab38d9e0419ef
674,234
def finger_hybrid_initial_state(): """Returns the initial hybrid state and mode (x0,m0) of a finger. state is x=(theta1,theta2,theta3,thetamotor,g) and m=(c1,c2,c3,l1,l2,l3) where c1,c2,c3 indicate contact states 0 or 1, and l1,l2,l3 indicate upper joint limit hit +1, lower joint limit hit -1, or neithe...
10cc25ad9b0b7bc21c282bf234b51d067f4cf466
674,235
import ntpath def pathLeaf(path): """ Returns the basename of the file/directory path in an _extremely_ robust way. For example, pathLeaf('/hame/saheel/git_repos/szz/abc.c/') will return 'abc.c'. Args ---- path: string Path to some file or directory in the system Returns...
f0d28f160dd9e32e6d2e99106bff870ca5995f52
674,236
import struct def unpacker(fmt): """create a struct unpacker for the specified format""" try: # 2.5+ return struct.Struct(fmt).unpack except AttributeError: # 2.4 return lambda buf: struct.unpack(fmt, buf)
f61bb5031344a3869c753d8309139a4c1228f5e2
674,237
def IsDataByte(num: int) -> bool: """Is a MIDI Data Byte.""" return num >= 0 and num <= 127
63ddeab52c52c77c3ddcc98b10ba1b7e1a006816
674,238
def gdp_energy_demand(year, growth_rate, base_demand): """computes demand based on gdpgrowth and BaseYearDemand. it uses follwing recursion Demand[y] = DemandGrowthRate[y] * Demand[y-1] this actually resolves to Demand[y] = product(DemandGrowthRate[all x such x<=y]) * BaseYearDemand """ bd ...
87bdab4e5dd8ba2b009f1c35d7a000355233fb29
674,239
import copy def convertUnits(ww_params, pixel_size): """ Convert to the units currently used by the analysis pipeline. This also adds additional zeros as needed to match the length expected by the analysis pipeline. """ ww_params = copy.copy(ww_params) ww_params[0] = ww_params[0] * pi...
cb32938ccacee6b76dbacbb1c4bd76e4f13b1cef
674,241
def skills(page): """ :param bs4.BeautifulSoup page: resume page :return: str """ page = page.find("div", {"data-qa": "resume-block-skills-content"}) page_skills = "" if page is not None: skills_child = page.findChild() page_skills = page.getText() if skills_child is None el...
5cffddbb23104a56a7f2dd975d49ccb66ce967b7
674,242
def giveChange(value, coins): """Determines whether or not it is possible to create the target value using values of coins in the list. Values in the list cannot be negative. The function returns a tuple of exactly two items. The first is a count of the number of coins needed and false if it is not. The...
aee614ceab16de972ced6147c3e53627132b0e0e
674,243
import random def generate_smallest_secret(poly_degree, crc_length, min_size=0, echo=False): """ Helper function to generate smallest secret which is: - divisible by 8, so that it can be encoded to bytes - secret length + crc_length is divisible by poly_degree + 1 to be able to split s...
5bfba7e9a13150175e681eda91799e2c08e144a9
674,244
def populate_mock(theta, model): """Populates halo catalog with galaxies given SMHM parameters and model.""" mhalo_characteristic, mstellar_characteristic, mlow_slope, mhigh_slope,\ mstellar_scatter = theta model.param_dict['smhm_m1_0'] = mhalo_characteristic model.param_dict['smhm_m0_0'] = mste...
174bbf18e7858e3c9971427a609b19ea1c3de698
674,245
def force_key(d, k): """Return a key from a dict if existing and not None, else an empty string """ return d[k] if d.has_key(k) and d[k] is not None else ""
1b7b5d74a56347685412cfe4d334f3dd787c268b
674,246
def foundSolution(solver_result): """ Check if a solution was found. """ return "Valid" not in solver_result and "unsat" not in solver_result
61e82ecd4f346b9536553bef114376f67f5d71f8
674,247
def to_text(value): """ :type value: str | None :rtype: str | None """ if value is None: return None if isinstance(value, bytes): return value.decode('utf-8') return u'%s' % value
a58177afee629d98148f06d51ed8f723dac4d55f
674,248
def get_create_table_command(): """ helper to get create table command """ return '''CREATE TABLE ENCODES (ID TEXT PRIMARY KEY NOT NULL, SOURCE TEXT NOT NULL, WIDTH INT NOT NULL, HEIGHT INT NOT NULL, CODEC ...
560272b3991bdcfbfef880216e6b7d40e2288799
674,249
import torch def torch_get_current_device_name(): """ Checks available GPUs to PyTorch. :return: """ if torch.cuda.is_available() and torch.cuda.device_count() > 0: return torch.cuda.get_device_name(torch.cuda.current_device())
215f43189c54a891411cc0ea734112168a8ddf36
674,250
def filter_bits(site, bits): """ Seperate top and bottom bits. Some IOSTANDARD bits are tile wide, but really only apply to a half. It is hard to write a fuzzer for this, but it is easy to filter by site, and all bits appear to have a nice hard halve seperatation in the bitidx. """ if site == '...
fde5d960b69e4c617ee8a4448ab74b9df8524d66
674,251
import torch def one_hotify(vec, number_of_classes, dimension): """ Turn a tensor of integers into a matrix of one-hot vectors. :param vec: The vector to be converted. :param number_of_classes: How many possible classes the one hot vectors encode. :param dimension: Which dimension stores the ...
583ce1ed52d99b4c428d2f8b5ab03b2987d13ee7
674,252
def convert_filename (pattern, name): """ Convert filename according to the pattern specified >>> convert_filename ("*","toto") == "toto" True >>> convert_filename ("?a*","toto") == "tato" True >>> convert_filename ("?a?","toto") == "tat" True >>> convert_filename ("i??","toto") == "iot" True >...
9ab191a9dde6c415b6dfea0a06de129429c44787
674,253
def _get_methods(module): """ Extract relevant methods from `module`. Parameters ---------- module : str The name of the module from which the methods should be extracted. Returns ------- methods : tuple The names of the relevant methods from `module`. Notes --...
3a157ac0521817725d215da237c44628f7ce17f4
674,254
import os def is_empty(path): """True if a file contains more than a single byte (has size >1). We ignore a single byte because shell and I/O operations sometimes create a file containing a space or EOL character, and that's meaningless. """ return os.stat(path).st_size < 2
3875fe09ba5a0b89d5bd06971de4457f3f22bc9d
674,255
def get_fuels(collection, country): """ Accumulate capacities for each fuel type for a given country """ result = collection.aggregate([ { # Search country '$search': { 'index': 'default', 'text': { 'query': country, 'path': 'coun...
fab8b976663ead606a8c1200c1309de88e2b5878
674,256
def extract_category(report, key): """ Create a dict from a classification report for a given category. Args: report: The report key: The key to a category on the report """ result = report.get(key) result['category'] = key return result
14a3e54a50065bd49a1d7d9941f7cb8918e48ffe
674,257
def get_int_from_little_endian_bytearray(array, offset): """ Get an int from a byte array, using little-endian representation,\ starting at the given offset :param array: The byte array to get the int from :type array: bytearray :param offset: The offset at which to start looking :type offs...
1c87a6f36642b92ac084d0a269003ed4250312a5
674,258
def _build_radv_config(config, interface_map): """ Generate the "radv" section of the BIRD daemon configuration. :type config: akanda.router.models.Configuration :param config: :type interface_map: dict :param interface_map: :rtype: """ retval = [ 'protocol radv {', ] ...
b2d3900cf53c638f448687d76872411b522b7c22
674,259
import os def full(file_name): """Full Path. Converts ~'s, .'s, and ..'s to their full paths (~ to /home/username) Args: file_name (str): Path to convert Returns: str: Converted path """ return os.path.expandvars(os.path.expanduser(file_name))
5c1b345408f38c3865904b5c5448644279d03ca0
674,260
def array_search(A: list, N: int, x: int): """ Осуществляет поиск числа x в массиве A от 0 до N-1 индекса включительно. Возвращает индекс элемента x в массиве A. Или -1, если такого нет. Если в массиве несколько одинаковых элементов, равных x, то вернуть индекс первого по счёту. :param A: ...
935d4cf4e1321ac1af925fae2c5208d041c4f6ae
674,261
def strfboard(board, render_characters='-+ox', end='\n'): """ Format a board as a string Parameters ---- board : np.array render_characters : str end : str Returns ---- s : str """ s = '' for x in range(board.shape[0]): for y in range(board.shape[1])...
6e6add6c93188051b96e2efc2a0bb06f3730fffb
674,262
def _calculate_protein_area(gene_df, usrdata, area_col, normalization, EXPTechRepNo=1): """Area column is psm_SequenceArea""" matches = usrdata[(usrdata['psm_GeneID'] == gene_df['e2g_GeneID']) & (usrdata['psm_AUC_UseFLAG']==1)] [ [area_col, 'psm_GeneC...
98a27fd0a3aac925410d54dd42754430bd9db469
674,263
def simple_dist(x1: float, x2: float) -> float: """Get distance between two samples for dtw distance. Parameters ---------- x1: first value x2: second value Returns ------- float: distance between x1 and x2 """ return abs(x1 - x2)
dea3188f7589bda30092ecec8b19ba02a47d5e58
674,264
def qvarToFloat(qv): """converts a Qvariant to a python float.""" return float(qv)
0f1f4a978f94f71d7c030b2d78f009fdba7d3616
674,265
import requests import json def get_metadata(project): """ :param project: project object :returns: metadata """ data1 = { 'token': project.token, 'content': 'metadata', 'format': 'json', 'returnFormat': 'json' } request1 = requests.post(project.url, data=...
689e882c41305e1d897f590691c997675ec9bd7f
674,266
def fitness_bc(agent, environment, raw_fitness, path): """ Returns as a tuple the raw fitness and raw observation of an agent evaluation. """ if len(path) > 0: return raw_fitness, path return raw_fitness, [0]
c08df3a6c27b5c5c2550e3c346a50779eaba67ef
674,268
def accuracy(y_pred, y_truth): """ Accuracy: #right / #all Parameters ------------- y_pred : numpy array, (m, 1) the predicted labels y_truth : numpy array, (m, 1) the true labels Returns -------- accuracy : double larger is better """ re...
f2971aa477f467020220f75a7a36e541ef4571c2
674,269
def train_test_split(t, df): """ Splits time series dataset into train, validation and test set with a 60-20-20 split. Targeted to be used in an apply function to a Series object. :param t: current timestep (int) :param df: pandas Dataframe containing the data :returns: subset categorization as ...
8d79cbf86586893519c85939cfa0c2cdb132b250
674,270
import traceback def cut_traceback(tb, func_name): """ Cut off a traceback at the function with the given name. The func_name's frame is excluded. Args: tb: traceback object, as returned by sys.exc_info()[2] func_name: function name Returns: Reduced traceback. """ ...
c7e5558eebf75b24bda1ddb49563220f8c497bce
674,271
def crop_2d_using_xy_boundaries(mask, boundaries): """ :mask: any 2D dataset :boundaries: dict{xmin,xmax,ymin,ymax} :return: cropped mask """ b = boundaries return mask[b['ymin']:b['ymax'], b['xmin']:b['xmax']]
1212a1a2a0441cc0542c5271bf5aedc65c0fbc7d
674,273
def get_unit(a): """Extract the time unit from array's dtype""" typestr = a.dtype.str i = typestr.find('[') if i == -1: raise TypeError("Expected a datetime64 array, not %s", a.dtype) return typestr[i + 1: -1]
22f132af5ab751afdb75c60689086874fa3dfd99
674,274
def find_dimension_contexts(instance,context,dimensions): """Returns a list of contexts containing the given dimension values and having the same period as the given context.""" contexts = [] for dimcontext in instance.contexts: if dimcontext.period_aspect_value == context.period_aspect_value and di...
fee072ebccdeb68a3f7bf13158c5c39ce8aa8ca9
674,275
def atoms_to_xyz_file(atoms, filename, title_line='', append=False): """ Print a standard .xyz file from a list of atoms Arguments: atoms (list(autode.atoms.Atom)): List of autode atoms to print filename (str): Name of the file (with .xyz extension) Keyword Arguments: title_lin...
de1fab407935c7b1b95471ee61cebbbb59f25419
674,276
from typing import List from typing import Dict import torch def prepare_batch(batch: List) -> Dict[str, torch.Tensor]: """ Take a list of samples from a Dataset and collate them into a batch. Returns: A dictionary of tensors """ input_ids = torch.stack([example['input_ids'] for example in...
eece79f3eb1c99c04876679247796c2286f8dd6e
674,277
def variants(*strings): """Creates three variants of each string: - lowercase (e.g. `husky`) - title version (e.g. `Husky`) - uppercase (e.g. `HUSKY`) :return: A list of all variants of all given strings. :rtype: list """ result = [] for string in strings: lowercase = strin...
a4c1af7ecdba9642c95cef8ac8a5516d703c1ad7
674,278
def get_start_end(title, print_char="-", size=150, nl_str=True, nl_end=True): """ :return: start: ------------------------------- <title> ------------------------------- end: ----------------------------------------------------------------------- """ title_len = len(title) print_ch...
abe8f063153069b32cd6503fac287c421d6f0c53
674,279
import sys def user_input_handler() -> list: """ Function to handle input from user and other threads.""" input_list = [line for line in sys.argv[1:]] return input_list
25bcfdbaf6783f5eb45d36a708cad5f8ed733b66
674,280
import os def check_filename(filename): """ Creates directory if the directory to save the file in does not exists. Args: filename: the filepath. """ if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) return filena...
8ab3ad1418b818bc18eb646121479d7cd63a4271
674,281
def has_text(text): """ Return False if the text is empty or has only spaces. A true value is returned otherwise. """ # This is faster than "not text.rstrip()" because no new string is # built. return text and not text.isspace()
c0b4ef15b2979f21aff835fbb6a2168cc3d72521
674,282
import torch def jacobian(f, x): """Computes the Jacobian of f w.r.t x. This is according to the reverse mode autodiff rule, sum_i v^b_i dy^b_i / dx^b_j = sum_i x^b_j R_ji v^b_i, where: - b is the batch index from 0 to B - 1 - i, j are the vector indices from 0 to N-1 - v^b_i is a "test...
913053f45b25d6f88d95cf26a757e7b4ba586089
674,283
from typing import List def mimes_to_codec(mimes: List[str]) -> str: """Utility function for turning mutagen's mime types into a single codec string.""" if any(["codecs=opus" in m for m in mimes]): return "opus" else: return mimes[0].replace("audio/", "")
7f902dface33111bca108304f902223fea61a095
674,284
def _gigabytes_to_ms(gb, sample_rate_hz, bytes_per_sample): """ Approximately convert GB to ms of WAV data. """ total_bytes = gb * 1E9 total_samples = total_bytes / bytes_per_sample total_seconds = total_samples / sample_rate_hz total_ms = total_seconds * 1E3 return total_ms
c05069f4c4720e78ba4c5b68cdba48bf185a5f83
674,285
import re def dbs(str): """ """ p = re.compile(r"[\\/[,{}:;\"\'\[\]()=<>!?]") str = p.sub('', str) return str
4d464fc2b9d8d113d19e082a351c8eb33fa7bd1f
674,286
def exclude_cortical_stimulation(df): """ Exclude all cortical electrical stimulation publication approaches (as part of TS filter) """ # df_excl = df.copy() # mask_string = df_excl[SEEG_ES].str.contains('ES', case=False, na=False) # df_excl.loc[mask_string, SEEG_ES] = np.nan # subset = [POS...
ecae2c0fd06e5946ac502173851b1fcb4f3db845
674,287
import re def split_source_id(source_id): """Retrieve the source_name and version information from a source_id. Not complex logic, but easier to have in one location. Standard form: {source_name}_v{search_version}.{submission_version} Arguments: source_id (str): The source_id to split. If this is...
731d3c4733471cd3293de05d3b3f97a62916b245
674,288
def pruneListByIndices(lst, indices): """Prunes a `lst` to only keep elements at the given `indices`.""" return [l for i, l in enumerate(lst) if i in indices]
9cc59c1f05775557a973f7ac4f0fccd3004af235
674,289
def get_single_pos(chunk_containing_pos): """Return only first pos and it's content.""" pos_char_end_idx = chunk_containing_pos.find(" ") pos = chunk_containing_pos[:pos_char_end_idx] pos_content = chunk_containing_pos[(pos_char_end_idx + 1) :] return pos, pos_content
591de89b5502754660003a49858d427946376c20
674,290
def get_machine_type(cpu_cores, memory, accelerator_type): """Returns the GCP AI Platform machine type.""" if accelerator_type.value == "TPU_V2" or accelerator_type.value == "TPU_V3": return "cloud_tpu" machine_type_map = { (4, 15): "n1-standard-4", (8, 30): "n1-standard-8", ...
426116d4b8742a110e2716415ceb7ae171068114
674,291
def __read_lst(dat): """ lst形式のデータ(文字列)の内容を読み込む """ dat_list = dat.split('\t') index = int(dat_list[0]) header_size = int(dat_list[1]) assert header_size == 2, 'header_sizeは2を想定:'+str(header_size) label_width = int(dat_list[2]) assert label_width == 5, 'label_widthは5を想定: '+str(labe...
989d1eb27dd7c7a62bd399273b3d1d5f59e5d0e0
674,292
import os def _file_exists(fullpath) -> bool: """Test if the requested config file exists. Returns: True of the file exists, otherwise False. """ exists = os.path.exists(fullpath) if not exists: raise UserWarning('The config file (%s) could not be found.' % (fullpath)) return...
92a2a919cd08c733b4d78674173feae28db6a71f
674,293
import torch def unk_init(dim): """ Initialize out of vocabulary words as uniform distribution in range 0 to 1. :param dim: word embedding dimension :return: randomly initialized vector """ return torch.rand(1, dim)
9e887107a96ad9a22329a4f8b57db5f324e3da82
674,294
def convert_txt_to_inds(txt, char2ind, eos=False, sos=False): """ Args: txt: Array of chars to convert to inds. char2ind: Lookup dict from chars to inds. Returns: The converted chars, i.e. array of ints. """ txt_to_inds = [char2ind[ch] for ch in txt] if eos: txt_to_ind...
48e3364e3af18d7a2a3b1820fd9c474920652269
674,296
import math def _calculate_brightness(color): """ Returns a value between 0 and 255 corresponding to the brightness of the specified color. From:http://tech.chitgoks.com/2010/07/27/check-if-color-is-dark-or-light-using-java/ """ return int(math.sqrt(color.red() ** 2 * .241 + \ ...
6d60256d9f785388877adbc82563c87f5b23a578
674,297
import numpy def scan_complete_history(complete_history, x): """ Search for a previously evaluated point within 1.E-12 of <x>, returns previous value and associated flag.""" for i, point in enumerate(complete_history.good_points): d = numpy.linalg.norm(x-point, ord=numpy.inf) if d < 1.E-1...
1380580a05a82e051775aec0a98251ad2fe13055
674,298
from typing import Tuple from typing import Any from typing import Optional from typing import Coroutine async def wait_for_poll( poll_result: Tuple[Any, Optional[Coroutine[Any, Any, Any]]] ) -> Tuple[Any, Any]: """See azure_rest_api_poll""" first_result, continuation = poll_result if continuation is ...
c2fc95d4f56652e57df0f16d48d6d3477bb02b6d
674,299
def reshape_array(data_header, array): """Extract the appropriate array shape from the header. Can handle taking a data header and either bytes containing data or a StructureData instance, which will have binary data as well as some additional information. Parameters ---------- array : :class:...
3844f7c92c745bc68f69514b7bf030ed2b41ab4b
674,300
def resettv(samp=1): """ Setting the parameters for running the windowed experiment :param samp: The samp value :return: the parameters """ parameters = {"fonollosa": {"ini_value": int(5000/5), "start_value": int(6400/5), "step": in...
32cbf9b4adc2e8ead3be7c3372563d750c74aca2
674,302
def pairwise_prefs(A,P,params,distance_bound=1): """ Return a dict pref that gives for each pair (i,j) of alternatives from A the sum, over voters that prefer i to j, of how many positions higher i is than j in the voter's ballot (but not more than "distance_bound" per ballot). If params["missing_pr...
e28174539029397565434f4fb1ba667b5351a178
674,303
def common_parent(a, b): """ Find the common parent tile of both a and b. The common parent is the tile at the highest zoom which both a and b can be transformed into by lowering their zoom levels. """ if a.zoom < b.zoom: b = b.zoomTo(a.zoom).container() elif a.zoom > b.zoom: ...
d3c8fdce19f19e431d3b4e894314e56dc9a45396
674,304
import calendar import random def random_day(month): """Return a random int within the range of the month provided.""" dayRange = calendar.monthrange(2020, month)[1] return random.randint(1, dayRange)
402f9b6900a06fe11a35e8cf118efd7ebc0de855
674,305
import sys def read_ids(idf): """ Read the ID file :param idf: an id file that has HOW\tGene :return: a hash of gene->how called """ ids={} with open(idf, 'r') as f: for l in f: p = l.strip().split("\t") if p[1] in ids: sys.stderr.write('Err...
8815d0686cf80f2901bd992d3cc68c9dfb49f7f9
674,306
def generate_annotation_vector(agreement_dictionary, k): """ Generates the annotation vector for specific response index Args: agreement_dictionary: the annotations used to combine the agreement vector k: the index """ annotation_vector = [] for sentence in sorted(agreement_dicti...
4f8f7cdc4787f27e61d40585c42c68d9a4844184
674,307
async def replace_field_from_dict(message, embed, field_dict, index): """ Replaces an embed field of the embed of a message from a dictionary with a much more tight function """ embed.set_field_at( index, name=field_dict.get("name", ""), value=field_dict.get("value", ""), ...
1e0bf3a9e0e4231c02186107e33626e0a5756d08
674,308
def make_search_conditions_on_display(mode :str): """ 表示に関する検索条件を作成する。 Args: mode (str) : 検索タイプのキーワード Returns: r_val (str) : 検索条件文字列(SQLの一部) """ if mode in ('1','purchased',): # 購入済みも表示する(非表示を取得しない) r_val = "(product_not_displayed is NULL) " elif mode in ('2',...
a0b57764b968c398ce5679bb6c06c2b7b4b839d2
674,309
def get_gesture_set(file_list, gesture=''): """Get set of unique gestures in list of `files` Args: file_list (list<str>) gesture (string) Returns: gestures (set<str>) """ if gesture is not '': gestures = set([gesture]) else: # Get set of gestures ...
d6d890e7a8909fb432969be4d40f3243a551dfac
674,310
import subprocess import logging def _RunCommand(command, log_error=True): """Run a command and logs stdout/stderr if needed. Args: command: Command to run. log_error: Whether to log the stderr. Returns: True if the process exits with 0. """ process = subprocess.Popen(command, ...
e67e734073b425bbbe044ed38215c89b0ab9f8a8
674,312