content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import requests from bs4 import BeautifulSoup def getResultsURLs(URL: str) -> list: """Finds appropriate result page link in the rounds section Args: URL (str): the URL of the division results page breaks (bool, optional): Return the link of the Returns: list: the URL of the requ...
91e0930730c39d243f5c30834051f85a44ca8197
663,315
def parse_nmap_host(line): """ :param line: like 'apnic|CN|ipv4|1.0.1.0|256|20110414|allocated' 1.0.1.0 mean ip begin , 256 mean sum total sum :return: return domain like 127.0.0.* or 127.0.0.1-128 """ l = line.split('|') ip, s = l[3], int(l[4]) a, b, c, d = (int(x)...
be14285a1792149058f22e3942a204b24c8bcccc
663,316
import re def populate_ec(entries): """ Extract EC codes per species across PALADIN entries """ ret_ec = dict() for entry in entries.values(): match = re.search("\\(EC ([0-9-]+\\.[0-9-]+\\.[0-9-]+\\.[0-9-]+)\\)", entry.protein) if match: entry_id = (entry.species_id, entry.spe...
f750cb8e8a9f888d6094ce70ca40afb82f09aaa9
663,317
import ast import re def is_literal_or_name(value: bytes) -> bool: """Return True if value is a literal or a name.""" try: ast.literal_eval(value.decode()) return True except (SyntaxError, ValueError): pass if value.strip() in [b"dict()", b"list()", b"set()"]: return T...
6a60ad64c6639ad8017820ba1d7ea5b256b477bc
663,318
def IS(attribute, val): """ Check if two values are equal """ return attribute == val
779aded6ba5d01191e9af08200e838a102b61c19
663,319
def _variable_lstm_shape(op): """Shape function for the VariableLSTM op.""" input_shape = op.inputs[0].get_shape().with_rank(4) state_shape = op.inputs[1].get_shape().with_rank(2) memory_shape = op.inputs[2].get_shape().with_rank(2) w_m_m_shape = op.inputs[3].get_shape().with_rank(3) batch_size ...
dfbcef1a18daee4886aa1358720433267798324d
663,320
import statistics def get_password_lengths(creds: list): """ Determine how many passwords have what lengths """ lengths = {} s = 0 for p in creds: if len(p) not in lengths.keys(): lengths[len(p)] = 1 else: lengths[len(p)] += 1 s += len(p) # The reason I didn't make this an orderdict or use Collec...
5b410a3c1e73fdb9893b5ac36d06105bd9a18351
663,321
def normalize_str(x): """ Given a value from an Excel cell, attempt to convert it to a string. Returns that normalized string if possible, or `None` otherwise. """ if not isinstance(x, str): return None return x.strip()
6657f28a4af22170963dbd0faa067a9b43fbab67
663,322
def lorenz(var, t, p, r, b): #{\frac {dx}{dt}}=-px+py #{\frac {dy}{dt}}=-xz+rx-y #{\frac {dz}{dt}}=xy-bz """ var = [x,y,z, x_dot,y_dot,z_dot] dx/dt = -px+py dy/dt = -xz+rx-y dz/dt = xy-bz """ x_dot = -p*var[0]+p*var[1] y_dot = -var[0]*var[2]+r*var[0]-var[1] z_dot = var...
d11d2e659cad6d0a639db81c63337aaeea56ad4d
663,323
def cast_op_support(X, bXs, tXs): # Type: (XLayer, List[XLayer], List[XLayer]) -> boolean """ Check whether we can execute the provided Cast operator on the dpuv2-ultra96 target """ dtype = X.attrs['dtype'] return dtype == 'float32'
cf3be405707fde71a919aa09033743f19489585f
663,324
import torch def dice_hard(pred, target): """This definition generalize to real valued pred and target vector. This should be differentiable. pred: tensor with first dimension as batch target: tensor with first dimension as batch """ smooth = 1. epsilon = 10e-8 # have to use contiguous ...
a4bbb1d90e75e21d2953430f0faf2e2e6a8f9d29
663,325
def t_statistic(mean1, mean2, n1, n2, svar1, svar2): """ Compute the t-statistic for the given estimates """ # Complete this funtion return 0.0
364dae4c0c475f837ed6daaac905c3cbda7af5c9
663,326
from typing import Union from typing import List from typing import Any from typing import cast def render_macro(template_name_or_list: 'Union[str, List[str]]', macro: str, **context: 'Any') -> str: """Evaluates and renders a **macro** from the template. Args: template_name_or_list: The name of the t...
3454ce572f308bf3d73a6ad4e7087ce753ff2ca1
663,327
import time import uuid def gen_random_resource_name(resource="", timestamp=True): """Generate random resource name using uuid and timestamp. Input fields are usually limited to 255 or 80 characters hence their provide enough space for quite long resource names, but it might be the case that maximum ...
b5897a72ddf551d2188c01925fe07103fffd3901
663,329
def solution2(values, expected): """ determines if exists two elements in values whose sum is exactly expected """ dic = {} for index, value in enumerate(values): diff = expected - value if diff not in dic: dic[value] = index continue return True ...
da8b996f4e693e97ee7724d01f8525e0a7344296
663,331
import random from datetime import datetime def generate_token() -> str: """ Function to generate token for the miscellaneous tasks. """ return ''.join( str(random.randint(0, 99)).zfill(2) + datetime.now().strftime('%H%S'))
a7bacd5d319eb534eeb82f3f74f7ee12db398644
663,332
def fixture_position(): """ Return a standard position argument for the colorbar. """ return "x0c/0c+w10c+h"
30bda82ac0cd96030f956ae5fe13e299f874a2b1
663,334
import json def parse_json(s, **kwargs): """Parse a string into a (nbformat, dict) tuple.""" d = json.loads(s, **kwargs) nbformat = d.get('nbformat',1) return nbformat, d
f77c0418bf935a560737278bb395aa2eb48fc21f
663,336
def login_testing_unauthorized(test_case, username, url, password=None, method='get', request_kwargs=None): """Test that a request is refused or redirected for login, then log in as the named user Defaults to making a 'get'. Set method to one of the other django.test.Client request method names (e.g., 'pos...
22ec5170bf54ff43d2463782be8ae64805b219e4
663,337
import re def get_unit_details(driver): """Get unit details such as price, unit number and size of the flat Args: driver (webdriver): Selenium webdriver Returns: dict : Returns dictionary containing unit details """ unit_details = [ a for a in driver.find_elements...
08625f53cd8b08f1cfda37c0ceb8fd6a703d0ba3
663,338
import warnings def validate_peril_factors(df_fsets, perils_implied): """Checks on implied perils deduced from the factor sets""" if not df_fsets.Peril_Factor.str.startswith( tuple(perils_implied) ).all(): warnings.warn( "Implied perils: Not every Peril_Factor starts with a Per...
3e9c727d3456ed4ed47cc76c5ef05a1a943bfcc2
663,339
import base64 def _bytes_to_url64(bytes_data): """Convert bytes to custom-url-base64 encoded string""" return base64.urlsafe_b64encode(bytes_data).decode().replace('=', '~')
cfb16657655f9ef0c6a429ecf9cf36dbed55d08b
663,340
def calculateRevenue(orders): """Calculate revenue from a number of orders""" totalRevenue = 0 for order in orders: totalRevenue += order.shippingPrice if order.status == 3 else 0 return totalRevenue
5f6e0c2cf963e485c400cc33549349ee91bd9ca0
663,342
def calc_cop_burner(Q_load_W, Q_design_W): """ This function calculates efficiency of gas burners supplying heat directly to the high temperature generators in double effect absorption chillers. :param Q_load_W: Load of time step :type Q_load_W: float :type Q_design_W: float :param Q_design_...
8872f417b11c23b2a0f547dcb8e6213059e79ee7
663,343
def find_missing_number(arr: list[int]) -> int: """ Complexity: Time: O(n) Space: O(1) Args: arr: array containing n-1 distinct numbers taken from the range [1,n] (n possible numbers) Returns: the single missing number in the range [1,n] missing fro...
105ebb8438b491fdc0f94bbffb714741b5c58291
663,344
def scrap_signature(consensus, fix=b'SIGNATURE'): """ Consume a signature field if there is one to consume. :param bytes consensus: input which may start with a signature. :returns: a tuple (updated-consensus, signature-or-None) """ if not consensus.startswith(b'-----BEGIN ' + fix ...
ca6ee8f64a7d41d5d09257a80c4e1827016a460c
663,346
def combine_graphs_single_pass(graphs_list): """ Combine N graphs into one. Do this by recognising common nodes between the two. Args: graphs_list: List of graphs to combine Returns: Combined graph """ combined_graph = graphs_list[0].__class__() for ...
0062457f7018beab74de3c4a606a7bd6b8383d58
663,347
import random def two_d6(): """Simulate the roll of two 6 sided die""" return random.randint(1, 6) + random.randint(1, 6)
9f77ae4a9681cf77eaf61a561d9bf594f6d6c6e5
663,348
import argparse def range_float(x): """Check the float is in [0, 1] range.""" x = float(x) if x <= 0.0 or x >= 1.0: raise argparse.ArgumentTypeError("%r not in range (0.0, 1.0)" % (x, )) return x
cb3e7aa0610c7245b2e127b8166206475c238fe3
663,349
def _is_sass_file(filename): """Checks whether the specified filename resolves to a file supported by Sass.""" if filename.endswith(".scss"): return True elif filename.endswith(".sass"): return True elif filename.endswith(".css"): return True return False
2e9ef936562482641457dcc71aa049400fdb7215
663,350
def translate_hand_kps(hand_kpss,kpss,wrist_ix): """ Translates the hand keypoints to a known wrist position. Parameters ---------- hand_kpss : list of numpy.ndarray The hand keypoints to correct. kpss : numpy.ndarray The general body keypoints. wrist_ix : int The in...
5a2a29f85dc788267270844979ed5358a712953b
663,351
def create_city_and_api_groups(data): """ Creates a list of groups based on city name and issue source used in scaling the final predictions. Args: data - a pandas dataframe that contains city and source columns Returns: a list of strings, each string contains the city na...
6cf990d681bc166c29c259ae7b18df2403654c5d
663,352
def provides_dep(package, other_package): """ Check if a package provides a dependency of another package. """ for dep in other_package.alldepends(): if package.providesName(dep.name): return True return False
6d30e7f1e1964d06844c71a879d5aa8364ba556f
663,353
import math def euclidean(vec1, vec2): """ 距离函数: 欧几里得距离. :param vec1: :type vec1: list[numbers.Real] :param vec2: :type vec2: list[numbers.Real] :return: """ d = 0.0 for i in range(len(vec1)): d += (vec1[i] - vec2[i]) ** 2 return math.sqrt(d)
ff407aea238adb32241457564109b2d9faf289c0
663,354
import numpy def nearlyequal(a, b, sig_digit=None): """ Measures the equality (for two floats), in unit of decimal significant figures. If no sigificant digit is specified, default is 7 digits. """ if sig_digit is None or sig_digit > 7: sig_digit = 7 if a == b: return True d...
a94ab12a50597682f31d7f00bebce418556f1819
663,355
def generate_question_id(example_id, assignment_id, question_per_example_index): """ Identifier assigned to a collected question question_per_example_index: 0-based (if a worker can write multiple questions for a single passage) """ if isinstance(question_per_example_index, int): question_pe...
294bde3f6016a4ab41af3a7ead8d147a6a363b18
663,356
def get_raise(data, key, expect_type=None): """Helper function to retrieve an element from a JSON data structure. The *key* must be a string and may contain periods to indicate nesting. Parts of the key may be a string or integer used for indexing on lists. If *expect_type* is not None and the retrieved...
a0a9a5bb419825720699d57476334637b51e34d8
663,357
def node_spec(): """Used in tests that have recursive $refs """ return { 'type': 'object', 'properties': { 'name': { 'type': 'string' }, 'child': { '$ref': '#/definitions/Node', }, }, 'required': ...
da0423019190ac565e09cee5558ed332b891c9f8
663,358
import torch def mask_long_scatter(mask, values, check_unset=True): """ Sets values in mask in dimension -1 with arbitrary batch dimensions If values contains -1, nothing is set Note: does not work for setting multiple values at once (like normal scatter) """ assert mask.size()[:-1] == values....
f44f06adda0cd3327d3851a5730cd9dcb5bb56dd
663,360
def melting_temp(seq): """Using Wallace Method suitable for short strands of base pairs (14-20) Tm = 2 °C(A + T) + 4 °C(G + C) = °C Tm Tm = (wA+xT)*2 + (yG+zC)*4 w """ Tm = sum([2*(str(seq).count('A')+ str(seq).count('T')) + 4*(str(seq).count('G')+ str(seq).count('C'))]) return "{}°C".format(T...
8a379e4438a96d8638a0db076960254c96aa1acd
663,361
def fsnative2glib(path): """Convert file system to native glib format""" assert isinstance(path, bytes) return path
5ed48332dee15df833acf24b1ca80a6436fde64c
663,362
def regions_intersect_ogr_p(region_a, region_b): """check if two regions intersect using ogr region_a_ogr_geom.Intersects(region_b_ogr_geom) Args: region_a (region): a region region_b (region): a region Returns: bool: True if `region_a` and `region_b` intersect else False. ...
97a886756e403104f708984705727c2095e866ac
663,363
def dim0(s): """Dimension of the slice list for dimension 0.""" return s[0].stop-s[0].start
730a3d0f8f14fcd12544bbf2333f6f51f83aac00
663,364
def get_aa_counts(table): """ A function that takes a Code and finds the counts of each AA. Returns a dictionary mapping AA to their respective counts. Parameters ---------- dict table: a python dict representing the codon table Returns ------- dict AA_count: a python dict mapping amin...
c0b719f1d2842b5934f19f9816a791f923ea5fa8
663,365
import re def _parse_resource_path(resource, to_fully_qualified, resource_type=None, subscription_id=None, resource_group_name=None, account_name=None): """Returns a properly formatted role...
f13c101b378b6db5646893468f2bdfe9e1bb8d59
663,366
def extract_sql_param_from_http_param(separator: str, http_param: str): """ Extracts sql params from an http param with given separator, returning tuple of db_query_label and query_name """ try: db_query_label, query_name = http_param.split(separator) except ValueError: raise Exc...
79a19490df6494b8ec75f1f1d2484b3e95906f70
663,367
import re def isfloat(value): """ Return whether or not given value is a float. This does not give the same answer as:: isinstance(num_value,float) Because isfloat('1') returns true. More strict typing requirements may want to use is_instance. If the value is a float, this function...
cfeccdf3b8f1e7687b984b15ff3130f58e1250d2
663,368
def check_partition_equality(op, representation): """Check to see if the operator has the required hash partitioning. @param op operator @param representation list of columns hash partitioned by, in the unnamed perspective @return true if the op has an equal hash partitioning to ...
ffc632f4cbaca6b00aa2ebc0566ea071b8997496
663,369
import hashlib def commit(key, msg): """ Puzzle friendly: no solving strategy is much better than trying random values of x""" m = hashlib.sha256() m.update(key) m.update(msg) return { "hash": m.hexdigest(), "key": key }
f21e8fbe6d87a2d9dc1057c32130582932e975e2
663,370
from pathlib import Path import os def parse_prepros(path, numproc=1): """Parse prepro results Parametres: ----------- path : str path to PREPRO calculation results numproc : int process number Returns: -------- nuclidpath : iterable of str path to nuclides fi...
c27adc00fc610b79be0245bfb25cd35259f52418
663,371
from typing import Dict import yaml def load_secrets_from_vault() -> Dict[str, str]: """Retrieves secrets information from Vault""" with open("secrets.yaml") as f: secrets_data = yaml.safe_load(f) return secrets_data
187672a5478db73caadab6287a3cf515b4fba85b
663,372
def group_signature_features(signature_features): """Further prepare signature feature dict for visualization""" grouped_features = {} for feature in signature_features: if feature["gn"] not in grouped_features: grouped_features[feature["gn"]] = [] grouped_features[feature["gn"]]...
2ae05dcf72d7bb08b08ead9aa598809b115dfd1b
663,373
def fib_memo(n, seen): """ Return the nth fibonacci number reasonably quickly. @param int n: index of fibonacci number @param dict[int, int] seen: already-seen results """ if n not in seen: seen[n] = (n if n < 2 else fib_memo(n - 2, seen) + fib_memo(n - 1, seen)) ...
b96f5f7a346eecc7689bfe95178d33f3b05975b8
663,374
def is_method_topic(topic): """ Topics for methods are of the following format: "$iothub/methods/POST/{method name}/?$rid={request id}" :param str topic: The topic string. """ if "$iothub/methods/POST" in topic: return True return False
6bf5463e97b14e554caad47af0dfe7999c143695
663,375
def create_instance_args_2_dict(args): """ change create_instance_args to dict :param args: create instance args :type args: CreateInstanceArgs :return: :rtype dict """ return { 'storageType': args.storage_type }
3c02761c963a2618afb7eefa80b59cd74167f423
663,376
from re import match def match_url(aim_url, role_str): """ :param aim_url: :param role_str: :return: """ rs = match(role_str, aim_url) return rs.span() if rs else None
7a5c74d89a643f41406e39caa0b8654486e024b4
663,377
def row2dict(row): """Convert SQL row to text""" return {c.name: str(getattr(row, c.name)) for c in row.__table__.columns}
c3eea2788c7b909e5b348a35c11a49ba826daede
663,378
import os def list2path(path_list): """ 根据list返回 path :param path_list: :return: """ return os.path.join(*path_list) if path_list else ''
4ff64e3e9631ab167ecb9123eb9ca821430bf70b
663,380
def set_mask_from_stack_img(ctx, nsigma=3, nsigma_connected=True): """Set the mask image from a stacked images Parameters ---------- ctx : :class:`wise.project.AnalysisContext` nsigma : int, optional Clip data below nsigma time the background level. nsigma_connected : bool, optional...
daf080c595ea2c3ab495496119aaee0cfea26d64
663,381
import glob def get_latest_benchmark_path(): """Returns the path to the latest benchmark run from `./.benchmarks/`""" benchmark_paths = glob.glob("./.benchmarks/*/*.json") dates = [''.join(_b.split("/")[-1].split('_')[2:4]) for _b in benchmark_paths] benchmarks = {date: value for date, v...
32db9a9f97900eeaaf3c4e7fb899bebe38bff29d
663,383
def player(): """ Returns a player's data, such as game stats. Parameters: `key`, `uuid` Example Response: ```json { 'success': True, 'player': { '_id': '************************', // Hypixel ID 'uuid': '********************************', // The Minecra...
820b9121f1bb916d5462123d9cbe7396d60971bb
663,384
def valid_boolean(config, section, option): """ Check an option to make sure that it's a valid boolean option """ try: if not config.has_option(section, option): return False config.getboolean(section, option) return True except ValueError: return False
8e5ed9f6af44f40b6fdd8d62d75368edc0b3af28
663,385
def algorithm_resolution(algorithm_conflict): """Create a resolution for a new algorithm configuration""" return algorithm_conflict.AlgorithmResolution(algorithm_conflict)
8e8598d71e92f09590fbb77303bb1398e598b702
663,386
from typing import Optional from typing import Union import click def parse_profit_input(expected_profit: str) -> Optional[Union[str, float]]: """Parses user input expected profit and ensures the input is either a float or the string 'YOLO'.""" if expected_profit == "YOLO": return expected_profit ...
e3e1a6eacc5b5c5a4b0f81449bfc9a28e80216be
663,387
import zipfile import os def location_hgt(name: str, fast_zip_check=False): """The location as latitude and longitude based on the filename. If fast_zip_check is True then this will just check the file extention instead of checking the zip. """ if not fast_zip_check and zipfile.is_zipfile(name): ...
271aba064a16a03fafb05944120aea68eea2182a
663,388
def select_supporting_facts(scored_sfs, min_thresholds): """ select supporting facts according to the provided thresholds :param scored_sfs: a list of (sentence_id, score) :param min_thresholds: a list of minimum scores for top ranked supporting facts: [min_score_for_top_ranked, min_score_for...
757f9bc75883b4930166f05874e7e6f102e3fe35
663,389
def strip_quotes(s): """ Remove surrounding single or double quotes >>> print strip_quotes('hello') hello >>> print strip_quotes('"hello"') hello >>> print strip_quotes("'hello'") hello >>> print strip_quotes("'hello") 'hello """ single_quote = "'" double_quote = '"' ...
fbb8650222c53b1bbe354a7d470136e840a395b8
663,390
def is_similar(new_signature, original_signature): """Check if the new state is similar enough to the original state.""" count = 0 if new_signature.crash_type == original_signature.crash_type: count += 1 for line in new_signature.crash_state_lines: if line in original_signature.crash_state_lines: ...
8ff3b87771cca5b819a6f4d2d6372d2acf7502ea
663,391
def project_bucket(project_id, bucket_name): """Return a project-specific bucket name.""" return '{name}.{project_id}.appspot.com'.format( name=bucket_name, project_id=project_id)
b6b8b1c10a2b1e0a748afd1eee15efe27c5a4a22
663,392
def create_buffer(gdf,buffer_distance): """ This function is used to create buffer around given geodataframe with a specified distance Input: - gdf: input geo dataframe Output: - buffer_poly: a buffer around the input gdf with the specified distance """ buffer_po...
a49b051558d600151bac808e9f6376305ebaae67
663,393
def categorical_encoding(item, categories): """ Numerical encoding items for specified categories. If there are no appropriate category, returns -1. :param object item: item to encode. :param list categories: categories to encode by. :return: digit. :rtype: int """ for num, cat in e...
209b2908f05165ea04da6a8e061ca7c841ec88df
663,395
def to_lower(text): """Convert uppercase text into lowercase.""" return text.lower()
bbe4cd3b661d7d73af81352ad88be992697ef0ed
663,396
def finditem(obj, key): """ find key in dict """ if not isinstance(obj, dict): return None elif key in obj: return obj[key] for k, v in obj.items(): ret_obj = finditem(v, key) if ret_obj is not None: return ret_obj
814b7b75a65c9e8e07744ad40cfb53f390aa6573
663,397
def data_indexing(record, broadcastVar, row_counts, col_counts): """ Index the data matrix V to create strata and partition """ (user_id, item_id, rating) = record num_workers, item_bound, usr_bound = broadcastVar.value i = -1 j = -1 for idx in range(num_workers): (lower, upper) ...
3355558af380a4c5212b63c6bb4697054b7684ce
663,398
def yes_no_binarize(df, columns = None, case_sensitive = True, inplace = False): """Replaces ``"Yes"`` and ``"No"`` with ``1`` and ``0``, respectively. Can specify a subset of columns to perform the replacement on using the ``columns`` parameter. :param df: :type df: :class:`~pandas.DataF...
958620dfaad68949e024c7bf66bac4d7a47dc870
663,399
import os def abspath(f): """ It is canonical because: canonical_abspath('y/../y/x') == canonical_abspath('y/x') """ return os.path.abspath(os.path.expanduser(os.path.expandvars(f)))
bd5d114e32db54e666e4d26372681fec506c9da3
663,400
def validate_alignments(item, base_chars='()-'): """Simple validator for alignments Note ---- Make sure an alignment is not longer than its segments. """ for alm in ['Alignment']: derived_alignment = [x for x in item[alm] if x not in '()-'] if len(derived_alignment) != len(item[...
2fd84163e5798d877cf2786f4a2cfc2fe69098d4
663,402
def energy_value(h, J, sol): """ Obtain energy of an Ising solution for a given Ising problem (h,J). :param h: External magnectic term of the Ising problem. List. :param J: Interaction term of the Ising problem. Dictionary. :param sol: Ising solution. List. :return: Energy of the Ising string. ...
866e3175534f5c1e1d606b12e6815cf520a467b0
663,403
def Coeffs_to_ASF(E,coeffs): """Calculate Henke scattering factors from polynomial coefficients. {E in eV and PECS in cm^2/atom}.""" return coeffs[0]*E + coeffs[1] + coeffs[2]/E + coeffs[3]/(E**2) + coeffs[4]/(E**3)
29e05d1385ac93132389892358f4299bf46ee2d0
663,404
def trint(inthing): """ Turn something input into an integer if that is possible, otherwise return None :param inthing: :return: integer or None """ try: outhing = int(inthing) except: outhing = None return outhing
93ecc4b235d8e7e7051b8720cdb832fbd7a04e2e
663,405
import dill def load_fn(path: str): """Load a function from a file produced by ``encode_fn``.""" with open(path, "rb") as file: return dill.load(file)
4ff3afa993474d8ab80adf2967c3b2acd0695075
663,406
import re def fmtVarName(strx): """ transform string into one that meets python naming conventions""" vName=re.sub('[^a-zA-Z0-9_\-\s/]','',strx.strip()) vName=re.sub('[\s/]','_',vName) vName=re.sub('-','_',vName) if re.match('[0-9]',vName): vName='_'+vName return vName
70914fd658031ab01be12ae7ad181043c3bdc385
663,407
def cache_decorator(func): """apply caching to the return value of a function.""" name = '_cached_' + func.__name__ def do_with_cache(self, *args, **kwargs): try: return getattr(self, name) except AttributeError: value = func(self, *args, **kwargs) setat...
d26a100c377b6c55d937325173f0cda61bdb6258
663,409
def aggregate_values(values_list, values_keys): """ Returns a string with concatenated values based on a dictionary values and a list of keys :param dict values_list: The dictionary to get values from :param str[] values_keys: A list of strings to be used as keys :return str: """ output = ""...
2d867560f41e1487c55e498ccdca74ef0c280d32
663,410
import torch def euler(f, omega, time_grid): """ :param f: function describing the differential equations :param omega: function returning values from -inf to 0 as a N-Dim tuple :param time_grid: 1-Dim tensor representing the time-grid on which to integrate :return: 1-Dim tensor the same size as ...
d9c94ae3e9f30cc779bb596320a39aaf77c222a1
663,411
def compute_parameter_importance(model, input_params, param_space): """ Compute the importance for each input parameter in a RF model. For now, importance can only be computed for RF models. :param model: a RF model. :param input_params: the input parameters whose importance we want to compute :...
0731ef0e280f905b0ca33a8bde777500a3f31c5b
663,412
def requirements(): """Load requirements""" with open("requirements.txt") as fileobj: return [line.strip() for line in fileobj]
baf07c02568d03cfb055d9ec1d3a13434286b865
663,413
from typing import Union import torch def int2precision(precision: Union[int, torch.dtype]): """ Get torch floating point precision from integer. If an instance of torch.dtype is passed, it is returned automatically. Args: precision (int, torch.dtype): Target precision. Returns: ...
d748f26c628706fee636479cfcbcd0d863ff7d8e
663,414
def slice_bands_inline(bands, slice_idx): """ Slices the given BandsData such that only the bands given in ``slice_idx`` remain, in the given order. The k-points remain unchanged. """ result = bands.clone() result.set_bands(result.get_bands()[:, slice_idx.get_list()]) return result
a2c45994bc8906a2d9a1576b7537e81596effc29
663,415
def _get_default_adt(): """Returns the boilerplate for a MiCADO ADT Args: filename (string): Filename of K8s manifest(s) Returns: dict: ADT boilerplate """ return { "node_templates": {}, }
e431183777bcc4faaa255cfb92e2a72bb9c21840
663,417
def learning_rate(initial_lr, epoch): """Sets the learning rate to the initial LR decayed by a factor of 10 every N epochs""" lr = initial_lr * (0.975 ** (epoch// 2)) return lr
466d5917835769ceb400f16237b922e776ddcdef
663,418
def get_parent(tree, child_clade): """ Get the parent of a node in a Bio.Phylo Tree. """ if child_clade == tree.root: return None node_path = tree.root.get_path(child_clade) if len(node_path) < 2: return tree.root return node_path[-2]
4352136242ab759d470cad3330f60d74b03cec26
663,419
def result(planet, input_data): """Solve a default impact for the default planet""" result = planet.solve_atmospheric_entry(**input_data) return result
90a044a88a3d250e0fd608b920e460ab43b37d5f
663,420
from datetime import datetime def valid_time(new_time: str): """validate mailing time""" try: datetime.strptime(new_time.strip(), '%H:%M') return True except ValueError: return False
5f9cfa6a20478f2bfe0c8a66ae366f393253bee1
663,421
def mention_user(user): """ Helper function to make it easier to mention users :Args: `user` the ID of the user :Returns: A string formatted in a way that will mention the user on Slack """ return "<@" + user + ">"
2ff453b37f05978b318c1eea5c73c850f84ee75d
663,422
def geojson_driver_args(distribution): """ Construct driver args for a GeoJSON distribution. """ url = distribution.get("downloadURL") or distribution.get("accessURL") if not url: raise KeyError(f"A download URL was not found for {str(distribution)}") return {"urlpath": url}
092709b281a5f14337583db625e1a25ad9d6876d
663,423
import json def maybe_dumps(s): """ If the given value is a json structure, encode it as a json string. Otherwise leave it as is. """ if isinstance(s, (dict, list)): return json.dumps(s) return s
d39c2c7857b060e2eb9101dd33e62507f1257117
663,424
def escape_naive(context): """A tag that doesn't even think about escaping issues""" return "Hello {0}!".format(context['name'])
bede9da0bdf7d63ab04103af2999a66af94b6c4c
663,426
import threading import types def synchronize_class(sync_class): """Make any class [somewhat] thread-safe by acquiring an object-wide lock on every method call. Note: this will *not* protect access to non-method attributes. Based on: http://theorangeduck.com/page/synchronized-python """ lock...
1a3c698497a21a476f8a426e2d57b2a54ff2d322
663,427
import html def escape(s, quotes=True): """ Converts html syntax characters to character entities. """ return html.escape(s, quotes)
d7b1fb4e3d4c72b23e873fd80d90aae012e8a70a
663,428