content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def str_list(input_list): """ Convert all the elements in a list to str Args: input_list: list of any elements Returns: list of string elements """ return ['{}'.format(e) for e in input_list]
5e0897a4c2de8516a1154a35e860f93133d9b17b
642,758
import torch from typing import Dict def standardize( x: torch.Tensor, stats: Dict[str, torch.Tensor]) -> torch.Tensor: """Standardize a tensor using precalculated global mean and std. Parameters ---------- x A tensor to be standardized. stats A dict with keys ``me...
76f63ba87380c8a0bf1dc9bcff2558bccb1275e2
642,759
import time def incompatible_flag_verbose_failures_url(): """ URL to the latest version of this script. """ return "https://raw.githubusercontent.com/bazelbuild/continuous-integration/master/buildkite/incompatible_flag_verbose_failures.py?{}".format( int(time.time()) )
daa04b0f3377d083c05a69e62d278cc35a423fb9
642,760
def _from_binary_data(cls, binary_stream): """See base class.""" return cls(binary_stream.tobytes())
933e00f4eb48490dfac6ff2cc1078dda97c33f5c
642,761
import re def filter_re_replace(val, pattern, repl): """Perform a regexp replacement on the given string.""" return re.sub(pattern, repl, str(val))
3ed0121260fbc90a600f66b3df9c1db6465c1ee9
642,762
def unpack_transform_msg(msg, stamped=False): """ Get translation and rotation from a Transform(Stamped) message. """ if stamped: t = msg.transform.translation r = msg.transform.rotation else: t = msg.translation r = msg.rotation return (t.x, t.y, t.z), (r.w, r.x, r.y, r...
de952759dbe61a100e9db5b01de20eb5cf9a1849
642,763
def describe_plus(df): """ Function that returns describe dataframe plus number of NaNs, number of uniques values, the mode # and the std per column :param df: dataframe :return: dataframe """ describe = df.describe() describe.loc['NaNs'] = [df[feature].isnull().sum() for feature in df.c...
b75c65e55bfe21220e4fd26e38c82b127b398ba4
642,764
def get_x_bounds(): """ All problems where we have a design set to explore with a forward function are normalized to be a unit hypercube. [0, 1]^dx """ return 0.0, 1.0
e37d7c2dee436f11653ec1d7ffb659075d7e92d3
642,765
def get_boolean(prompt): """Function to prompt the user for a Boolean value""" while True: try: return {'Y': True, 'N': False}[input(prompt).upper()] except KeyError: print('Sorry, your choice was not recognised. Please enter Y or N:')
973bb81096b0913694e0e7cdb98c23e3bea39130
642,766
def make_poem_html(poem, pid): """This function makes a section of HTML code for a poem. Args: poem: A poem defined as a list (rows) of lists (words in rows). pid: HTML <p> tag ID attribute for CSS identification. Returns: A string containing HTML code for displaying a poem, for ex...
f4e139403bd1e8039aee1a3ad459eddf1dff2b93
642,767
def _img_crop(im, x_pos, y_pos, radius, im_shape): """ Perform crop of the image. Crop the region of the image containing the cell of interest. Parameters ---------- im : numpy.array Fluorescence microscopy image. x_pos : int :math:`x`-coordinate of the center of the cell o...
c49d18d0891d77fabc52ecda77cb69355f475abb
642,768
def scrub_response(secret): """Helper function that provides a filter function for stripping secrets from HTTP responses before they are stored by vcrpy Based on the example implementation found her: https://vcrpy.readthedocs.io/en/latest/advanced.html#custom-response-filtering Example: >...
01701e31e4eac98f234e8dbcb5bc49d4bcd5f999
642,769
import itertools def create_atomic_orbital_names(orbitals): """Generate all atomic orbital names that could be used by Molpro. The names are returned in a dictionary, organized by subshell (S, P, D and so on). """ # We can write out the first two manually, since there are not that many. atomic_o...
d1a1afdd64c32dde5dcf00ae72f59f98672387f7
642,770
def to_int(n): """Converts a string to an integer value. Returns None, if the string cannot be converted.""" try: return int(n) except ValueError: return None
109da76f1368df598016a7bb34af2b11f5d97920
642,772
import re def validate_period_format(period_str): """validates a period in string format Args: period_str (string): period in string format starting with a number and ending with the letters m, h or d, for minutes, hour and day, respectively. Returns: bool: True if the period is valid, else F...
86909345fd09a09d55971bb4567ac268ff48606e
642,774
import importlib def ini_agents(args): """ 定义具体算法,例如DQN """ agent_file_name = str(str(args.algo)) agent_file_import = importlib.import_module(agent_file_name) agent_class_name = args.algo.upper() network_file_name = str(str(args.network)) network_file_import = importlib.import_module(...
e4c649f1ff650b3737ed46fab1d70f8e896771bb
642,775
def config_from_args(args): """pull config variables from parsed args/generic object""" config = { 'SERVER': args.server, 'APIKEY': args.apikey, 'QUEUE': args.queue, 'CAPS': args.caps, } return {k: v for k, v in config.items() if v is not None}
370e2ed8eab344770d92c6d90493d4b040f33e96
642,776
def viralAdvertising(n): # print(n) """ d1[5,0] : 5/2 = 2 =>2*3 = 6 -> 0 + 2 d2[6,2] : 6/2 = 3 =>3*3 = 9 -> 2 + 3 d2[9,5] : 9/2 = 4 =>4*3 = 12 -> 5 + 4 d2[12, 9]: 12/2 = 6 =>6*3 = 18 -> 9 + 6 ... """ cul = 0 t = 5 for i in range(n): nCul = int(t/2) ...
fe4fdbdd0e5a3043a0495103cb28609598d187b9
642,777
import numpy def atleast_3d(ary): """ numpy.atleast_3d adds axes on either side of a 1d array's axis, but I want the new axes to come afterward. :param ary: :type ary: :return: :rtype: """ ary = numpy.asanyarray(ary) if len(ary.shape) == 0: result = ary.reshape(1, 1, 1) ...
4f5dcd39b26ae6bf682870a0c89a658639dda960
642,778
def eval_sequence(seq, dataset, tracker, class_list, metrics_list, metric_names): """Function for evaluating a single sequence""" raw_data = dataset.get_raw_seq_data(tracker, seq) seq_res = {} for cls in class_list: seq_res[cls] = {} data = dataset.get_preprocessed_seq_data(raw_data, cl...
24a618d16ab8d976d8c0189f12cd69d3a278a791
642,779
def get_upper_long_from_trace_id(trace_id): """Returns the upper 8 bytes of the trace ID as a long value, assuming little endian order. :rtype: long :returns: Upper 8 bytes of trace ID """ upper_bytes = trace_id[:16] upper_long = int(upper_bytes, 16) return upper_long
6e9ea39521a21c5e03c6b6a9f63b4b3268977f1d
642,781
def legendre_symbol(x, p): """ a, p sayılarının legendre symbol değerlerini döndürür""" ls = pow(x, (p - 1) // 2, p) if(ls == 1): return 1 elif (ls == 0): return 0 else: return -1
ddcea18f7c6f6092b3faf79a1e4161c12d6a6b00
642,782
import os import re import pickle def translate(counts, dict_words,lowercase,total_files,size,tmpdir): """Translate numbers back to words in a list format for kitconc.""" ngrams = [] files = os.listdir(tmpdir) # unigrams if size == 1: punct = re.compile('^\W+$') # range r...
a19971b0f0738ccb6f20d791efdd5bcbff0a0463
642,783
def get_trace_data_from_file(input_file_name): """Handles the decoding traces.""" with open(input_file_name, "rb") as input_file: return input_file.read() return None
789f0983cbdf58461017cd7505d51d2527251a72
642,784
from functools import reduce import operator def birthday_problem(g, n): """returns the probability that n independent choices from a set of g objects are all unique""" return reduce(operator.mul, [float(g-i)/g for i in range(0, n)])
a9d9d0d27307d05cbad0cb711cf237e8e846a4a1
642,785
import struct def bitness(): # type: () -> int """ The bitness of python running inside Maya as an int. Returns ------- int """ # NOTE: platform.architecture()[0] returns '64bit' on OSX 10.6 (Snow Leopard) # even when Maya is running in 32-bit mode. The struct technique # is m...
8a08ab11a3f05643ba6b57a0a0affde09815a42f
642,786
def bytes2human(byte_count,base=1024,short=True): """ Return a value,label tuple """ if base not in (1024,1000): raise ValueError('base must be 1000 or 1024') labels = ['kilo','mega','giga','tera','peta','exa','zetta','yotta'] name = 'bytes' if short: labels = [l[0] for ...
33cb4f10adaa097c9f3898763d8f424cc1da6165
642,787
from typing import List def format_detector_line(detector_line: List, offset: int) -> str: """ Display detectors from detector_line. """ message = " " * offset last_index = 0 for detector in detector_line: spaces = detector["start_index"] - last_index # Overlay if spaces < 0: ...
17ec4476c20ae8b8423e8819c090160cc8cde9d4
642,788
import os def replace_ext(path: str, ext: str) -> str: """ Replace a path's extension with another. >>> replace_ext('/dir1/dir2/path.ext', '.ext2') '/dir1/dir2/path.ext2' Args: path (str): Path string. ext (str): New extension. Returns: str: Path string with new exte...
3d556d07a45c0712a2fb0c5854bf814bfdd397c4
642,789
def remove_private_prefix(attr_name: str, prefix: str) -> str: """Return the specified attribute name without the specified prefix.""" return attr_name[len(prefix):]
5a41d4c48d0998b7c1cfdc3371da3977a943a29f
642,790
def default_archiver(random, population, archive, args): """Do nothing. This function just returns the existing archive (which is probably empty) with no changes. .. Arguments: random -- the random number generator object population -- the population of individuals archive...
41c42404480dbe30c9884887cd064f1a124fd3b9
642,791
import argparse def get_parser(): """A parser for command line arguments """ parser = argparse.ArgumentParser(description='attention training') parser.add_argument('--seed', type=int, default=42, help='random seed (default: 42)') parser.add_argument('--dataset_path', type=str,...
7a7fdf8260759ee2b1adf2f24d48eedb7242d239
642,792
from datetime import datetime def to_ISO8601(dt: datetime) -> str: """Convert datetime object to ISO 8601 standard UTC string""" return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
a3a0550871fa904d3fd61d2591034cdbf103b66c
642,793
def cmd_subject_hash(cert): """Returns hash of certificate subject. """ return cert.get_subject().hash()
d8c37c7ee5150af69226c321ec606f3605857392
642,794
def findResource(resource, request): """Traverse resource tree to find who will handle the request.""" while request.postpath and not resource.isLeaf: #print 'findResource:', resource, request.postpath pathElement = request.postpath.pop(0) request.prepath.append(pathElement) next...
3a1139feb78060c4b55dd0552bd41bbfe7636260
642,795
import json import os def _GetPackageInfo(package_path): """Returns a tuple with the name and version of a package.""" # Query the metadata file which resides next to the package file. package_info = json.load( open(os.path.join(os.path.dirname(package_path), 'package'))) return (package_info['name'], ...
45db3947fc0c2ecbc6e83e5d5fde0da601f9bfbd
642,796
def print_board(board, rows, cols, row_sep='', col_sep='', joint_sep='', row_fmt='%s\n'): """ Prints the board in a grid format. """ row_sep = row_fmt % joint_sep.join(row_sep * cols) if row_sep else '' return row_sep.join([row_fmt % col_sep.join(board[row * cols:(row + 1) * cols]) for row in range(rows...
fa90129fa0318fca59c90e0ac51ac247e363c076
642,799
def matches(open, close): """ 判断左右括号类型是否匹配,如果下标值相同,则匹配.反之,则未匹配 @open: 左括号 @close: 右括号 @retur: 匹配结果,bool值 """ opens = '([{' closes = ')]}' return opens.index(open) == closes.index(close)
8d1110616f2bb078fb4cea04893b39d794661c58
642,800
def neq(a, b): """Checks if antecedent ⇎ consequent (a ⇎ b). `📘`_ - a: antecedent - b: consequent Example: >>> neq(True, False) == True >>> neq(False, True) == True >>> neq(True, True) == False >>> neq(False, False) == False .. _📘: https://github.com/python3f/extra-boolean/wiki/neq ...
944a157ed824307c3174bbcb32207558ecd51f23
642,801
def getBoolArray(emptyList, fullList, minDistance): """ This function returns the boolean list with True where there is a full circle else False. - The emptyList param is a list with empty cicle coordinates - The fullList param is a list with full cicle coordinates - The minDistance param is the min...
0ff39c85070760b82f366d760f2d005d78ea8ce2
642,802
def check_point(x, y, d, d_shell, length): """ Проверяет точку на принадлежность оболочке волновода Точка в ск Федера """ if 0 <= x <= length: return -d_shell / 2 <= y <= -d / 2 or d / 2 <= y <= d_shell / 2
eefcfe9414c4962f6f51bf342c64177b817e3095
642,803
def _get_key_recursively(response, key, limit): """ Recursively search for a key in a response Not really sure if that's the most elegant solution.""" if response is None: raise TypeError( "Either provide a response or a URL for the next_page and previous_page methods" ) st...
f22e5bdb2b9a79b780b76c3492fdef9c20eb370f
642,804
def sort_annotations_by_offset(annotations): """ This function expects as input a list of dictionaries with this structure: {'ann_id': u'T34', 'continuation': False, 'entity_type': u'Registry', 'positions': [{'end': 2465, 'start': 2448}], 'surface': u'reg 38 Padavinus,'}, And sorts...
3c2cee926243ae487161afb78baa0394cddcb1f3
642,805
def swap_letters(sequence, index_1, index_2): """ Swaps the letters at the indices 1 and 2 and returns the new string. Assumes that index 2 - index 1 is 1. """ string_list = list(sequence) string_list[index_1], string_list[index_2] = string_list[index_2], string_list[index_1] return ''.join(...
36e1b4af1e38a9d1528d3d5ee4dd863173959d57
642,806
from operator import add def do_query(issues, config_file=None, logger=None, context=None): """ Iterate through issues and count total number of issues and total number of words. Returns result of form: { "num_issues": num_issues, "num_words": num_words } :pa...
79231f5e0076ee4bbf0b6d9a96649d034ceb6651
642,807
import time def wait_for( func, max_seconds=10, pause=1 ): """ def wait_for Wait for up to max_seconds for func to return True If func returns True within time alloted, return True Otherwise, return False func must return a boolean value (others might work, but behavior is undefine...
ad4079bb961a4f7be335f5c8616aa7689f367013
642,808
import numpy def threshold_value_op( base_array, threshold_value, base_nodata, target_nodata): """If base > threshold, set to 0.""" result = numpy.empty(base_array.shape, dtype=numpy.uint8) result[:] = target_nodata valid_mask = ~numpy.isclose(base_array, base_nodata) result[valid_mask] = ...
1543257dbb36b6c14ecedb2249d1d831c6afc8f7
642,809
def get_elc_instances(): """Return a mocked list of ElastiCache instances.""" return { 'DescribeCacheClustersResponse': { 'DescribeCacheClustersResult': { 'CacheClusters': [ { 'CacheClusterStatus': 'available', ...
72fda316f7ed896476090f027c618e569d6d30d8
642,812
from typing import OrderedDict def convert_to_order_dict(map_list): """ convert mapping in list to ordered dict @param (list) map_list [ {"a": 1}, {"b": 2} ] @return (OrderDict) OrderDict({ "a": 1, "b": 2 }) """ ordere...
af280b67b7b7f6a88d7d010464e5b1c8fcaf6d0c
642,813
def tcp_opts_tuple_list_to_dict(opts_list: list) -> dict: """Convert tuple of TCP options to a dictionary :param opts_list: list of TCP options tuple :return: diction of TCP options """ opts = {} if None in opts_list: opts_list.remove(None) for opt, value in opts_list: # here...
751689e93e66f54251944343f0cac626bf5103c2
642,815
def has_teacher_permissions(student, course): """ Returns true if the student ist allowed to change and delete the course, i.e. they are a teacher or have general permissions to change and edit course objects """ return course.can_modify(student) or ( student.user.has_perm('course.ch...
955d72d9828dd7a449fdf53f7c05924bfe478f44
642,816
def _sequence(one, two): """Return function calling two functions in order""" if one is None: return two elif two is None: return one return lambda *args, **kargs: (one(*args, **kargs), two(*args, **kargs))[1]
b5ae26c354659fccee26ef2d02a268ab9cbdf68f
642,817
def parseSerialNumber(ManuDataHexStr): """ Parses the serial number from a hex string """ if (ManuDataHexStr == "None"): SN = "Unknown" else: ManuData = bytearray.fromhex(ManuDataHexStr) if (((ManuData[1] << 8) | ManuData[0]) == 0x0334): SN = ManuData[2] ...
b86f34b4c871210f54ccbc25cf2684451f094626
642,818
def add_cache_headers(request): """ The Oauth2 draft spec requires that all token endpoint traffic be marked as uncacheable. """ resp = request.response resp.headerlist.append(('Cache-Control', 'no-store')) resp.headerlist.append(('Pragma', 'no-cache')) return request
a3ec7a08c240ad006b44a260f2a60348fb2c9612
642,819
def getgid(): """Return the real group id of the current process. :rtype: int """ return 0
dc75daef5cfb3998d4398c3d901e2d149f7b6d38
642,820
from numpy import array,argsort,dot,diag from numpy.linalg import eig def SVD_rotation_max_V_auto_correlation(U,s,V): """"Maximize the auto-correlation of the V vectors""" S = diag(s) # Calculate auto-correlation. N = len(V) C = array([sum(V[i,:-1]*V[i,1:]) for i in range(N)]) # Sort the V ve...
2e57dc47398fe14c9462e7402e532d650efb6859
642,821
def _get_early_stopping_params(early_stopping): """Set default parameters if not already set in input. """ if early_stopping is not None: if early_stopping['type'] == 'cost': if 'threshold' not in early_stopping: early_stopping['threshold'] = 0.005 if 'length_...
d65665e4b8bf8cf2fb6d4d1c83e789047d1febbe
642,823
def removeNewLines(sentence): """ Remove new lines """ sentence = sentence.replace('\r\n', ' ').replace('\n', ' ').replace('\r', ' ') return sentence
a3bde1743698b9735128d4b19c7debb62aa64166
642,824
def toStr(pipeObj): """Create string representation of pipeline object.""" res = '' lastIdx = len(pipeObj) - 1 for i, c in enumerate(pipeObj): if c[0]: res += c[0] + '(' res += toStr(c[1]) res += ')' else: res += c[1] if i != lastId...
a7b5397e55a8ea13173695ab8848179d184dc5db
642,825
import copy def dict_np_to_dict_list(input_dict): """ Convert a dict of numpy array to a dict of list """ input_dict = copy.copy(input_dict) if type(input_dict) is dict: for name in list(input_dict.keys()): input_dict.update({name: input_dict[name].tolist()}) return inp...
6ced5c818820d2f2d1d4407ee8422370eaf0b140
642,826
def _construct_instance(Estimator): """Construct Estimator instance if possible.""" # return the instance of the class with default parameters return Estimator.create_test_instance()
a77df893875e25313ddb0cb7e886cba6dde41420
642,828
from typing import List def dict_value_from_path(src_dict: dict, path: List[str], case_sensitive: bool = False): """ returns the value of dict field specified via "path" in form of a list of keys. By default the keys are matching case insensitive way. Example: src_dict = {"level1:{"level2":{"lev...
a76a15c7b0f35ff20fbc0320cac71297b4a7ddcf
642,829
def index(elm, lst): """return int index where elm appears in a list lst. -1 if not found.""" try: if type(list)!=list: lst=list(lst) idx=lst.index(elm) return idx except ValueError: return -1
5bf859aa45d26ab23800383b4e80795fcee99b4b
642,830
import base64 def deep_bytes_to_str(e, encoding: str = 'utf-8'): """ Replaces bytes with their str equivalents """ if isinstance(e, bytes): try: return e.decode(encoding) except: return base64.b64encode(e).decode(encoding) if isinstance(e, dict): for k, v in...
acbea2f3d8930ffe8edd3d2929bb3d5e79c914a2
642,831
def _sqlname(name): """parse database name and table name from given name string name: a string of the form 'databaseurl?table=tablename' """ key = '?table=' if name is None: db, table = None, None # name=None elif name.startswith((key,'table=')): # name='table=memo' db, table = None, n...
3d9e579e3d1b0261dba878d6730553bee0ed52dd
642,832
def get_avg_course_eval_by_department(dict_cursor, departmentID, campus): """ Get information from table Eval about how the average department course was held. """ sql = "SELECT round(avg(intellectuallySimulating), 2) as\ intellectually_simulating, round(avg(deeperUnderstanding), 2) as\ dee...
abe4ed97b599e26f1eb434c06edc870d5cb1fb42
642,833
import pkg_resources def load_engines(group): """Find all the classes that implements `base_class`.""" engines = {} # for _, module_name, _ in pkgutil.walk_packages([path], prefix=prefix): # module = importlib.import_module(module_name) # for klass_name, klass in inspect.getmembers(modul...
a363a693fa6923b5a4f08c8aa11ae93682d2d658
642,834
from math import floor def calcL1Ainterval(rate): """ Returns the L1Ainterval in BX associated with a given rate in Hz """ return floor((1.0 / rate) * (1e9 / 25))
57233912db7fb9f0bf6aa189b1f419a9daa759f4
642,836
def expectation_description(expect = None, expect_failure = None): """Turn expectation of result or error into a string.""" if expect_failure: return "failure " + str(expect_failure) else: return "result " + repr(expect)
0a6944cbe83fbc14723526fd145ab816b86d2f0a
642,839
def get_simulation_priority_value(simulation_result, data_item, target_priority): """ Collect a priority metric from the simulation. :param simulation_result: Metrics on simulation :param data_item: Metric name :param target_priority: Priority :return: List of values from simulation. """ ...
259ecb92c5c0902d60d6fcfb35a4b08ed373fcbb
642,840
def get_keytable_path(opendkim_conf): """Returns the path to the KeyTable file from the OpenDKIM config. """ param = 'KeyTable' with open(opendkim_conf, 'r') as f: for line in f: if line.startswith(param): return line.replace(param, '').strip() msg = "Could not ...
cc40686d6dd9440747dff76ea0ceaafc0c3357ad
642,842
def read_header(fname): """ Read a generic header of the form value key """ header = {} header_lines = "" f = open(fname, "r") for i in range(20): line = f.readline() tokens = line.split() # print "+++ tokens: ",tokens if (len(tokens) != 2) or (type(t...
7fa5c6b801c26990c7e526c007dcb15a33903491
642,843
def dabei(phase): """ Gibt True zurück, wenn die Person in der angegebenen Phase weiterhin mitspielt. """ return phase is True
f68f4bc3268e56cb1347490f497b0ee805f447b4
642,844
def get_V_fan_dsgn_H(V_fan_rtd_H): """(17) Args: V_fan_rtd_H: 定格暖房能力運転時の送風機の風量(m3/h) Returns: 暖房時の送風機の設計風量(m3/h) """ return V_fan_rtd_H * 0.79
144299a005cef4b428d6f7491716d96d45bf58f8
642,845
import pytz def get_time_zone(time_zone_str): """Get time zone from string. Return None if unable to determine.""" try: return pytz.timezone(time_zone_str) except pytz.exceptions.UnknownTimeZoneError: return None
820794b06728c23c4bd9fbb6a31367a40fc66dfb
642,846
def display_timedelta(delta): """convert a timedelta to a human-readable format""" days = "" if delta.days: if delta.days == 1: days = "1 day, " else: days = "{} days, ".format(delta.days) return days + "{}:{:02}:{:02}".format( delta.seconds // 3600, delt...
c57af53cbbcc42fb0b09f31d8ca49b25abd78a67
642,847
def keeponly(value, val, field='ENTRYTYPE'): """ Filter by BibTeX field """ return [entry for entry in value if field in entry.keys() and entry[field] == str(val)]
86c3475fb4c66668b879eec55263359e46cbd575
642,848
def prepare_constructor(tag, children): """ create what is necessary to build a constructor. """ pre_shape = tag.default_shape shape, storage = pre_shape.fusion(children) return (shape, storage)
48bbdbb4cc54adc67e161a4fe74b64565f5df2f3
642,849
def _split_int(integer): """拆分函数,将整数字符串拆分成由4位数字组成的list""" integer = str(integer) int_lst = [] # 以4为单位划分 idx = len(integer) % 4 if idx > 0: int_lst.append(integer[0:idx]) while idx < len(integer): int_lst.append(integer[idx:idx+4]) idx += 4 return int_lst
4c6e289deddd01f1f6dd69d72ad2262756f67e2d
642,852
def number_format(number): """Formats numbers with thousands separators""" return u'{:,}'.format(number)
43880d5bd25d1ba94c5634e423a566568d7fca9a
642,853
def files_exist(files): """Check whether all file names in a list are accessible for reading. """ for f in files: with open(f, "r") as fi: pass return True
23941ee752c965526567571cce894399c1e7a42f
642,854
import importlib def importer(str_or_obj): """ If the argument is a string import it with importlib """ if isinstance(str_or_obj, str): modname, clsname = str_or_obj.rsplit(".", 1) str_or_obj = getattr(importlib.import_module(modname), clsname) return str_or_obj
bfc48942e64397c63749cdad07df66ebc4ed205d
642,855
import os import inspect def determine_file_path(base=None): """Returns the absolute file path for module that invoked this function. This is similar to __file__ but determines it in a way that's suppose to be more portable. @param base: The current working directory that was being used when the module ...
23f15ec666256553db66774f03b2ad2f44bf3cf9
642,856
def recall_score_(y_true, y_pred, pos_label=1): """ Compute the recall score. The recall score is the ability to detect all the positive examples. Args: y_true: a scalar or a numpy ndarray for the correct labels y_pred: a scalar or a numpy ndarray for the predicted labels pos_lab...
8ccee6f09072cc52a46155702b1a1c04ed2173d9
642,857
import torch def total_variation_loss(batch, cfg): """ Takes a batch and computes the total variation loss. Code for this function comes from https://github.com/gordicaleksa/pytorch-neural-style-transfer-fast. """ batch_size = batch.shape[0] tv_loss = (torch.sum(torch.abs(batch[:, :, :, :...
4d0438d6c2197513b626b15a68097fda0524fbde
642,858
import hashlib def get_sha1_file( filename ): """ This module generates sha1sum for the given file Args: filename (str): Full path to the file Returns: sha1sum hash of the file """ hash_size = 256 sha1 = hashlib.sha1() with open( filename, 'rb' ) as f: while Tru...
bc270e386ea658187ba0a16c34097250a996b011
642,859
def check_keys(in_dict): """Checks which keys are present within the input dictionary This function looks within the input dictionary and checks which keys are contained within it. Then, with these keys, it generates a list containing these keys and returns this list as output. Parameters ...
e38c1853b2a73a35c5b615e35980e2b6921825a4
642,860
def kmph_to_mps(kmph): """ Transform a value from kilometers-per-hour to meters-per-second """ return kmph * 0.277778
e264cf6c676daca13bfde3e0e9e242c008e3d5aa
642,862
def asciiToString(ascii_list): """ Ascii bit data change to String list """ bit_index = 2 charic = 0 string_list = list() for bit in ascii_list: charic += bit*pow(4, bit_index) bit_index -= 1 if bit_index < 0: bit_index = 2 charic += 64 string_list.append(chr(charic)) charic = 0 return stri...
b829b2e93683bbde0b219002fcafbf135ef28877
642,863
import os import shutil def sandbox(function, test_dir: str = "test_dir"): """ Executes function in test_dir (making that directory if it doesn't already exist) then deletes test_dir """ def makedirs(*args, **kwargs): # Establish test dir if not os.path.exists(test_dir): ...
b1d9981221c5f5aad0032fe3e65d03520c8fd282
642,864
from typing import List def trades_keys() -> List[str]: """ Expect below keys as result of trade-related API endpoints calls. Endpoints: - `trades` - `historicalTrades` """ return [ 'id', 'isBestMatch', 'isBuyerMaker', 'price', 'qty', 'quoteQty', 'time' ]
248c8c0e70089a3b01230f2c901148f2ac77ce58
642,865
def split(df): """Returns a tuple with down/up-cast.""" idx = df.index.argmax() + 1 down = df.iloc[:idx] # Reverse index to orient it as a CTD cast. up = df.iloc[idx:][::-1] return down, up
a9ff1c5e87e0b97587bd6d1f8c8906ca5d79aeea
642,867
def get_returns(bid, strike_price, dte): """Calculate return and annual return for a sold option.""" put_return = bid / (strike_price - bid) * 100 annual_return = put_return / dte.apply(lambda x: x if x > 0 else 1) * 365 return (round(put_return, 1), round(annual_return, 1))
2292644287ade284922a556513ca5a3c6f5c5d45
642,868
import os from warnings import warn import sys def get_valid_cwd(): """ We check if the current working directory is valid or not. Typically happens when you checkout a different branch on git that doesn't have this directory. We return the original cwd because the shell still considers th...
2f006e19dd82c162dd874fc7e54189836a1a33d4
642,869
import json def reconciliation_period_reformat(lst): """ Reformat reconciliation period into From [dd/mm/yyyy] to [dd/mm/yyyy] format """ try: lst = json.loads(lst) except: lst = [] period = "" for f_date, t_date in lst: period += "From " + f_date + " to " + t_d...
d982f1b3b095e9b4015b76fbba28aff6c78afbf6
642,870
import random def random_pick(some_list, probabilities): """ 根据概率随机获取元素 :param some_list: 元素列表 :param probabilities: 概率列表 :return: 当前元素 """ x = random.uniform(0, 1) cumulative_probability = 0.0 item = some_list[0] for item, item_probability in zip(some_list, probabilities): ...
a137d01112477882ead151f495bb4e2282939540
642,871
def find_closest_versioned_parent(manager, model): """ Finds the closest versioned parent for current parent model. """ for class_ in model.__bases__: if class_ in manager.version_class_map: return manager.version_class_map[class_]
0f63da93cd973a32f9aa1f9990c9333638348849
642,872
import string def valid_str(v): """ Convert a value or values to a string which could go in a filepath. Partly based on `this gist`_. .. _`this gist`: https://gist.github.com/seanh/93666 """ if hasattr(v, '__name__'): return valid_str(v.__name__) if isinstance(v, tuple) or isi...
abff316446c6a6f0263b8199b3123fac82d4e9e1
642,873
def is_ratelimit(tweet): """ Returns True if the "tweet" is a rate-limit response. If False, then it should be an actual tweet. Works with raw tweet (as str) or de-JSONified tweet (as dict). """ if isinstance(tweet, dict): # The tweet is a Python dictionary if 'limit' in tweet...
15f93ae7e2d2cca90c6c6af5efaed4d4b339c1f3
642,874
def sumsq(values): """ Calculates the sum of squares of a list of values. """ return sum(map(lambda x: x ** 2, values))
a8edcba0f475300bd372f0c6b74f9e2e4eff6ad7
642,875