content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def make_safe(s): """Replaces all spaces with '\\ '""" return replaceAll(s, " ", "\\ ")
2f7d09b50cd7d4b78789fd27c31639d1d981b404
44,600
def gradient_descent(w0, optimizer, regularizer=None, opts=dict()): """ Mini-Batch Stochastic Gradient descent algorithm. w0: is the initial guess loss_function: is the loss function you want to optimize. It should have the gradient and loss method. opts: a dictionary with the algorithm parameters ...
070b42508343b662128c60726f6c7ebdc312511c
44,601
import io def parse_xml_file(filename): """Returns a dictionary with the class_id, genus, species, bg_species.""" def strip_tag(s): return s.split('>', 1)[1].split('<', 1)[0] mapping = {"ClassId": "class_id", "Genus": "genus", "Species": "species", "Ba...
14bb447987d42465bfb6543935ba67285e72322c
44,602
import re import ctypes from ctypes import byref import sys import os def autodetect_version(libdirs): """ Detect the current version of HDF5, and return X.Y.Z version string. Intended for Unix-ish platforms (Linux, OS X, BSD). Does not support Windows. Raises an exception if anything goes wrong. ...
c065b901e6cc719f4b190491ed3512348d29de91
44,603
def compute_aggregation_axes(dims, axes=None, keepdims=False): """Computes parameters for an aggregation-over-axes operation. Args: dims ([int or Value]): The dimensions of the value being aggregated. axes ([int], optional): Defaults to None. The indices of the axes to aggregate over. k...
c4d6bec3c9bad18bd56829e05b36030c262a3649
44,604
def dataNormalize(data, maxAudio_total ,maxVisual_total ): """ :param data: the avData, size is (*,288,360) :return: the normalized avData, size is (*,288,360) normalize method: (x-min_local)/(max_total-min_local) """ data_nor = np.zeros(data.shape) for i in range(6): audiodata = dat...
0078397ebbbd360c8ca4d0501cad87cf34582a48
44,605
def is_rfc1918(ip_str): """Returns True if the IP is private. If the IP isn't a valid IPv4 address this function will raise a :class:`ValidationError`. """ private_networks = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"] try: ip_str_network = ipaddr.IPv4Network(ip_str) except ipaddr....
40c103719203f469ccb00e0a27a9524275dbaeb5
44,606
def create_hparams(hparams_string=None, verbose=False): """Create model hyperparameters. Parse nondefault from given string.""" hparams = tf.contrib.training.HParams( ################################ # Experiment Parameters # ################################ epochs=1000, ...
3bed61b035e51cca028cd8dbaf62c44a6dca1b9a
44,607
import astropy.table from copy import deepcopy from legacyhalos.mpi import call_ellipse as mpi_call_ellipse from contextlib import redirect_stdout, redirect_stderr from legacyhalos.mpi import _done import os import shutil import time def call_ellipse(onegal, galaxy, galaxydir, pixscale=0.262, nproc=1, ...
d774bc3e3cd52829f0d369f2583b68cb5f9b7aff
44,608
import sys def start_the_sink_communications_process(): """ Creates a Sink object for a sink process (i.e. initialises the worker_exec process and keeps the zmq communication between the worker_exec and the forwarder) :return: The SinkCom object """ push_port, receiving_topics, _, paramete...
693a489fc9494d45f271b88c4cac65d89089f3d5
44,609
def optionsSymbols( symbol="", expiration="", includeExpired=None, token="", version="stable", filter="", format="json", ): """This call returns an object keyed by symbol with the value of each symbol being an array of available contract dates. https://iexcloud.io/docs/api/#options-...
ea4ff999bd58777d162870b8499a881f0526d351
44,610
import textwrap def text_word_wrap(text, width): """ Word-wrap a string to width `width`. """ return textwrap.wrap(text, width)
7dbaae3a61be37a3208dd9c9b6a541aadb325e3e
44,611
from typing import Union def inspect_coefs(lm, X) -> Union[pd.Series, pd.DataFrame]: """ View a summary of a linear model's coefficients. Works for both linear and logistic regression models. >>> import pydataset >>> iris = pydataset.data('iris') >>> X, y = iris[['Sepal.Length', 'Sepal.Width...
01827a747d6cb0e5d5c221ce358eb2e3b299f6db
44,612
def clean_census_data(df): """ Clean up the census data results from the API. By default, the census data often includes non-numeric characters as annotations or missing values. # see https://www.census.gov/data/developers/data-sets/acs-5year/data-notes.html # for estimate and annotation values ...
978ac976d3a39815c48a827e42760044846eda1b
44,613
import json def move(): """ Called when the Battlesnake Engine needs to know your next my_move. The data parameter will contain information about the board. Your response must include your my_move of up, down, left, or right. """ start = timer() # my_moves delta = [[-1, 0], # go up ...
75c06f215a3a3ebec7b567ff8fb1deac6d604c86
44,614
def find_detection_probability(Mc, eta, redshifts, distances, n_redshifts_detection, n_binaries, snr_grid_at_1Mpc, detection_probability_from_snr, Mc_step=0.1, eta_step=0.01, snr_step=0.1): """ Compute the detection probability given a grid of SNRs and detection probabilities...
4d042c65616d6f4c4952f9478659e32b6dcd746a
44,615
def maybe_value(tree: dict, *path_components: str): """ Get the value corresponding to last key in the key path ``[k1, k2, ..]`` on the input dictionary tree. The key sequence may match an actual key path or match it up to a point or not match any path at all. If a key ``k[n]`` in the input sequence...
6869f81a30d0d5ddf70394a48b7ae5588e778631
44,616
import os def load_datasets(arg_space, use_embds, batchSize, kmer_len=None, embd_size=None, embd_window=None): """ Loads and processes the data. """ input_prefix = arg_space.inputprefix output_dir = 'results/'+arg_space.directory if not os.path.exists(output_dir): os.makedirs(output_di...
565fa7c0b39ffd80b6dc7f1eb9221674d55cdd73
44,617
def response_json_ok(json): """Creates a tuple representing the HTTP package to respond the requisition with the given JSON on its body and status code 200 :param json: object to be sent on HTTP body :return response: tuple representing the HTTP response package """ return _make_json_respons...
07e7c7894ec6deab7795aa70500ab73a795a01ce
44,618
def build_k_indices(y, k_fold, seed=1): """build k indices for k-fold.""" num_row = y.shape[0] interval = int(num_row / k_fold) np.random.seed(seed) indices = np.random.permutation(num_row) k_indices = [indices[k * interval: (k + 1) * interval] for k in range(k_fold)] return...
7e9b1ff6a12669db8d92d6c9034551256ceaa9d0
44,619
import torch def init_model(args, num_classes): """Initialise model""" architecture = getattr(models, args.model) if args.curve is None: model = architecture.base(num_classes=num_classes, **architecture.kwargs) else: curve = getattr(curves, args.curve...
db774fb07dc33fb28e770e06b18d7a0f5b3c8d3c
44,620
def get_LoiterType_str(str): """ Returns a numerical value from a string """ if str == "VehicleDefault": return LoiterType.VehicleDefault if str == "Circular": return LoiterType.Circular if str == "Racetrack": return LoiterType.Racetrack if str == "FigureEight": return LoiterType.FigureEight...
c8905381f56a070b8ecc83545638e0f4a40bc4af
44,621
import json def load_tour(fname): """ Reads a tour from a JSON file. Input: - fname : filename Output: - tour : loaded tour """ with open(fname, 'r') as fp: return json.load(fp)
7cd4db05867d2ab5dd26620c8ff2497eb5aa4a68
44,622
def get_lhn_accordion(driver, object_name): """Select relevant section in LHN and return relevant section accordion.""" selenium_utils.open_url(url.Urls().dashboard) lhn_menu = dashboard.Header(driver).open_lhn_menu() # if object button not visible, open this section first if object_name in cache.LHN_SECTION_...
595c56ba27bf5cd44c0763e49fc61438f36051c0
44,623
import itertools def modular_sqrt_composite(c, factors): """ Calculates modular square root of composite value for given all modulus factors For a = b^2 mod p*q*r*m... calculates b :param c: residue :param factors: list of modulus prime factors :return: all potential root values """ n ...
ea4512dde1eb297911c60145e5f327e55397a4df
44,624
def trim_zeros(x): """It's common to have tensors larger than the available data and pad with zeros. This function removes rows that are all zeros. x: [rows, columns]. """ pre_shape = x.shape assert len(x.shape) == 2, x.shape new_x = x[~np.all(x == 0, axis=1)] post_shape = new_x.shape ...
18e81174191c8299c6c1b6ac38920c07b457d1db
44,625
from bslib import __version__ import ssl import os def build_opener(apiurl, user, password, cookie_path, debuglevel=0, capath=None, cafile=None, headers=()): """build urllib opener for given name/password it creates * HTTPSHandler with proper ssl context * HTTPCookieProcessor with a link to c...
c693f579d4c72fae7c053d0a798c539ba1056141
44,626
def show_user(username): """Some Comment""" return 'Welcome: %s' % username
29980cfe7dba8048aa0ecaa351d9baf4d47dd8ec
44,627
def unfold_rep_seq(rep_seq: str) -> str: """Unfold the rep_seq string.""" unfolded = "" matches = rep_seq_pat.findall(rep_seq) for m in matches: unfolded += m[0] * int(m[1]) + m[2] return unfolded
da5f1434c1cd2970def90ef899fc8ad72c58aea4
44,628
def get_cost(ss, a, dist_mat, C, n): """Determines the cost of an airline route network from a sampleset. Args: - ss: Sampleset dictionary. One solution returned from the hybrid solver. - a: Float in [0.0, 1.0]. Discount allowed for hub-hub legs. - dist_mat: Numpy matrix providing dista...
d8e810133a08213d0815a551c1fd7eaaa650532f
44,629
import os def get_python_code(paths): """ Returns all Python code, as a list of tuples, each one being: (filename, list of lines) """ retval = [] for p in paths: if not os.path.isdir(p): raise Exception("'%s' is not a directory." % p) for (dirpath, dirnames, filena...
455d27565c6c6e7bd468570581c7a25d0548179b
44,630
def get_epsilon_interpolator( eps, t_break, eps2=-1, t_delta_phases=-1, transition_time=14, t_break_final=None, eps_final=None ): """ Return an interpolator that produces an epsilon when called with a time (relative to the model start). The solution has at least 3 steps (4 if t_break_final and eps_final...
7c456cfc737c9625da09555f8262e650124ae7ea
44,631
def get_cqt_index(pitch, hparams): """Get row closest to this pitch in a CQT spectrogram""" frequencies = librosa.cqt_frequencies(constants.TIMBRE_SPEC_BANDS, fmin=librosa.midi_to_hz(constants.MIN_TIMBRE_PITCH), bins_per_octave=...
7dca5cb117f5c64874408b63728a296b99bcb781
44,632
import io def save_file_in_minio(csv_file, shop_key): """ creates a file in the minio stores 'productstore' bucket :param shop_key: A string that is used to specify a shop :param csv_file: A object that is an instance of CsvFile :return: """ with Span(span_name='save_file_in_minio', trace_...
b83b1452dc475b69966c7274446311220147c341
44,633
import unittest import test def suite(): """Suite of test to run""" glome_tests = unittest.TestLoader().loadTestsFromModule(test.glome_test) autoglome_tests = unittest.TestLoader().loadTestsFromModule( test.autoglome_test) fuzzing_tests = unittest.TestLoader().loadTestsFromModule(test.fuzzing_...
becc2d4834cc6cf44b32d7a2502772c777c993c3
44,634
def kde_2d(df, w, x, y, xmin=None, xmax=None, ymin=None, ymax=None, numx=50, numy=50): """ Calculates a 2 dimensional histogram from a Dataframe and weights. For example, a results distribution might be obtained from the history class and plotted as follows:: df, w = history.get_dis...
2a824323cebd2de21b7eb2f83a882436b8ce91f3
44,635
import unicodedata import re def slugify(value): """ Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace. """ value = ( unicodedata.normalize('NFKD', value) .encode('ascii...
0b2ca40d1595d079f0b85cebc250264866cf1b39
44,636
def hexpass(pwd): """Convert no alpha numeric characters in a password string to hexadecimal Args: pwd(str): The password as a string Returns: The converted string Examples >>> print(hexpass('matter')) 'matter' >>> print(hexpass('m@tt3r')) "m%40tt3r' """ ...
07e91b8d2b3890ac3594235c74c420f5b1164118
44,637
def get_best_align_elem(tensor_size, tensor_dtype): """Get the best tiling factor for alignment axis.""" basic_align_elem = int(ct_util.BLOCK_SIZE / get_bytes(tensor_dtype)) lcm = least_common_multiple(tensor_size, basic_align_elem) gcd = greatest_common_divisor(tensor_size, basic_align_elem) if gcd...
5b545bf8ca59053b046031deddab2681075d0f66
44,638
import os import yaml def backend_from_string(backendstring, backendopts=None): """ creates (a)sync backends from strings returns tuple (boolean,backend) where boolean specifies whether this is a syncbackend (True) or asyncbackend (False) """ backendopts = backendopts or {} ctor_kwargs...
062f7e88beeafb2981284de18329cce7795bdebc
44,639
import urllib import json def callAPI(verb, endpoint, body="", quiet=False): """ General purpose function for all API calls. Parameters: verb standard hypertext: GET POST etc endpoint substring to be added to base URL body the payload containing a list of dictionary objects. ...
734aa8b70fc604e87ec2ad7c8fc420160d27ddb1
44,640
import os def addFreqWeightsToCatalog(imageDict, photFilter, diagnosticsDir): """Add relative weighting by frequency for each object in the optimal catalog, extracted from the data cube saved under diagnosticsDir (this is made by makeSZMap in RealSpaceMatchedFilter). This is needed for multi-frequency cl...
e647af951de3be5d8003945e0fe477493e491653
44,641
def new_spline(Tend, n_parts, targetvalues, tag, bv=None, use_std_approach=True): """ :param Tend: :param n_parts: :param targetvalues: pair of arrays or callable :param tag: :param bv: None or dict of boundary values (like {0: [0, 7], 1: [0, 0]}) :return: Spli...
6d4bc880802c7f093bf7dfb57d0b510190f305f4
44,642
from operator import concat def sample_and_group(npoint, nsample, xyz, points, density_scale = None): """ Input: npoint: nsample: xyz: input points position data, [B, N, C] points: input points data, [B, N, D] Return: new_xyz: sampled points position data, [B, 1, C]...
bb49ddba21180c14826668abbdcea78ae4f046f7
44,643
def main(corpus, allrules, names, maxrules, iteration, options, display): """ Produces lists of grams, from monograms up to k-grams. Duplicate found in /scripts/readnames.py Example use to get monograms, birgams, and trigrams: getKgrams(getPNs(), 3) Args: corpus (set) = set of all tokens...
10f2b5533a23ca1d5401d647fe59909581f749bd
44,644
def bin2hex(binary): """ Converts Binary to HExaDEcimal""" binary_split1 = (binary[0:4]) binary_split2 = (binary[4:8]) hex1 = b[binary_split1] hex2 = b[binary_split2] return str(hex1) + str(hex2)
078bd13a5c9e014f96321d5f9bfd3469f31f4b41
44,645
def derive_along_path(path, seed): """Derive an extended key from a 64-byte binary seed and a BIP-0044 path. Returns the extended key obtained by following the given derivation path, starting at the extended master key derived from the given binary seed. """ elements = list(element.rstrip("'") for...
44eab8ba7868f178b32c339bb0e341cb03588e4f
44,646
def _convert_to_float(score): """ Convert a string ('score') to float. If the string is empty, return None. If the string is float-like, return its float. """ if len(score) == 0: return None else: return float(score)
48cbc42310595d5a6ae8d8296feb7d81e61d52dc
44,647
import click import functools def ensure_host_configured(f): """Ensure that this configuration has been set up.""" @click.pass_obj @functools.wraps(f) def _wrapper(cfg, *args, **kwargs): if cfg.get('remote.ssh.host', '*') == '*': click.echo(f"{click.style('ERROR', fg='red')}: No c...
f44ec26db18a3a228620b9e3319529ff728c9cfa
44,648
def _next_good_prime(p, R, qq, patience, qqold): """ Find the next prime `\\ell` which is good by ``qq`` but not by ``qqold``, 1 mod ``p``, and for which ``b^2+4*c`` is a square mod `\\ell`, for the sequence ``R`` if it is possible in runtime patience. INPUT: - ``p`` -- a prime - ``R`` -- an...
cfb3701cff0d4a6dcbe53ed34bb5e2f02504819f
44,649
def Satellite_Simulator( Satellite_skyfield, SimulationTime, Timeline_settings, pointing_altitude, LogFlag=False, Logger=None, ): """Simulates a single point in time for a Satellite using Skyfield and also the pointing of the satellite. Only estimates the actual pointing definition used...
7e34704186bd4236f787dbe2229404e686b8d5b3
44,650
def leapyear(year): """Judge year is leap year or not.""" return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
afd3239d8616e2439fd551506f37cd5a93f00bd8
44,651
def correlate_clines(x1,x2,y1,y2,penalty): """use dynamic time warping to correlate centerlines inputs: x1, y1 - coordinates of first centerline x2, y2 - coordinates of second centerline penalty - parameter that forces more parallel correlation (or not) outputs: p - indices of correlation in...
7a7b64d6775e2a8efe3752edbc04055a761dcdfb
44,652
from typing import List from typing import OrderedDict def _serialize_params(params: List[ParamsDependency]): """Return two types of values from stage: `keys` - which is list of params without values, used in a pipeline file which is in the shape of: ['lr', 'train', {'params2.yaml': ['lr']}] ...
018c569b462a1aad2276e4d57df09f83483e569f
44,653
def evolve_profile(diff_matrix, x_points, dc_init, exp_norm_profiles=None, plot=True, return_data=False, labels=None): """ Theoretical diffusion profile, given the diffusion matrix. Parameters ---------- diff_matrix : tuple diffusion matrix, tuple of (eigenvalues, eigenv...
35550b0980430fa9d3e96bc7203591de82663663
44,654
def evaluate(model, inputs, **kwargs): """Performs model rollouts and create stats.""" initial_state = {k: v[0] for k, v in inputs.items()} num_steps = inputs['cells'].shape[0] prediction = _rollout(model, initial_state, num_steps) error = tf.reduce_mean((prediction - inputs['velocity'])**2, axis=-1) scala...
9d5a981ef28c9f9e724787049c5934dbb0c5876f
44,655
def add_stereo_from_geometries(rxn, rct_geos, prd_geos): """ Add stereo assignments to this reaction object from geometries. :param rxn: a reaction object :type rxn: Reaction :param rct_geos: the reactant geometries :param prd_geos: the product geometries :returns: a reaction object with stereo...
0766b6a5ba80bafae9c2ac9f19d6491e15810f5a
44,656
def determine_suitable_lda(displace_elev, margin): """Given a displacement elevation and safety marign, determine the minimum acceptable LDA settings.""" return displace_elev * margin
6db43c125ee98bfefe91f9d44c601dcacdf7aff3
44,657
def current_client_year(): """ gets the current year based on client timezone. this is a helper method to let get the client year without providing value to `current_year` method. :rtype: int """ return get_component(DateTimePackage.COMPONENT_NAME).current_client_year()
108805b978ab30b91ff5b3ffe9b540219726e3c9
44,658
def einsum(x1, x3): """paddle.einsum only support in dynamic graph mode. x1 : n c u v x2 : n c t v """ n, c, u, v1 = x1.shape n, c, t, v3 = x3.shape assert (v1 == v3), "Args of einsum not match!" x1 = paddle.transpose(x1, perm=[0, 1, 3, 2]) # n c v u y = paddle.matmul(x3, x1) # ...
fd9d7544376aa84e26de898eb5e91b02f8b30280
44,659
def format_raw_object(raw_object, internal_dict): """Format a RawObject.""" raw = raw_object.GetChildMemberWithName("raw_").GetValueAsUnsigned() # SmallInt if raw & 0x1 == 0: return str(raw_object.GetChildMemberWithName("raw_").GetValueAsSigned() >> 1) low_tag = (raw >> 1) & 0x3 if low_...
141908858f5de01277a94db22e4e6b53d34bfd0c
44,660
def constructfullKMap(tmap, kmap): """construct a complete k-map from the complete t-map and mapping between t-vals and k-vals""" newarr = tmap.copy() for t, k in enumerate(kmap): newarr[tmap==t] = k return newarr
d034522b00facc29cd9218f50a5f22ed1963c24c
44,661
def get_format_from_name(name: str) -> str: """ Function to infer the input format. Used when the input format is auto. """ try: int(name) src_format = "numeric" except ValueError: if len(name) == 2: src_format = "alpha-2" elif len(name) == 3: ...
ca5baa8790837002261bab68f3989f57fa2943af
44,662
def get_linexp_from_variables(variables): """ Return a linear expression from the supplied list of variables. """ linexp = gp.LinExpr() for v in variables: linexp += v return linexp
f20d845544fcaac541346f45b58e63129be9df0a
44,663
def get_landing_from_url(path): """ determine whether a URL is a landing page. This should always return boolean, not search result. """ if LANDING_RE.search(path): return True else: return False
1cc5ce37d57c0b0c36b3bb33b6e39dbdbc363b8a
44,664
def svn_diff_fns_invoke_datasource_close(*args): """svn_diff_fns_invoke_datasource_close(svn_diff_fns_t _obj, void diff_baton, svn_diff_datasource_e datasource) -> svn_error_t""" return _diff.svn_diff_fns_invoke_datasource_close(*args)
f4ef81415ee0879fe454ee2d6e47e27fb95f74bf
44,665
async def set_turn(pnum): """Set turn manually.""" try: player_num = int(pnum) except ValueError: return jsonify({"status": "error", "error": "invalid player id"}) if player_num < 0 or player_num > 3: return jsonify({"status": "error", "error": "invalid player id"}) try: ...
c0648676e79ac6fee4a7540b0ef56a76cd275fb0
44,666
from typing import List def _help(session: "DebugSession") -> List: """ Display command help for both general and connection-specific commands :param session: Current DebugSession """ # Construct a help table for standard shell commands outputs = [ _create_help_table( first_c...
15a9e65c2675ccb9bf1dae3d6e1812d6687517c7
44,667
def do_mixup(x, mixup_lambda): """Mixup x of even indexes (0, 2, 4, ...) with x of odd indexes (1, 3, 5, ...). Args: x: (batch_size * 2, ...) mixup_lambda: (batch_size * 2,) Returns: out: (batch_size, ...) """ out = (x[0 :: 2].transpose(0, -1) * mixup_lambda[0 :: 2] + \ ...
7642f9825c87487d6f80de8d5be9f7e6be98df9b
44,668
def get_function_inputs(f): """ Given function signatures gets the name of the function. :param f: a callable function :return: input names on a tuple. """ if hasattr(f, cts.INTERNAL_PARAMETERS): # 'internal_parameters' is defined inside the solver() annotation, see solver.py for details...
bcd96b4de330d6277a4fb31ee6420a4fb60bd34a
44,669
def recursive_dict_evaluate(d): """ Recursively run :func:`eval` on each element of the provided dictionary. A raw read of a configuration file with `ConfigObj` results in a dictionary that contains strings or lists of strings. However, when assigning the values for the various ParSets, the `f...
c5eb463aaa95d2bcfd37d71d5e1f5e091331bfd6
44,670
def firmware_version(ip_address): """ Returns the firmware version """ return str(snmp_get(FIRMWARE_VERSION_OID, ip_address))
b16b11e3606da1fbe6475c7c3e66c146a04481fe
44,671
def adjugate(matrix : Matrix) -> float: """It transposes a given Matrix,""" array = [item[:] for item in matrix.rawMatrix()] arrays = [[] for item in matrix.collsAll()] for row in array: i = 0 for num in row: arrays[i].append(num) i+=1 return Matrix(arrays)
6d7438420abe9a5d85d45db7440f6169e4cfdccf
44,672
import string def shorten(message): """Convert message into a shorter form""" if message == 'On time': return '0' number = message.translate(None, string.ascii_letters).strip() sign = '+' if 'late' in message else '-' return '{}{}'.format(sign, number)
3fc8392e9ec61fa46fd9db6ed69ee4ac62a5f4b0
44,673
def index(): """Serve index page.""" default_application_json = post('test', 'group/project', {}) rendered = flask.render_template('index.html.j2', application_json=default_application_json) return rendered
7b37cbb72d242d386a53986f6b25ab39cea0e238
44,674
def get_ground_truth(data, keypoints, warped_keypoints, shape, correctness_thresh, inv): """ Compute the ground truth keypoints matchings from image to image' where image' in the result of warping image with H_matrix. """ #keypoints = np.stack([keypoints[0], keypoints[1]], axis=-1) # Warp the ...
d1f93ad572ffd0177e689473c70ab3e1d9e05107
44,675
def bsonjs_dump(doc, file, mode=bsonjs.LEGACY): """Provide same API as json_util.dumps""" return bsonjs.dump(to_bson(doc), file, mode=mode)
cd1116b91d6f6d01b207b848b094c880df86392e
44,676
def get_create_table_field_data(field_data): """ Generates the field wise query segments needed to create a table. :param field_data: List of dicts with each dict having keys 'name', 'type' and, optionally, 'modifiers' :return: none """ field_query_list = [] for field in field_data: ...
92ef0a4c60d54212e90cc3ac110964565bbfd1be
44,677
import os import json import time def load_cached_creds(bless_config): """ Load cached AWS credentials for the user that has recently MFA'ed Args: bless_config (BlessConfig): Loaded BlessConfig Return: dict of AWS credentials, or {} if no current credentials are found """ client_co...
10a4e0a281e722f368a95c03c342016b4bd8a5b1
44,678
def hough_lines(img, ρ, θ, threshold, min_line_len, max_line_gap): """ `img` should be the output of a Canny transform. Returns the hough lines. """ lines = cv2.HoughLinesP(img, ρ, θ, threshold, np.array([]), minLineLength=min_line_len, maxLineGap=max_line_gap) return lines
0fb36b815ba9edd98822362a9b458cbcbf29f6a7
44,679
def url2pathname(pathname): """OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.""" tp = urllib.splittype(pathname)[0] if tp and tp != 'file': raise RuntimeError, 'Cannot convert non-local URL to pathname' if pathname[:3] ...
1a948f456ce94769ac8f98a94322270d56855357
44,680
def _shellquote(s): """Return a shell-escaped version of the string *s*. Args: s (str): String to shell quote. Returns: str: The shell-quoted string. """ if not s: return "''" if _find_unsafe(s) is None: return s # use single quotes, and put single quotes...
68e8c6dfa846a887591d6eeea55052e436429acd
44,681
def cancel_order(order_id): """method to get and edit an order by the user""" if request.method == "PUT": data = request.get_json() response = validate_parcel_data(data) if response == "valid": sender_name = data['sender_name'] descr = data['descr'] se...
9d61dc7cfe4e308a642a4b13ebfb3d586112245b
44,682
def determine_timestamp(item): """Determine the timestamp of the given item Args: item: [dict] Specifies an resource instance created by an API """ # There is no standard for this. # The following are common to some APIs. for key in ['creationTimestamp', 'timeCreated']: if key in item: return i...
e590b8e2efa9a791b96ba64d1bd73601ba34d317
44,683
def EmptyActivation(): """EmptyActivation() object""" return Activation(handle=_interpreter.interpreter_EmptyActivation())
5be18f1815c577e3efe6c624a6078114f3827698
44,684
def checkbox_to_boolean(list_checkbox_params, dict_all_params): """ Takes a list of strings that are to be processed as checkboxes on a post parameter, (checkboxes supply some arbitrary value in a post if they are checked, and no value at all if they are not checked.), and a dict of parameters and their val...
fe57b02ae6593a0426364cba0c2b41f1362d2968
44,685
def distribution_data(history,mutant_id,i,all_types=False): """ generates neighbour data for mutants (or all cells if all_types is True) cells are labelled by their ancestor. all cells with ancestor=mutant_id are type 1, all other cells type 0. returns list of dicts with keys: tissueid, time, n, k, ...
31f8b07108a6283713277f8ecf90df14c2f0e003
44,686
def likes(names): """Take string of names and let you know who likes 'it'.""" if len(names) == 0: return "no one likes this" elif len(names) == 1: return "{} likes this".format(names[0]) elif len(names) > 3: return "{}, {} and {} others like this".format(names[0], names[1], ...
0d4f3d4275b2d92c503228fc6002ce0ae01acb6a
44,687
def vmkernel_adapter_absent( name, datacenter_name=None, cluster_name=None, host_name=None, service_instance=None ): """ Ensure VMKernel Adapter exists on matching ESXi hosts. name The name of the VMKernel interface to update. (required). datacenter_name Filter by this datacenter n...
32c38a10cc7c2ad88a3bff766b6cfcaea540d568
44,688
def josa_en(word): """add josa either '은' or '는' at the end of this word""" word = word.strip() if not is_hangul(word): raise NotHangulException('') last_letter = word[-1] josa = u'은' if has_jongsung(last_letter) else u'는' return word + josa
6831b3bf62b8162a31712fc88d19a73632094ff0
44,689
import yaml def get_runtime_env(yml_filename): """Reads input YAML filename and returns a dictionary in which each key is a category name of runtime environment and the corresponding value is an object that includes version information of packages listed in that category. """ runtime_env = di...
b9f060605d84aeff799a3abad1601dae1f2b89b5
44,690
def matrix_power(M, n): """ Raise a square matrix to the (integer) power n. Parameters ---------- M : Tensor variable n : Python int """ result = 1 for i in xrange(n): result = theano.dot(result, M) return result
7f998b3613160371be79a57753311a236ab7b3ff
44,691
import torch def camera_rays(camK, W=None, H=None, c2w=None, graphics_coordinate=True, center=False): """shoot viewing rays from camera parameters. Args: camK: Tensor of shape `[3,3]`, the intrinsic matrix. W: Integer, if set None, then `W` is calculated as `2*cx`. H: I...
c572283305dccc243de1bd956d11b7fd2ff42726
44,692
def basic_project_data(): """ Provide a basic collection of Sample-independent data. :return dict[str, object]: Mapping from Project section name to value or collection of values. """ return { METADATA_KEY: { NAME_TABLE_ATTR: "anns.csv", OUTDIR_KEY: "outdir",...
2988e94efe4e210ca7fe12f094077c8f72c0a61a
44,693
def get_data(filename, args): """ @ input filename: ex. kr00001973962b1p-4 @ output image, coordinates, labels """ xmlfile = filename jpgfile = filename.replace(".xml",".jpg") doc = ET.parse(xmlfile) root = doc.getroot() object_dict = {} for x in root.findall('...
8f6d4488b60e559ccae579cf6baf1c9f75d3907e
44,694
import re def photos(context, group): """ Render one or more photos defined in the spreadsheet. """ photoset = [photo for photo in context['COPY']['photos'] if photo['group'] == group] whitespace_regex = re.compile(r'\s+') # Remove whitespace for Markdown embedding fragments = [] for row i...
22f792ece3a44e6643a50e4465c81de9f07b6971
44,695
import subprocess def run_command(cmd,input_dir): """ Another git convienience function, this time just running an arbitrary command in an arbitrary location and waiting until quit. """ p = subprocess.Popen(cmd, cwd=input_dir,stdout=subprocess.PIPE) out, err = p.communicate() return out
bb5cba884fc38b7c2d1dfc8407a57ca0c21ed62d
44,696
import os def makepath(subsystem, group, pseudofile=None): """Pieces together a full path of the cgroup""" mountpoint = get_mountpoint(subsystem) group = group.strip('/') if pseudofile: return os.path.join(mountpoint, group, pseudofile) return os.path.join(mountpoint, group)
9c4809e78038fa1472f11831563c5241046042b8
44,697
def sky_noise_jy_autos(lsts, freqs, autovis, omega_p, integration_time, channel_width=None, Trx=0.0): """Make a noise realization for a given auto-visibility level and beam. This is a simple replacement for ``hera_sim.noise.sky_noise_jy``. Parameters ---------- lsts : array_like LSTs at wh...
dd00615de1a63cea9c30960f77c01082cd957f07
44,698
def shortestDist(S1, S2): """Returns the distance between the time series S1 and S2. S1 and S2 have size N x ... x 3 Assumes linear interpolation between points but no assumption about the velocity between grid points (hence the shortest distance is between segments is returned) return array of size...
c330af8b03661523174a5a310d49a2642af2a95f
44,699