content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def make_term_structure(rates, dt_obs): """ rates is a dictionary-like structure with labels as keys and rates (decimal) as values. TODO: Make it more generic """ settlement_date = pydate_to_qldate(dt_obs) rate_helpers = [] for label in rates.keys(): r = rates[label] h =...
ccef79d5f409d6dc061e546daa8b3eba1aa6d070
15,100
def skip_after_postgres(*ver): """Skip a test on PostgreSQL after (including) a certain version.""" ver = ver + (0,) * (3 - len(ver)) def skip_after_postgres_(f): @wraps(f) def skip_after_postgres__(self): if self.conn.server_version >= int("%d%02d%02d" % ver): re...
075aecad4bcdd2340ec57089124143cc3642a38b
15,101
def validateParameters(options): """ Who needs documentation TODO: Add some... """ #options.identity should be a valid file if os.path.isfile(options.identity): try: f = open(options.identity, "r") except IOError as err: print "Could not open the identity...
6ecfa0e919a5f54687ab27d652dcf6e4c8b56106
15,102
def make_order_embeddings(max_word_length, order_arr): """ 根据笔顺表生成具有最大字长约束的笔顺embeddings :param max_word_length: :param order_arr: :return: """ order_arr = [ row + [0] * (max_word_length - len(row)) if len(row) <= max_word_length else row[:max_word_length - 1] + [row[-1]] ...
a2f2ac2d0576b2a22145e583cc1e5b8fa9c1cc77
15,103
import numpy def agg_double_list(l): """ @param l: @type l: @return: @rtype: """ # l: [ [...], [...], [...] ] # l_i: result of each step in the i-th episode s = [numpy.sum(numpy.array(l_i), 0) for l_i in l] s_mu = numpy.mean(numpy.array(s), 0) s_std = numpy.std(numpy.array(s), 0) return s_mu, s_std
82b67e70caccb1f5d430e8e9f0a9c75348d3bc7a
15,104
def get_string_from_bytes(byte_data, encoding="ascii"): """Decodes a string from DAT file byte data. Note that in byte form these strings are 0 terminated and this 0 is removed Args: byte_data (bytes) : the binary data to convert to a string encoding (string) : optional, the encoding type to...
c07523139e2509fcc19b2ce1d9a933fcb648abfd
15,105
def default_component(): """Return a default component.""" return { 'host': '192.168.0.1', 'port': 8090, 'name': 'soundtouch' }
780dd84ff613f2bccb56f560e5de77e9d57d9d5a
15,106
from pathlib import Path def check_series_duplicates(patches_dir, series_path=Path('series')): """ Checks if there are duplicate entries in the series file series_path is a pathlib.Path to the series file relative to the patches_dir returns True if there are duplicate entries; False otherwise. "...
58a5b6fbcf6867d770693938a2fc8308d644d54b
15,107
def is_free(board: list, pos: int) -> bool: """checks if pos is free or filled""" return board[pos] == " "
64b75aa5d5b22887495e631e235632e080646422
15,108
def rc_from_blocks(blocks): """ Computes the x and y dimensions of each block :param blocks: :return: """ dc = np.array([np.diff(b[:, 0]).max() for b in blocks]) dr = np.array([np.diff(b[:, 1]).max() for b in blocks]) return dc, dr
0837367eca7a7668a3f0b0078cf8699f5e5bc4d6
15,109
import argparse def _create_parser(): """ Creates argparser for SISPO which can be used for CLI and options """ parser = argparse.ArgumentParser(usage="%(prog)s [OPTION] ...", description=__file__.__doc__) parser.add_argument("-i", "--inputdir", ...
f1f62b8be37139c8c73293b376e0b9bd0540e5c5
15,110
def serialize_measurement(measurement): """Serializes a `openff.evaluator.unit.Measurement` into a dictionary of the form `{'value', 'error'}`. Parameters ---------- measurement : openff.evaluator.unit.Measurement The measurement to serialize Returns ------- dict of str and str...
69eedd9006c63f5734c762d6113495a913d5a8c4
15,111
from exifpy.objects import Ratio def nikon_ev_bias(seq): """ http://tomtia.plala.jp/DigitalCamera/MakerNote/index.asp First digit seems to be in steps of 1/6 EV. Does the third value mean the step size? It is usually 6, but it is 12 for the ExposureDifference. Check for an error conditi...
09a91fc3d82851bb6411b549c282a16f02470e88
15,112
import json def process_message(schema, publisher, data): """ Method to process messsages for all the bases that uses Google's Pub/Sub. Args: schema (:obj:`dict`, required): A JSON schema for contract validation. JSON Schema is a vocabulary that allows you ...
01e396355e6f7fd6913eaff786af39c95da64718
15,113
def rename_record_columns(records, columns_to_rename): """ Renames columns for better desc and to match Socrata column names :param records: list - List of record dicts :param columns_to_rename: dict - Dict of Hasura columns and matching Socrata columns """ for record in records: for col...
41d5cc90a368f61e8ce138c54e9f5026bacd62b9
15,114
import requests import json def request_similar_resource(token, data_): """If a similar resource to the data_ passed exists, this method gets and returns it """ headers = {'Authorization': 'Token {}'.format(token.token)} # get the resource endpoint url_check_res = URL.DB_URL + 'getSimilarResource/' ...
84981ff2520050651b0cb83b11198a2fc1117582
15,115
def total (initial, *positionals, **keywords): """ Simply sums up all the passed numbers. """ count = initial for n in positionals: count += n for n in keywords: count += keywords[n] return count
2df0b37ddec7e4bcdd30d302d1b7297cec0ef3cc
15,116
def login_required(f): """Ensures user is logged in before action Checks of token is provided in header decodes the token then returns current user info """ @wraps(f) def wrap(*args, **kwargs): token = None if 'x-access-token' in request.headers: token = request.heade...
68b36213830f9fad7f6bcf7ec5951534331c5507
15,117
def loop_to_unixtime(looptime, timediff=None): """Convert event loop time to standard Unix time.""" if timediff is None: timediff = _get_timediff() return looptime + timediff
c2da70e961a5802c2da37f04094baec2c6c88f3c
15,118
def groups(column: str) -> "pli.Expr": """ Syntactic sugar for `pl.col("foo").agg_groups()`. """ return col(column).agg_groups()
30fd3eae7abb4c47ce5d12d0c5d17184d5c25770
15,119
from authentek.internal import app import os def create_app(testing=False, cli=False) -> Flask: """Application factory, used to create application """ app.config.from_object(os.getenv('APP_SETTINGS', 'authentek.server.config.DevelopmentConfig')) if testing is True: app.config["TESTING"] = True...
044ad7531f8ca1410f2d2f232856715a9c12e0d3
15,120
def filter_roidb(roidb, config): """ remove roidb entries without usable rois """ def is_valid(entry): """ valid images have at least 1 fg or bg roi """ overlaps = entry['max_overlaps'] fg_inds = np.where(overlaps >= config.TRAIN.FG_THRESH)[0] bg_inds = np.where((overlaps < conf...
e93c4e2236c1febd773e216f109cd2657c94084e
15,121
def get_res(url): """ 使用requests获取结果 :param url: :return: """ try: requests.adapters.DEFAULT_RETRIES = 5 res = requests.get(url) time.sleep(random.randint(0, 3)) if res.status_code == 200: return res return None except Exception, e: ...
ed643029be33ff3e76822f74060b0b3588f97f50
15,122
def seebeck_thermometry(T_Kelvin): """ This function returns the Seebeck coefficient of the thermocouple concerned (by default type "E") at a certain temperature. The input of the function is a temperature in Kelvin, but the coefficient below are for a polynomial function with T in Celsius. The output is S in [V...
8fca07e7e6488a98c96cc76c68d4ab1b656951e5
15,123
def correlation_permutation_test( x, y, f, side, n=10000, confidence=0.99, plot=None, cores=1, seed=None ): """This function carries out Monte Carlo permutation tests comparing whether the correlation between two variables is statistically significant :param x: An iterable of X values observed :param y...
bc6667985d3046f5b97dd01f109c94449f044bf9
15,124
def value_iteration(model, maxiter=100): """ Solves the supplied environment with value iteration. Parameters ---------- model : python object Holds information about the environment to solve such as the reward structure and the transition dynamics. maxiter : int The ma...
e04ffc27be47470f466832a14f9ecf9910d18f27
15,125
from typing import Callable import inspect import abc def node(function: Callable): """A decorator that registers a function to execute when a node runs""" sig = inspect.signature(function) args = [] for (name, param) in sig.parameters.items(): value = param.default if value is inspe...
65ed2c383e1354a0663daef98b78b73382ea65ea
15,126
def mg_refractive(m, mix): """Maxwell-Garnett EMA for the refractive index. Args: m: Tuple of the complex refractive indices of the media. mix: Tuple of the volume fractions of the media, len(mix)==len(m) (if sum(mix)!=1, these are taken relative to sum(mix)) Returns: The ...
57712b6abd9b6a5a642767fa91b6212729b697dc
15,127
def locateObjLocation(data, questionDict, questionIdict): """ Locate the object of where questions. Very naive heuristic: take the noun immediately after "where". """ where = questionDict['where'] for t in range(data.shape[0] - 1): if data[t, 0] == where: for u in range(t + 1...
4b0b8ff892e7d6fdbd9b1cf9d7a9ce7a50ba90c2
15,128
def main(config, model, stid, forecast_date): """ Produce a Forecast object from bufkit data. """ # Get parameters from the config try: bufr = config['BUFKIT']['BUFR'] except KeyError: raise KeyError('bufkit: missing BUFR executable path in config BUFKIT options') try: ...
4a9dccc58ac96f7e3c4b90d3d94c12d602d67d15
15,129
from typing import Union from typing import List def mkshex(shapes: Union[CSVShape, List[CSVShape]]) -> Schema: """Convert list of csv2shape Shapes to ShExJSG Schema object.""" # pylint: disable=invalid-name # One- and two-letter variable names do not conform to snake-case naming style if isinstance...
3cc83d3a23ca982f30c6b4b64553801e404ef1b3
15,130
def get_unsigned_js_val(abs_val: int, max_unit: int, abs_limit: int) -> int: """Get unsigned remaped joystick value in reverse range (For example if the limit is 2000, and the input valueis also 2000, the value returned will be 1. And with the same limit, if the input value is 1, the output value wwill ...
6e77d76423ffeef756291924d00cbdbb2c03cc07
15,131
def to_xyz(struct, extended_xyz: bool = True, print_stds: bool = False, print_forces: bool = False, print_max_stds: bool = False, print_energies: bool = False, predict_energy=None, dft_forces=None, dft_energy=None, timestep=-1, write_file: str = '', append: bool = False, labe...
729a5429d2c6b4cc0c63462577b91a582bf197ed
15,132
def load_file(filename: str): """Load the .xls file and return as a dataframe object.""" df = pd.read_csv(filename, delimiter='\t') return df
09a7f6abc67bf80651dffe5d7698798f5dfc5be8
15,133
def loadRegexList(regexListFile): """Returns regexList, registries, internetSources""" regexList = [] registries = set() internetSourceTypes = set() libLF.log('Loading regexes from {}'.format(regexListFile)) with open(regexListFile, 'r') as inStream: for line in inStream: line = line.strip() ...
7a3fe4c269aa4c868684384417f3c1d0229fcad8
15,134
def _decode_and_center_crop(image_bytes, image_size, resize_method=None): """Crops to center of image with padding then scales image_size.""" shape = tf.shape(image_bytes) image_height = shape[0] image_width = shape[1] padded_center_crop_size = tf.cast( ((image_size / (image_size + CROP_PADDING)) * ...
933bfb91a84f9fe403adf9cbfc9efeb57d1e50f0
15,135
import typing import numpy def match_beacons_translate_only( sensor_a_beacons: typing.Set[typing.Tuple[int, int, int]], sensor_b_beacons: numpy.ndarray, min_matching: int, ) -> typing.Optional[numpy.ndarray]: """ Search for matching beacons between `sensor_a_beacons` and `sensor_b_beac...
0fd12c05d9ee159e301c7bad9d1ddcaa3009a960
15,136
def txm_log(): """ Return the logger. """ return __log__
3b03daf2075549dc4d333e5a47d8e9a1cef21152
15,137
def remove_list_by_name(listslist, name): """ Finds a list in a lists of lists by it's name, removes and returns it. :param listslist: A list of Twitter lists. :param name: The name of the list to be found. :return: The list with the name, if it was found. None otherwise. """ for i in range(...
356a7d12f3b2af9951327984ac6d55ccb844bf72
15,138
import math def song_clicks_metric(ranking): """ Spotify p :param ranking: :return: """ if 1 in ranking: first_idx = ranking.index(1) return math.floor(first_idx / 10) return 51 @staticmethod def print_subtest_results(sub_test_names, metric_names, results): ...
ec6400e7929a2ab0f7f691fffa0ecb3be039b012
15,139
import copy def merge_reports(master: dict, report: dict): """ Merge classification reports into a master list """ keys = master.keys() ret = copy.deepcopy(master) for key in keys: scores = report[key] for score, value in scores.items(): ret[key][score] += [value] ...
3ac633c38a8bb73a57841138cba8cbb80091cf04
15,140
import os import logging def parse_xeasy_peaks(peak_file): """ Parse Xeasy3D peakfile to Peaks object Xeasy file format stores a column labled 'unused' to indicate rather the peak has been used in a structure calculation procedure (0 or 1). This column is, however, not assigned automatica...
3c17e6e6da4591e96ac5313ca3374894da96eff5
15,141
def multi_layer_images(): """ Returns complex images (with sizes) for push and pull testing. """ # Note: order is from base layer down to leaf. layer1_bytes = layer_bytes_for_contents( "layer 1 contents", mode="", other_files={"file1": "from-layer-1",} ) layer2_bytes = layer_bytes_f...
08b35fa4202a7d25ec415ed3b6d1ae6a9f37fd9c
15,142
from typing import Iterable def user_teams(config: Config, email: str) -> Iterable[Team]: """Return the teams a user member is expected to be a member of. Only the teams in which the user is a direct member are return. The ancestors of these teams are not returned. """ names = config.by_member.ge...
669ec82b68e8e530dafeee4e272c85743bde7db1
15,143
import torch def se3_transform(g, a, normals=None): """ Applies the SE3 transform Args: g: SE3 transformation matrix of size ([1,] 3/4, 4) or (B, 3/4, 4) a: Points to be transformed (N, 3) or (B, N, 3) normals: (Optional). If provided, normals will be transformed Returns: ...
9d8ca31dd6df6382e6a45fb80f30b61e9902da5c
15,144
def summarize_single_OLS(regression, col_dict, name, is_regularized=False): """Return dataframe aggregating over-all stats from a dictionary-like object containing OLS result objects.""" reg = regression try: col_dict['rsquared'][name] = reg.rsquared except AttributeError: col_dict['rsq...
b7dd8dfac6cf1b743491ae4e1abfc20fb73e8f31
15,145
def simplify(polynom): """Simplifies a function with binary variables """ polynom = Poly(polynom) new_polynom = 0 variables = list(polynom.free_symbols) for var_i in variables: coefficient_i = polynom.as_expr().coeff(var_i)/2 coefficient_i += polynom.as_expr().coeff(var_i ** 2) ...
62647c9a7530df8b73644e7af96b77b06bfb5285
15,146
def process_login(): """Log user into site. Find the user's login credentials located in the 'request', look up the user, and store them in the session. """ user_login = request.get_json() if crud.get_user_by_email(user_login['email']): current_user = crud.get_user_by_email(user_l...
39e0498370e06ca3203c1212552ce435b1d047e0
15,147
def is_int(var): """ is this an integer (ie, not a float)? """ return isinstance(var, int)
09924c6ea036fc7ee1add6ccbefc3fb0c9696345
15,148
def returnstringpacket(pkt): """Returns a packet as hex string""" myString = "" for c in pkt: myString += "%02x" % c return myString
866ef7c69f522d4a2332798bdf97a966740ea0e4
15,149
def GetIndicesMappingFromTree( tree ): """ GetIndicesMappingFromTree ========================= reuse bill's idea to gives the indexes of all nodes (may they be a sub tree or a single leaf) gives a list of indices of every sublist. To do that, I add one thing: the last element of an index is the ...
d18e85943273a1f4a75951f3f3fda176853b06e0
15,150
import warnings import os def preprocess_labs(lab_df: pd.DataFrame, material_to_include: list = ['any_blood'], verbose: bool = True) -> pd.DataFrame: """ Preprocess the labs dataframe :param lab_df: :param material_to_include: list of materials to include where material is one of t...
2f90d6e5a89fc1a0873b0878293186d657c42eef
15,151
def find_option(command, name): """ Helper method to find command option by its name. :param command: string :param name: string :return: CommandOption """ # TODO: use all_options if command in COMMAND_OPTIONS: if name == 'help': return OPTION_HELP for opt in ...
229505b909c9b42d6f1e686763db3422cd1249cb
15,152
import random def generate_pairwise(params, n_comparisons=10): """Generate pairwise comparisons from a Bradley--Terry model. This function samples comparisons pairs independently and uniformly at random over the ``len(params)`` choose 2 possibilities, and samples the corresponding comparison outcomes...
96bea4a192d81eaf9a43f8ae493187d826dcdb21
15,153
def render_json(fun): """ Decorator for views which return a dictionary that encodes the dictionary into a JSON string and sets the mimetype of the response to application/json. """ @wraps(fun) def wrapper(request, *args, **kwargs): response = fun(request, *args, **kwargs) tr...
15984f0fe7a6a5fbc5a6c9b360bb2780854868b4
15,154
from typing import List def count_smileys_concise(arr: List[str]) -> int: """ Another person's implementation. Turns the list into an string, then uses findall() on that string. Turning the result into a list makes it possible to return the length of that list. So this version is more concise, but...
8fbd353422cbac9840294af3d0a6022d8a45e4e1
15,155
def transform_dead_op_vars(graph, translator=None): """Remove dead operations and variables that are passed over a link but not used in the target block. Input is a graph.""" return transform_dead_op_vars_in_blocks(list(graph.iterblocks()), [graph], translator)
c10fde9cca58732bf6bd17018e963ee629a1796d
15,156
import torch def test_reconstruction_torch(): """Test that input reconstruction via backprop has decreasing loss.""" if skip_all: return None if run_without_pytest else pytest.skip() if cant_import('torch'): return None if run_without_pytest else pytest.skip() device = 'cuda' if torch....
070e7e52ce44c2a875a7ad418ffb985a1827d8c6
15,157
def to_pixels(Hinv, loc): """ Given H^-1 and (x, y, z) in world coordinates, returns (c, r) in image pixel indices. """ loc = to_image_frame(Hinv, loc).astype(int) return (loc[1], loc[0])
09dff4d2045c64d753aa8229f44f049f1a6936c3
15,158
from io import StringIO import os import shutil def temporary_upload(request): """ Accepts an image upload to server and saves it in a temporary folder. """ if not 'image' in request.FILES: return HttpResponse(simplejson.dumps({'status': 'no image uploaded'})) filename = request.FILES['im...
432ce9fe26b9ea09c2399418e7d6027ba17ce1d2
15,159
import os def adf_test(path): """ Takes a csv file path as input (as a string) This file must have one heading as Dates and the other as Close This csv file will be converted into a series and then the ADF test will be completed using data from that csv file (Optional: will plot the data u...
dd29d22f9739c6a4b17d7c53d968591cf575182a
15,160
def calc_distance_between_points_two_vectors_2d(v1, v2): """calc_distance_between_points_two_vectors_2d [pairwise distance between vectors points] Arguments: v1 {[np.array]} -- [description] v2 {[type]} -- [description] Raises: ValueError -- [description] ValueError...
75d00fae9dbe8353e1b53d12428de054e267a528
15,161
import heapq import random def get_nearest_list_index(node_list, guide_node): """ Finds nearest nodes among node_list, using the metric given by weighted_norm and chooses one of them at random. Parameters ---------- node_list : list list of nodes corresponding to one of the two search trees growing towards ...
7d8a373a589e87dc04f72150424685c088b535fb
15,162
def get_extensions_from_dir(path: str) -> list[str]: """Gets all files that end with ``.py`` in a directory and returns a python dotpath.""" dirdotpath = ".".join(path.split(sep)[1:]) # we ignore the first part because we don't want to add the ``./``. return [f"{dirdotpath}.{file}" for file in listdir(path...
c5a12241270f970733c055493534c7f5e8548fd2
15,163
def to_normalized_exacta_dividends(x,scr=-1): """ Convert 2-d representation of probabilities to dividends :param x: :param scr: :return: """ fx = to_normalized_dividends( to_flat_exacta(x), scr=scr ) return from_flat_exacta(fx, diag_value=scr)
1c216908752326333185da7d21e7657f722e20f1
15,164
def CSVcreation(): """This functions allows to access to page for the creation of csv""" if "logged_in" in session and session["logged_in"] == True: print("User login", session["username"]) try: count1 = managedb.getCountLoginDB(session["username"]) if count1 == 0: ...
33af7221ab77d8d0d40b60d220ce8e59ba728f0f
15,165
from pathlib import Path def filter_perm(user, queryset, role): """Filter a queryset. Main authorization business logic goes here. """ # Called outside of view if user is None: # TODO: I think this is used if a user isn't logged in and hits our endpoints which is a problem return ...
9489253f19af9bb0d0d4fdbcc00f349037f7b85a
15,166
import types def generate_copies(func, phis): """ Emit stores to stack variables in predecessor blocks. """ builder = Builder(func) vars = {} loads = {} # Allocate a stack variable for each phi builder.position_at_beginning(func.startblock) for block in phis: for phi in ph...
5ee76907970dea569c34d3bd4a5f57456bed7eb4
15,167
from typing import Sequence def calculate_dv(wave: Sequence): """ Given a wavelength array, calculate the minimum ``dv`` of the array. Parameters ---------- wave : array-like The wavelength array Returns ------- float delta-v in units of km/s """ return C.c_km...
8e29af2644a97948330a4a5fcaaeb2e49ddad831
15,168
def check_link_errors(*args, visit=(), user="user", **kwargs): """ Craw site starting from the given base URL and raise an error if the resulting error dictionary is not empty. Notes: Accept the same arguments of the :func:`crawl` function. """ errors, visited = crawl(*args, **kwargs) ...
571b03e555894560128530c6e751c50a4aed0e21
15,169
def cart3_to_polar2(xyz_array): """ Convert 3D cartesian coordinates into 2D polar coordinates. This is a simple routine for converting a set of 3D cartesian vectors into spherical coordinates, where the position (0, 0) lies along the x-direction. Parameters ---------- xyz_array : ndarray ...
37220bd026ae48bf5a9914117075a10a51efba5a
15,170
import requests def deploy_release(rel_id, env_id): """deploy_release will start deploying a release to a given environment""" uri = config.OCTOPUS_URI + "/api/deployments" r = requests.post(uri, headers=config.OCTOPUS_HEADERS, verify=False, json={'ReleaseId': rel_id, 'EnvironmentId'...
08eae9366a3233704f65a6f952801cdd3ffbe867
15,171
def create_static_route(dut, next_hop=None, static_ip=None, shell="vtysh", family='ipv4', interface = None, vrf = None): """ To create static route Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com) :param dut: :param next_hop: :param static_ip: :param shell: sonic|vtysh :param family...
9097f016eaeb85e9b84351d50cac71d88779b1c1
15,172
def _markfoundfiles(arg, initargs, foundflags): """Mark file flags as found.""" try: pos = initargs.index(arg) - 1 except ValueError: pos = initargs.index("../" + arg) - 1 # In cases where there is a single input file as the first parameter. This # should cover cases such as: ...
e27ca91de403a6364cbebc8ee4ee835a9335dccc
15,173
def part_a(puzzle_input): """ Calculate the answer for part_a. Args: puzzle_input (list): Formatted as the provided input from the website. Returns: string: The answer for part_a. """ recipes_to_make = int(''.join(puzzle_input)) elf_index_1 = 0 elf_index_2 = 1 recip...
50e1cf923184a15747322528a47bad248c03dfa2
15,174
def _CompareFields(field, other_field): """Checks if two ProtoRPC fields are "equal". Compares the arguments, rather than the id of the elements (which is the default __eq__ behavior) as well as the class of the fields. Args: field: A ProtoRPC message field to be compared. other_field: A ProtoRPC mess...
d6ce0b7f7caafd17dff188679800dee2dbe8e791
15,175
import os def classpath_dest_filename(coord: str, src_filename: str) -> str: """Calculates the destination filename on the classpath for the given source filename and coord. TODO: This is duplicated in `COURSIER_POST_PROCESSING_SCRIPT`. """ dest_name = coord.replace(":", "_") _, ext = os.path.spl...
e14a86897ebe6f4e75e4d7ac16737ffda83d632f
15,176
def loadtxt_rows(filename, rows, single_precision=False): """ Load only certain rows """ # Open the file f = open(filename, "r") # Storage results = {} # Row number i = 0 # Number of columns ncol = None while(True): # Read the line and split by commas ...
9393cf7df8f24910a81e7d55128164a9bb467d91
15,177
def create_signal(frequencies, amplitudes, number_of_samples, sample_rate): """Create a signal of given frequencies and their amplitudes. """ timesamples = arange(number_of_samples) / sample_rate signal = zeros(len(timesamples)) for frequency, amplitude in zip(frequencies, amplitudes): signa...
58876fd45e96d221220ccc4ad0129cf48912d691
15,178
import logging import requests from datetime import datetime def serp_goog(q, cx, key, c2coff=None, cr=None, dateRestrict=None, exactTerms=None, excludeTerms=None, fileType=None, filter=None, gl=None, highRange=None, hl=None, hq=None, imgColorType=None, imgDominantColor=None,...
ca1b32d2795c035aab8578f0dc36f4a8dd503bec
15,179
import os import subprocess def get_git_revision(): """ Get the number of revisions since the beginning. """ revision = "0" if os.path.isdir(os.path.join(basedir, '.git')): try: proc = subprocess.Popen( ['git', '-C', basedir, 'rev-list', '--count', 'HEAD'], ...
0aa0d132ac79698f418c1200db5a730a60300d4c
15,180
def get_wiki_modal_data(term): """ runs the wikiperdia helper functions and created the wikipedia data ready for the modal """ return_data = False summary_data = get_wiki_summary(term=term) related_terms = get_similar_search(term=term) if summary_data: return_data = { ...
2d19c8ac1b3d261b3866b69a6a70d78ddac0ad0c
15,181
def format_taxa_to_js(otu_coords, lineages, prevalence, min_taxon_radius=0.5, max_taxon_radius=5, radius=1.0): """Write a string representing the taxa in a PCoA plot as javascript Parameters ---------- otu_coords : array_like Numpy array where the taxa is positioned li...
46052620ee7d4092761e728d78d6ab7b6abb6b45
15,182
import argparse from typing import List def _get_symbols_from_args(args: argparse.Namespace) -> List[icmsym.Symbol]: """ Get list of symbols to extract. """ # If all args are specified to extract only one symbol, return this symbol. if args.symbol and args.exchange and args.asset_class and args.cu...
7257d2b43d242ee552b320826c0a417d2a508d74
15,183
def compute_heading(mag_read): """ Computes the compass heading from the magnetometer X and Y. Returns a float in degrees between 0 and 360. """ return ((atan2(mag_read[1], mag_read[0]) * 180) / pi) + 180
c160e7a69aa0d4bdfe232f45094e863d0d8dd478
15,184
def ConvertTrieToFlatPaths(trie, prefix=None): """Flattens the trie of paths, prepending a prefix to each.""" result = {} for name, data in trie.items(): if prefix: name = prefix + '/' + name if len(data) != 0 and not 'results' in data: result.update(ConvertTrieToFlatPaths(data, name)) el...
c226f3c9d72ca04d5dfe3267a92888bc6255d649
15,185
from typing import List from pathlib import Path def get_root_version_for_subset_version(root_dataset_path: str, sub_dataset_version: str, sub_dataset_path: MetadataPath ) -> List[str]: """ ...
b77da6b9f35e50e463dfba8cd2d710c357615d36
15,186
def subject() -> JsonCommandTranslator: """Get a JsonCommandTranslator test subject.""" return JsonCommandTranslator()
eed4b66f06a0257b2070e17b7cffa9f9005b6b0d
15,187
import torch def accuracy(output, target, cuda_enabled=True): """ Compute accuracy. Args: output: [batch_size, 10, 16, 1] The output from DigitCaps layer. target: [batch_size] Labels for dataset. Returns: accuracy (float): The accuracy for a batch. """ batch_size = ta...
fc795bf54bfccfeea6bb3e8f1f81aa7282499d39
15,188
import sqlite3 def save_message(my_dict): """ Saves a message if it is not a duplicate. """ conn = sqlite3.connect(DB_STRING) # Create a query cursor on the db connection queryCurs = conn.cursor() if my_dict.get('message_status') == None: my_dict['message_status'] = "Unconfirmed" ...
57f65f949c731b8120dec1b0f1b77b3d29505497
15,189
from typing import List def getKFolds(train_df: pd.DataFrame, seeds: List[str]) -> List[List[List[int]]]: """Generates len(seeds) folds for train_df Usage: # 5 folds folds = getKFolds(train_df, [42, 99, 420, 120, 222]) for fold, (train_idx, valid_idx, test_idx) in enumer...
adc25fad4530bf0f134033d95a1d936fb7eb2653
15,190
def redownload_window() -> str: """The number of days for which the performance data will be redownloaded""" return '30'
d5cc816f426f26586870def4797b91a05e37825a
15,191
def clean_flight_probs(flight_probs: np.ndarray, rng: np.random.Generator) -> np.ndarray: """ Round off probabilities in flight_probs to 0 or 1 with random bias of the current probability :param flight_probs: a vector of inclusion probabilities after the landing phase :param rng: a random number genera...
f7127433781df86dabe699575be740f775310194
15,192
async def question(session: AskSession): """ Ask user for his answer on which LeetCode problem he whats to anticipate. """ return await session.prompt( message="Enter the problem URL from LeetCode site: ", validator=LeetCodeUrlValidator(session) )
a4ac5fd194736d2850e70ee5ac89e3569abf4410
15,193
import copy def mongo_instance(instance_dict, ts_dt): """An instance as a model.""" dict_copy = copy.deepcopy(instance_dict) dict_copy["status_info"]["heartbeat"] = ts_dt return Instance(**dict_copy)
32b0547cad0d84400a879814790eed6219ddb84a
15,194
import os def remove(path, force=False): """ Remove the named file or directory Args: path (str): The path to the file or directory to remove. force (bool): Remove even if marked Read-Only. Default is False Returns: bool: True if successful, False if unsuccessful CLI Exa...
5ff9b29999de614e24f80f5ac737ba8ae5f8445e
15,195
def get_conversion_option(shape_records): """Prompts user for conversion options""" print("1 - Convert to a single zone") print("2 - Convert to one zone per shape (%d zones) (this can take a while)" % (len(shape_records))) import_option = int(input("Enter your conversion selection: ")) return import...
7608c588960eb3678970e0d4467c67ff9f17a331
15,196
def base_conditional(Kmn, Lm, Knn, f, *, full_cov=False, q_sqrt=None, white=False): """ Given a g1 and g2, and distribution p and q such that p(g2) = N(g2;0,Kmm) p(g1) = N(g1;0,Knn) p(g1|g2) = N(g1;0,Knm) And q(g2) = N(g2;f,q_sqrt*q_sqrt^T) This method computes the mean and (co)v...
a6ddc7d2904836d7fa83557057dc42e25a8b8a9b
15,197
def find_shortest_dijkstra_route(graph, journey): """ all_pairs_dijkstra_path() and all_pairs_dijkstra_path_length both return a generator, hense the use of dict(). """ all_paths = dict(nx.all_pairs_dijkstra_path(graph)) all_lengths = dict(nx.all_pairs_dijkstra_path_length(graph)) if len(a...
49689cc3f4b03fa6589369bf0d085ee2dbe64d5d
15,198
from functools import reduce import operator def product_consec_digits(number, consecutive): """ Returns the largest product of "consecutive" consecutive digits from number """ digits = [int(dig) for dig in str(number)] max_start = len(digits) - consecutive return [reduce(operator.mul, dig...
2df16f7445e6d579b632e86904b77ec93e52a1f3
15,199