content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def manual_switch_gradient(loss_delta_noreduce, model, eps=1e-5, loss_coeff=1.0): """Fill in the gradient of switch probas manually Assuming that the batch size is enough to estimate mean loss with p on and off. """ mask = model.model.last_mask input_dim = model.n_features + mod...
4a0d3dc9572834acf39837abeb89b581bac5e43b
656,905
def tuple_slice(tup, start, end): """get sliced tuple from start and end.""" return tup[start:end]
edea6d09bb017b8aa588855186e3543db35477e2
656,906
def find_plus(word): """ returns 1 if the word containe '+' Input=word Output=flag """ if '+' in word: return 1 return 0
7059f4d4be5de07d5e704bd68c1424be7cc5b30a
656,907
def make_lib_dll(env,base): """Return the static or link lib and shared-lib name. For a given base we return base.lib and base.dll on windows. base.so and base.so on non-windows. Users link against the link lib.""" dll = env.shared_lib_name(base) static_lib = env.static_lib_name(base) ...
39c7ba9bbef3116cdbdec9514b0f13cbf43edd5a
656,908
def process_followed_path(list_of_nodes, edges_dictionary): """ Process the nodes of followed path and retrieve a dictionary containing parameters such as covered distance, travelling time, intermediate nodes, geographical points, and edges. :param list_of_nodes: The list of nodes which consist the opt...
2dcfb8538e2230611c43db8feebbd5060fc112f8
656,909
def defaultModel(t, alpha=3.0, beta=None): """ See ebisu's defaultModel function documentation. Note: This app's init_model function provides default alpha=2 instead of alpha=3.0, but it's a small difference, and this function goes with default alpha=3.0. """ if beta is None: beta =...
91609d34a239fefd2c17967da2ef145be25cf237
656,910
def findLastK(head, k): """ 方法功能:找出链表倒数第 k 个结点 输入参数:head: 链表头结点;k: 需要寻找的位置 返回值:倒数第 k 个结点 """ if k < 1 or head is None or head.next is None: return None slow = fast = head for i in range(k): fast = fast.next if fast is None: return None while fast ...
ee2f71523785023e2033af534dbe2f2cc4a669c1
656,912
def reorder_coefficients(occupations, coefficients): """ Reorder the coefficients according to occupations. Occupated orbitals will be grouped at the beginning non occupied will be attached at the end :param occupations: list on integers (0 or 1) or list of Boolean :param coefficients: dictionary ...
f998f1a518c61e07a2d38124416aa43b224ff323
656,913
import socket def is_port_open(ip, port): """ 测试端口是否可用 """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((ip, int(port))) s.shutdown(socket.SHUT_RDWR) return True except: return False finally: s.close()
223ab3fd23d3bad479d18652382e0990d2432bb0
656,914
import io def _load_vectors(filename, head_n=None, open_encoding='utf-8'): """ 装载前N个词向量 :param filename: :param head_n: head n word vectors will be loaded :return: dict, {word: str => vector: float list} """ line_count = 0 data = {} try: fin = io.open(filename, 'r', encodin...
5744ac0d5922c6755f93e6896e47f1b240bac833
656,915
def profit(initial_capital, multiplier): """Calculate the profit based on multiplier factor. :param initial_capital: Initial amount of capital :type initial_capital: float :param multiplier: Multiplying factor :type multiplier: float :return: Profit :rtype: float """ return initi...
c47305991f9b66963248d329eef5bd1164dc28c0
656,916
def _cx_oracle_req(): """ Fallback function stub """ return 'Need "cx_Oracle" and Oracle Client installed for this function exist'
ee5afd8b2c0917798624e99039eeb2b66cb24ea9
656,918
def _roman(n): """ :param n: the input integer :return the roman numeral :raise ValueError: if the input integer is not a positive integer less than five """ if n not in range(1, 5): raise ValueError("The roman numeral converter is not supported" " for th...
ec16ef964a5fcd41b73723b2309d2099c7dcef76
656,919
def process_rsa_data(rsa_data): """Process the .rsa output file: residue level SASA data.""" naccess_rel_dict = {} for line in rsa_data: if line.startswith("RES"): res_name = line[4:7] chain_id = line[8] resseq = int(line[9:13]) icode = line[13] ...
c8dae328d225e04156fc5074a98bc64f90595fc5
656,920
def row(**key_value_pairs): """Converts kwargs into a dict. Why use this? Because syntax highlighting for kwargs is nicer than for dicts.""" return key_value_pairs
622d5ed5b3dbe0fba2d5d8cf02cd762ff7960956
656,921
def _collect_time_shifts(synthetics, component): """ Collects time shifts by interating over data structure """ time_shifts = [] indices = [] for _i in range(len(synthetics)): stream = synthetics[_i].select(component=component) if len(stream)==0: time_shifts += [] ...
3b11487fec46de376001273b6cae637c4cb58f8f
656,922
import subprocess def predict(ci,trfile,tfile,pfile): """ Fits model and predicts labels for the test data. Writes predicted labels to 'pfile', as well as a trained model to 'model'. """ model="../models/"+trfile.split('/')[-1]+'.model' traincmd=["../liblinear/train", "-c", "0.001", "-q", trfile, ...
dc2875a3d75143117aefc0a6a3b8fa7df35ad1c7
656,923
def colors_objects() -> dict: """ Age of Empires II object colors for minimap. Credit for a list of objects goes to: https://github.com/happyleavesaoc/aoc-mgz. :rtype: dict """ food = (150, 200, 150) return { # FOOD 48: food, # BOAR 59: food, # BERRY BU...
09f543f5efa1d72c4f753a4c7e2aeb16ef5299eb
656,924
from typing import Optional def get_restore_path(restore_path: Optional[str] = None) -> Optional[str]: """Gets the path containing checkpoints from a previous calculation. Args: restore_path: path to checkpoints. Returns: The path or None if restore_path is falsy. """ if restore_path: ckpt_res...
31353578c602e2384c041ae96f01a15467302ec3
656,925
def get_manual_flags(level="all"): """Returns a list of content flags from the qualitative coding manual available at http://www2.psych.ubc.ca/~psuedfeld/MANUAL.pdf. Valid `level` inputs are: ["all", 1, 2, 3, 4, 5]. Other inputs will return an empty list.""" flags_for_1 = ["absolutely", "all",...
279075dff0036691ace32c7c8ffd56242448cedb
656,926
import shlex def GetHammerdArguments(): """Parses the hammerd.override and retrieves the arguments. The format of the file is: env FOO=1234 # comment of FOO env BAR="string value" # comment of BAR Returns: a dict containing the arguments of hammerd process. The type of the key and value are ...
78cf4fdf6f762b9c27ed4dd7d6d96ace488ea213
656,927
def units_converter(from_units="ip", **kwargs): """ Converts IP values to SI units Parameters ---------- from_units: str specify system to convert from **kwargs : [t, v] Returns ------- converted values in SI units """ results = list() if from_units == "ip": ...
5f20e2241bcd2d4a10d20c024a90d2952c60adc6
656,928
import math def bin_width_of_dec(num): """ >>> bin_width_of_dec(255) 8 >>> bin_width_of_dec(256) 9 """ return int(math.ceil(math.log(num + 1, 2)))
f71812bcc8e9206a113f152a8562fb4691ecfcbf
656,930
def in_range(x: int, minimum: int, maximum: int) -> bool: """ Return True if x is >= minimum and <= maximum. """ return (x >= minimum and x <= maximum)
4e3cb7808d0756e65da618dc141cf54ccd55447d
656,931
def auth_provider_fixture(): """Auth provider fixture :rtype: dict """ return { "dcos-users": { "authentication-type": "dcos-uid-password", "client-method": "dcos-usercredential-post-receive-authtoken", "config": { "start_flow_url": "/acs/api...
91752fbd236438264860561ff1dff646bdbf5e72
656,932
def extract_nodes_with_location_info(nodes): """ Will return an array identifying the indices of those nodes in nodes array another array identifying the node_id of those nodes another array indicating the line numbers all 3 return arrays should have same length indicating 1-to-1 matching. ...
b5781637418df80297b17882ca7a9c8d99634342
656,933
def pop(trace, instructions, reg): """Pop one item off the stack into reg""" instructions.append({"trace": trace, "op": "pop", "reg": reg}) return instructions
76b2a1e9370f228c8e438bf9778434d78a22c0f0
656,934
def modify_extra_section(yaml_content): """Modifies extra's section of the yaml_content. Args: yaml_content (str): Text representing yaml content Returns: [str]: yaml_content with extra's section modified """ yaml_content["extra"]["recipe-maintainers"] = ["prabhakk-mw", "diningPhil...
680717a8c5778598567a97f7f1bc82d38ae52499
656,935
def check_add_customer_params(request_data: dict) -> bool: """This method is used to check mandatory fields of model""" params = [ "c-email", "c-full-name", "c-address", "c-city", "c-postal-code", "c-phone-number", ] params_check = [item in request_data.ke...
00fc6edc54de289dd69ea3a0e1e979235f5adfd8
656,937
def fibonacci_recursive(n): """Recursive implementation of the fibonacci function time: (2^n) more precisely O((1+sqrt(5))/2)^n) space: O(n) note that one recursive is fully resolved before the other begins """ if n < 2: return n return fibonacci_recursive(n - 1) + fibon...
acccce965fd99c5ae2b430dcb4385d8c663db329
656,938
def model_cs_id_list(cursor, model_name): """Get a list of ``cs_id``'s for a model in a NEPC database. Parameters ---------- cursor : cursor.MySQLCursor A MySQLCursor object. See return value ``cursor`` of :func:`.connect`. model_name : str Name of a model in the NEPC MySQL database...
6999ae8bb719bf71050bcc4cfa3f174670cef283
656,939
def dist(a, b): """ >>> class O(): ... def __init__(self, start, stop): ... self.sstart, self.sstop = start, stop >>> a, b, c = O(12, 15), O(10, 11), O(16, 17) >>> dist(a, b) 1 >>> dist(a, c) 1 >>> dist(b, c) 5 """ d1 = abs(a.sstart - b.sstart) d2 = ab...
29d9781c2a0cac99dee1670570de90b1bff384b0
656,940
def reject_none(dict_obj: 'dict') -> 'dict': """Remove the item whose value is `None`""" return {k: v for k, v in dict_obj.items() if v is not None}
ec466e6d9d3f069d116ecfc90a314bf35ea99768
656,941
def max_length_diff(a1, a2): """Find the maximum length difference between two lists of strings. Find max(abs(length(x) − length(y))) where x from s1 and y from s2 input = two lists, each one has strings of letters a-z output = integer difference if any list is empty, return -1 ex: s1 = ["h...
34c476eb288469f6920bf00c7b562d3ac52b12dd
656,942
def mention_channel_by_id(channel_id): """ Mentions the channel by it's identifier. Parameters ---------- channel_id : `int` The channel's identifier. Returns ------- channel_mention : `str` """ return f'<#{channel_id}>'
ad827f59a1faf9a0a5c625460308085390208940
656,943
def to_sg(plato): """ Convert from plato to specific gravity """ return 1 + (plato / (258.6 - ((plato / 258.2) * 227.1)))
84892322d2289e93e48d73a724b1d4c2a5d6f185
656,944
import typing def _color_brew(n: int) -> typing.List[typing.Tuple[int, int, int]]: """Generate n colors with equally spaced hues. Parameters ---------- n The number of required colors. Returns ------- List of n tuples of form (R, G, B) being the components of each color. ...
e59a0b980cc93297d4e1738152a551a109e36ead
656,945
import os def get_long_description(): """Reads the long description from the README""" this_directory = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as file: return file.read()
530d47c7fc69c6241194760474337bca8e00f223
656,946
def parse_version(version_string): """ Parse the version from a string The format handled is "<major>.<minor>.<patch>-<date> <commit>" Args: version_string: the version string to parse Returns: A 3-tuple of numbers: (<major>, <minor>, <patch>) """ # Remove commit from version...
903780f7b2fc2abd3ec78bcadf96b39252ec49bb
656,947
def get_dimensionality(dims): """dims: string of dimensions identifier (ex: 'XYZT')""" return len([d for d in dims if d != "C"])
630a647a08243c25f3028627964246e3556c1e95
656,948
def _check_even(number): """检查数字是否为偶数 :param number 要检查的数字 :type number int :rtype bool :return True: 数字是偶数 False: 数字是奇数 """ result = False if number % 2 == 0: result = True return result
ddbba0f67b22b8d692ed6db4e487e86088de99ad
656,949
import random def make_aliases(): """Generate aliases. MAKES A DIFFERENT LIST EACH TIME. Puts alliterative aliases, where first and last names start with the same letter, up front where they are more likely to be used. Included here only for reference. The actual list is hard-coded. """ occ...
5d5de3ac73216af90299f2af5ce6a4ab5de4984e
656,950
import os def getOutDriver(outFileName): """ Set output driver type and creation options based on file extension. Returns driver name and list of creation options as dictionary. """ outControls = {} gdalFormat = 'ENVI' gdalCOOptions = [] calcStats = False e...
7d2e216e900bbb3862a3e9ad1ead634734e27e4a
656,951
import os import errno import stat def isfile_strict(path): """Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: st = os.stat(path) except OSError as err: if err.errno in (err...
906f0e31aa05a75f56ca6f237000e32fdb6dcab1
656,954
def get_cigar_by_color(cigar_code): """ ***NOT USED YET*** :param is_in_support: :return: """ if 250 <= cigar_code <= 256: return 0 if 148 <= cigar_code <= 158: return 1 if 70 <= cigar_code <= 78: return 2
5ef2830a497ffaecd22ae5cd49ecab9445bfca90
656,955
def _format_pval(p_value): """Helper function for formatting p-value.""" if p_value < 0.0001: return 'p < 0.0001' else: return 'p = {:5.4f}'.format(p_value)
3c78573f314bb1a0db55f7ae20540ac44ab359c1
656,956
def get_map_fn_dim(map_name): """ :param map_name: "seg" -> (F + 1) x 1 (bs as -1 or 0) "uv" -> (F + 1) x 2 (bg as -1) "uv_seg" -> (F + 1) x 3 (bg as -1) "ids" -> (F + 1) x 1 (bg as -1) "binary" -> (F + 1) x 15 (bs as -1) "par" -> (F + 1) x (10 + ...
20927b254fc6a80b2a610c96a30677129face708
656,958
def to_dict_plain(self): """ 只处理数据库中存在的列,不处理 backref 属性 """ return {c.name: getattr(self, c.name, None) for c in self.__table__.columns}
d6d78e420d08e429fc5c03ef62565e0b0d77b05f
656,959
def job_on_gpu(gpu_id, jobs): """ Find job on GPU gpu_id Parameters: ----------- gpu_id : ``int`` jobs : ``list of celery tasks`` """ for job in jobs: if job.gpu_id == gpu_id: return job
7c965c62ab97a4f61d449bf02a10e32273589cf7
656,960
def SLIME(rxnName, subsystem): """ if the rxnName contains the SLIME, classify the reaction into SLIME reaction """ for i,x in enumerate(rxnName): if 'SLIME' in x: subsystem[i] = 'SLIME reaction' print(subsystem[i]) else: subsystem[i] = subsystem[i] ...
8ed5aa012a8e26309108a03c9fa588e8c0479af9
656,961
def IfIn(words, text, opr="or"): """[It take a array of words and checks if the words are present in the text and return their AND or OR relation mentioned in the arguments.] Args: words ([list of strings]): [The words to check if present in text] text ([string]): [The simple string text] ...
d2d844b10a7d912f687105db616b2ef1e2c1fd09
656,962
def tr_tet_tet_coord_test(x, y, z): # dist2 = 2 """Test for coordinate in tretrahedron/truncated tetrahedron grid""" return ((x % 2 == 0 and y % 4 == ((x + z)) % 4) or (y % 2 == 0 and z % 4 == ((y + x)) % 4) or (z % 2 == 0 and x % 4 == ((z + y)) % 4))
a2390c131f709d3daf1106eb0fb10f4be8ccba35
656,963
import torch def covariance_diff_biased(X, Xk, SigmaHat, Mask, scale=1.0): """ Second-order loss function, as described in deep knockoffs manuscript :param X: input data :param Xk: generated knockoffs :param SigmaHat: target covariance matrix :param Mask: masking the diagonal of Cov(X,Xk) :par...
9c632769c09f05dceecccce71d91a95980917927
656,964
def default_2d_contour_plot(): """Return the default 2d contour plots """ twod_plots = [["mass_ratio", "chi_eff"], ["mass_1", "mass_2"], ["luminosity_distance", "chirp_mass_source"], ["mass_1_source", "mass_2_source"], ["theta_jn", "luminosity_distance"]...
ae8ef515aeaa691d7f482aa5884bde5fb42824b1
656,967
def subarraySum(self, nums, k): # ! 这样也是暴力求解,O(n^2) """ :type nums: List[int] :type k: int :rtype: int """ acc = 0 count = 0 for i in range(len(nums)): acc = nums[i] if acc == k: count += 1 for j in range(i + 1, len(nums)): acc += nums...
5872e905d8650f20a57c0d0af67de12e383ab6f2
656,968
def get_all_keys_in_dataset(raw_dataset): """Determines if there are keys shared by the whole dataset""" allKeys = [] for item in raw_dataset: for elem in list(item.keys()): if elem not in allKeys: allKeys.append(elem) return allKeys
138ba7ecae51c3bd893493bc6f21bcf141ce99ca
656,969
import torch import math def cal_GauProb(mu, sigma, x): """ Return the probability of "data" given MoG parameters "mu" and "sigma". Arguments: mu (BxGxC) - The means of the Gaussians. sigma (BxGxC) - The standard deviation of the Gaussians. x (BxC) - A batch of data ...
3237d9dbc89968804dfe66722ef62f86f5000c4d
656,970
def _lowercase_kind(value): """Ensure kind is lowercase with a default of "metric" """ if isinstance(value, dict): kind = value.get("kind", "metric").lower() # measure is a synonym for metric if kind == "measure": kind = "metric" value["kind"] = kind return value
8270b084cf8d14b62e8a9e20d5e4443756855e09
656,971
import torch def zdot(x1, x2): """Finds the complex-valued dot product of two complex-valued vectors. Args: x1 (Tensor): The first input vector. x2 (Tensor): The second input vector. Returns: The dot product of x1 and x2, defined as sum(conj(x1) * x2) """ return torch.su...
786ba11ff793bd8e5d05e5b53fcd74c969b81f5a
656,972
def CheckAnyListElementSameType(in_list:list, in_type:type): """ This function checks all elements of a list a equal to a specific type. :param in_list:list: a list of elements :param in_type:type: a specific type """ return any(isinstance(x, in_type) for x in in_list)
cabf1deffd6673082b47ec4d84307563eec1cd3c
656,973
def reswrite(self, fname="", cflag="", **kwargs): """Appends results data from the database to a results file. APDL Command: RESWRITE Parameters ---------- fname File name and directory path (248 characters maximum, including the characters needed for the directory path). A...
b209b77fcffd451927327d52214209049236f805
656,974
def cal_hamming_distance(hash_file1, hash_file2): """ 计算两篇文章的海明距离 :param hash_file1: :param hash_file2: :return: """ hamming_dis = 0 for i in range(len(hash_file1)): if hash_file1[i] != hash_file2[i]: hamming_dis += 1 # print("海明距离:", hamming_dis) return hammi...
73c8f63ef5cd077ad4465d5aecd41056c288ebd3
656,975
import os import torch def save_checkpoint(G, D, curr_epoch, G_loss, D_loss, val_loss, curr_step, args, filename ): """ Saves a checkpoint and updates the best loss and best weighted accuracy """ # is_best_loss = recon_loss < args['best_recon_loss'] if val_loss < args['best_recon_loss']: ...
d2bbf006fb6404770cc17ca3e3708615ee20441a
656,976
def cluster_length_to_bin(len_list, num): """compute bin bound """ avg_bin_len = len(len_list) // num sort_list = sorted(len_list) bin_bound = [] for i in range(num): if i == (num - 1): bin_bound.append((sort_list[i * avg_bin_len], 1e5)) else: bin_bound...
2340008c28c73e2faad82d3e533c588c219b2d19
656,977
import re def valid_ip(_ip): """[Determine if the host ip is valid] Arguments: ip {[string]} -- [host ip] Returns: [bool] -- [true or false] """ get_ip = re.compile( '^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\.(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\.' '(1\\...
87157008568550ea5058c2fda1162df12a172bfb
656,978
def validate_anyvalue(data_input, mode): """Just placeholder, anyvalue is always valid """ return True
eccfcbc8a9cf5ff69de2d974163393f4b5198ec3
656,979
def get_genome_parameters(g, topology_id: int): """Unravel the genome's parameters as an ordered list.""" if topology_id in [222, 333]: result = [g.nodes[2].delay, g.nodes[2].scale[0], g.nodes[2].bias_h[0]] elif topology_id in [22222]: result = [g.nodes[2].bias_h[0], g.nodes[2].weight] e...
6a5ba4127605b55b2bdb9a7c0c21f0aea428d448
656,980
import socket def check_remote_port_whether_open(remote_addr, remote_port): """ Check the remote port whether open :param remote_addr: Remote host's ip address :param remote_port: Remote host's tcp port :type remote_addr: string :type remote_port: int :return: A boolean value to decide the po...
943af8cf5d18561495eed08e1fff763089a422dd
656,981
def reformat_clip_range(clip_range): """Given the clip_range defined in excel, reformat it to go into ANUGA. This includes treating strings appropriately using very large hard coded numbers """ assert len(clip_range[0]) == 2 l = len(clip_range) output = list() for i in range(l...
2f442cf743ba6a38517c666e7f884124544f8fab
656,982
import os def _get_local_path(file_name, db_dir): """ Append local MIDAS_DB path to file(s) """ if isinstance(file_name, list): return [os.path.join(db_dir, f"{fn}") for fn in file_name] return os.path.join(db_dir, f"{file_name}")
b117efea1448fbb4133b5c7d1198fcd2bcfbc46a
656,984
def stringListaksi(string, delim=",", poistaTyhjat=True): """ Paloittelee merkkijonon erottimen (delim) kohdalta listaksi, poistaa listasta tyhjät merkkijonot (jos poistaTyhjat=True), siivoaa ylimääräiset välilyönnit ja muuttaa tekstin kirjainkoon pieneksi. Oletuserotin on pilkku. """ lista = [s...
7cec2336d45ab72485b7f5008b089d7eb0be5ef0
656,985
import logging import traceback import json def flask_method(function): """Decorator to handle errors.""" def generate_errcode(*args, **kwargs): try: return function(*args, **kwargs) except Exception as e: logging.error(str(e)) traceback.print_exc() ...
696b589f23ce9c8d5ce3cf1f595dfa7da5d09dd6
656,986
def are_blocking_checks(checks, ignore_warnings): """ Return True if checks are errors or unignored warnings. :arg dict checks: dictionary with a list of errors/warnings per library :arg bool ignore_warnings: ignores failed checks of type warning """ has_errors = any(p.endswith('Errors') for p ...
cc8d1e8ca9d0ee77b0384d3ea5863fff7d46350f
656,987
def get(isamAppliance, isamUser, object, admin_domain='Default'): """ Retrieve a specific object """ ret_obj = isamAppliance.invoke_post("Retrieve a specific object", "/isam/pdadmin/objectshowext/v1", { "admin_id": isamU...
09d9dc1d0911b7e95e157a358848537106aa82f6
656,988
import calendar import time def mktime(year, month=None, day=None): """ Make a timestamp from year, month, day. See `yearmonthday`. """ if month: if day: return calendar.timegm(time.strptime("%i-%s-%s" % (year, str(month).zfill(2), str(day).zfill(2)), "%Y-%m-%d")) return ca...
a76316d8d5ff8c680040b532ece82a274d927a2d
656,989
def _split_gradient(gradient: float, ratio: float) -> tuple[float, float]: """ (s+h)/2 = c s = 2c-h --- s-1 = r*(h-1) s-1 = rh-r s = rh-r+1 --- 2c-h = rh-r+1 h(r+1) = 2c+r-1 h = (2c+r-1)/(r+1) s = 2c-(2c+r-1)/(r+1) = (2cr+r-1)/(r+1) """ highlight = (2 * gradient +...
6216e5c13ed412b317ff3c07f5dff04bbd98a927
656,990
def parse_contrast(contrast, samples, check=True): """ Extract contrast batch and column, target and reference groups from a DE contrast design. Check for contrast validity if check = True. If "all" is in the contrast groups, it is always assumed to be the target (and expanded to mean all groups in...
8c9e31662f2ce13b1c069e767a567b9bb8e1b389
656,991
def get_blocklist_for_file(filename, manifestdict): """ <Purpose> Get the list of blocks needed to reconstruct a file <Arguments> filename: the file within the release we are asking about manifestdict: the manifest for the release <Exceptions> TypeError, IndexError, or KeyError if the manifes...
2c11d4b1c4ff2a1faa6487283d024eb59c34c3ed
656,992
import re import time def send_check_recv_data(serialport, pattern, timeout): """ receive serial data, and check it with pattern """ matcher = re.compile(pattern) tic = time.time() buff = serialport.read(128) while (time.time() - tic) < timeout: buff += serialport.read(128) if matc...
b83f9432081e87831ff005224702f7c73384720c
656,993
def update_vehicle_profile(spawn_profile, new_vehicle): """ Updates the vehicle profile of the spawning profile :param new_vehicle: new vehicle profile :param spawn_profile: spawning profile :type spawn_profile: SpawningProfile :type new_vehicle: VehicleProfile :return: updated spawning prof...
c019c99a66bd8c79927e3ccf63fef6fecc7ae5da
656,994
import sys import os def is_color_supported(): """ Returns ``True`` if the running system's terminal supports color, and ``False`` otherwise. Notes ----- Code from Djano: https://github.com/django/django/blob/\ master/django/core/management/color.py Returns ------- bool "...
e11a3ddea8dce8e641968ecc3a5ed9f8030e09eb
656,996
import operator def _cross_platform_stable_fs_iter(dir): """ Provides a stable ordering across platforms over a directory Path. This allows iteration across filesystems in a consistent way such that case sensitivity of the underlying system does not affect how the files are iterated. Args: ...
0cd1de96f754cf4e95e37602fa9666799498d87e
656,997
def _dir_filter(self): """ Using introspection, mimic dir() by adding up all of the __dicts__ for the current class and all base classes (type(self).__mro__ returns all of the classes that make it up) Basically filters by: __x__ OK __x bad _classname bad """ def chec...
9b826c6a233c292a3cf09145d575fd6a08af75ee
656,998
def pagination_numbers(current, all, radius=2, border=1): """ 1 ... 5 6 7 8 9 ... 20 """ maxlen = (border + radius) * 2 + 3 if all <= maxlen: return range(1, all+1) rawpages = list(set(range(1, all+1)) & \ (set(range(1, border+1)) | set(range(all-border+1, all+1)) \ | set(ran...
baf0ac0f525b8e64c6aca3ab69466b4d139ff738
656,999
def count(seq): """ Count the number of items in seq Like the builtin ``len`` but works on lazy sequencies. Not to be confused with ``itertools.count`` See also: len """ if hasattr(seq, '__len__'): return len(seq) return sum(1 for i in seq)
7094eb12434707606336056851c43340b474b96d
657,000
def range_corrector(g_range): """Swap start and end if start > end.""" chrom, start_end = g_range.split(":") start_end_split = start_end.split("-") start, end = int(start_end_split[0]), int(start_end_split[1]) if start < end: return g_range else: return f"{chrom}:{end}-{start}"
d361c1594d4cd7dfaef123c1dff6a368f6c73fac
657,001
import os def FindFileInDirectoryOrAncestors(filename, dirname, perm=os.R_OK | os.W_OK): """ Tries to find the file `filename` in the given directory `dirname` or its parents. When found it makes sure the permissions match the given `perm`. If no file is found, None is returned. If the file was found, but the...
2ab3a84adb76155262cff3277a52609d180656c6
657,002
import re def is_html_markup(text): """checks if text contains balanced html markup <token ...> body </token> """ pattern = re.compile("(?<=[<])[a-z]+") tokens = set(pattern.findall(text)) if not tokens: return False for token in tokens: num_start = len(re.findall(f"<{tok...
9baee9a6ee15eab3507d78d20045ffda11137944
657,003
import re def combine_tops(top_text, itp_texts): """ Search through parent topology top_text and replace #include lines with the relevant child topologies from the dictionary itp_texts """ for itp in itp_texts: # split on include string, then rejoin around itp file spl = re.spl...
2d21b6f4f015844f85f3b7563f538ceb9fc3b4a5
657,004
import os import re def parse_directory(directory, database): """ Determine which linelist and isotopologue this directory contains data for (assumes data was downloaded using our script) Parameters ---------- directory : String Local directory containing the line list file[s], broadening...
176413ba9417a321649e33e3628551852d3ce119
657,005
def residuals(constants, function, x, y): """ Function used to optimise the fit of the curve to the data. It calculates the distance between y-value from real data and y-value from the function (sigmoid/sine/etc). """ return y - function(constants, x)
55d4a1ba11fdc6854a4820831f3749f2a4e4931d
657,006
import os def load_package_tests(pkg_dir, loader, standard_tests, pattern): """Generic load_tests implementation for simple test packages. Most packages can implement load_tests using this function as follows: def load_tests(*args): return load_package_tests(os.path.dirname(__file__), *arg...
859c416b77f3344325b60a6e991071777fb87d8f
657,007
def archive_to_path(arch, date, archives_path, allowed_channel_dims): """ Converts archive entry (array of elements: [[station, channel, code, location, start_date, end_date],] to dictionary of this format: {"N": "data/20160610AZTRO/20160610000000.AZ.TRO.HHN.mseed",} Path example: /seismo/archive/IM/LNS...
a2c1dc309491403b1213d9ed0de8cced0b5b25bc
657,008
import pathlib import os def nas_data_out(nas_store=None, subdir="data_out", create=False): """Get base directory for data to store on NAS.""" pd = pathlib.Path( nas_store or os.environ.get("NAS_DATA") or "/media/nas/x21308") / subdir if create: pd.mkdir(parents=True, exist...
6c6fe6a2419070c744a6c733ec7c5fd4734203c8
657,009
import uuid import time def get_payload(eq_id, form_type, collection_exercise_id, ru_ref): """ Generates the payload required by EQ that will be later encoded. Note, this came from an integration test so there may be superfluous bits to it. """ return { "jti": str(uuid.uuid4()), "...
d91ed1e96df378516e0b1448f43c16f59133d7d0
657,010
def remove_negcon_empty_wells(df): """return dataframe of non-negative control wells""" df = ( df.query('Metadata_control_type!="negcon"') .dropna(subset=['Metadata_broad_sample']) .reset_index(drop=True) ) return df
5b4caa99fda231871f27e9e6797d2526a7e5a573
657,011
def rgb_maximize(r, g, b, scale=255): """ Calculates full luminosity RGB values from rgb chromacity coordinates :param r: Red ratio :param g: Green ratio :param b: Blue ratio :param scale: Output R,G,B values scale :return: RGB tuple """ ratio = scale / max(r, g, b) return tuple(int(...
d52f76ef47e0bf6ff547860411681649e6509eb1
657,012
import random def init_parameters(): """small random init for w, 0 for b""" return {'w': random.uniform(-1, 1) * 0.001, 'b': 0}
7103b5fbbf860d6b142a2306ca49b03fe539d52a
657,014
from operator import contains def project_contains_keywords(project, keywords): """Returns True if project contains at least one of the keywords.""" # Iterate over all sprites and backdrops, and the project itself. for child in project["children"] + [project]: # Perform a DFS on each script look...
00a2749d54a189d5ff4b6bbe2833e97f3ba89aba
657,015
import torch def dataset_to_list(loader, voc_size): """ Transform pyTorch tensors to lists. :param loader: :return: """ # Lists inputs_list = list() labels_list = list() time_labels_list = list() # Get training data for this fold for i, data in enumerate(loader): #...
7a42835f034a31e949d3078d28ab1dc5be1dac41
657,016