content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
def get_time(sec_scale):
"""time since epoch in milisecond
"""
if sec_scale == 'sec':
scale = 0
elif sec_scale == 'msec':
scale = 3
else:
raise
secs = (datetime.utcnow() - datetime.utcfromtimestamp(0)).total_seconds()
return int(secs *... | c233133d61c6347a27186ef3baf0ae2bc79cf8f2 | 15,500 |
import urllib
import json
def get_json(url):
"""
Function that retrieves a json from a given url.
:return: the json that was received
"""
with urllib.request.urlopen(url) as response:
data = response.readall().decode('utf-8')
data = json.loads(data)
return data | 3164bb7d1adc40e3dcd07e82ec734807f3a17abc | 15,501 |
def _defaultChangeProvider(variables,wf):
""" by default we just forword the message to the change provider """
return variables | 5087dc06e0da1f3270b28e9ab1bd2241ed4b4de4 | 15,502 |
def evaluate_surface_derivatives(surface, params, order=1):
"""
"""
if surface.rational:
control_points = np.array(surface.weighted_control_points)
else:
control_points = np.array(surface.control_points)
degree_u, degree_v = surface.degree
knot_vector_u, knot_vector_v = surface.... | 669a20bf23f96720f2a2eae917652723c0aa3fe5 | 15,503 |
def GPPrediction(y_train, X_train, T_train, eqid_train, sid_train = None, lid_train = None,
X_new = None, T_new = None, eqid_new = None, sid_new = None, lid_new = None,
dc_0 = 0.,
Tid_list = None, Hyp_list = None, phi_0 = None, tau_0 = None,... | 28bdf5575f16d1ee3a719aaadc59eefda642171d | 15,504 |
def zdotu(x, y):
"""
This function computes the complex scalar product \M{x^T y} for the
vectors x and y, returning the result.
"""
return _gslwrap.gsl_blas_zdotu(x, y, 1j) | 135b5196568454dc0c721ab42cdd13d4bed63c5c | 15,505 |
def music21_to_chord_duration(p, key):
"""
Takes in a Music21 score, and outputs three lists
List for chords (by primeFormString string name)
List for chord function (by romanNumeralFromChord .romanNumeral)
List for durations
"""
p_chords = p.chordify()
p_chords_o = p_chords.flat.getElem... | 142a0ef06c5c9542097cc7db0631a1f19e2f8f72 | 15,506 |
def city_country(city, country, population=''):
"""Generate a neatly formatted city/country name."""
full_name = city + ', ' + country
if population:
return full_name.title() + ' - population ' + str(population)
else:
return full_name.title() | 23be8d5b39380fd177240e479cf77ac7eb6c7459 | 15,507 |
def generate_headermap(line,startswith="Chr", sep="\t"):
"""
>>> line = "Chr\\tStart\\tEnd\\tRef\\tAlt\\tFunc.refGene\\tGene.refGene\\tGeneDetail.refGene\\tExonicFunc.refGene\\tAAChange.refGene\\tsnp138\\tsnp138NonFlagged\\tesp6500siv2_ea\\tcosmic70\\tclinvar_20150629\\tOtherinfo"
>>> generate_heade... | 16bbbc07fa13ff9bc8ec7af1aafc4ed65b20ec4c | 15,508 |
def max(q):
"""Return the maximum of an array or maximum along an axis.
Parameters
----------
q : array_like
Input data
Returns
-------
array_like
Maximum of an array or maximum along an axis
"""
if isphysicalquantity(q):
return q.__class__(np.max(q.value), ... | 0a3cfae6fb9d1d26913817fcc11765214baa8dff | 15,509 |
from typing import OrderedDict
def make_failure_log(conclusion_pred, premise_preds, conclusion, premises,
coq_output_lines=None):
"""
Produces a dictionary with the following structure:
{"unproved sub-goal" : "sub-goal_predicate",
"matching premises" : ["premise1", "premise2", ..... | 17f7cb8b6867849e034d72f05e9e48622bd35b7d | 15,510 |
import requests
def request(url=None, json=None, parser=lambda x: x, encoding=None, **kwargs):
"""
:param url:
:param json:
:param parser: None 的时候返回r,否则返回 parser(r.json())
:param kwargs:
:return:
"""
method = 'post' if json is not None else 'get' # 特殊情况除外
logger.info(f"Request M... | c222cc2a5c1e2acb457600d223c9ca6ab588aa5e | 15,511 |
import math
def log_density_igaussian(z, z_var):
"""Calculate log density of zero-mean isotropic gaussian distribution given z and z_var."""
assert z.ndimension() == 2
assert z_var > 0
z_dim = z.size(1)
return -(z_dim/2)*math.log(2*math.pi*z_var) + z.pow(2).sum(1).div(-2*z_var) | a412b9e25aecfc2baed2d783a2d7cd281fadc9fb | 15,512 |
def denom(r,E,J,model):
"""solve the denominator"""
ur = model.potcurve(r)#model.potcurve[ (abs(r-model.rcurve)).argmin()]
return 2.0*(E-ur)*r*r - J*J; | 19dc7c5cd283b66f834ba9a0d84fb396ca2c2c89 | 15,513 |
def approximate_gaussians(confidence_array, mean_array, variance_array):
""" Approximate gaussians with given parameters with one gaussian.
Approximation is performed via minimization of Kullback-Leibler
divergence KL(sum_{j} w_j N_{mu_j, sigma_j} || N_{mu, sigma}).
Parameters
----------
confi... | 7c722f0153e46631b3c4731d8a307e0b219be02b | 15,514 |
from typing import Callable
import types
def return_loss(apply_fn: Callable[[jnp.ndarray, jnp.ndarray], jnp.ndarray],
steps: types.Transition):
"""Loss wrapper for ReturnMapper.
Args:
apply_fn: applies a transition model (o_t, a_t) -> (o_t+1, r), expects the
leading axis to index the ba... | 970cb6623436982ef1359b1328edcb828012f1f7 | 15,515 |
def part_two(data):
"""Part two"""
array = ['a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
commands = data.split(',')
for _ in range(1000000000 % 30):
dance(array, commands)
return ''.join(map(str, array)) | 75e847cd5a598aa67ca54133c15a0c2c3fc67433 | 15,516 |
import os
import json
import requests
def ts_declare():
"""Makes an f5-telemetry-streaming declaration from the supplied metadata"""
if is_rest_worker('/mgmt/shared/telemetry/declare') and os.path.isfile(
TS_DECLARATION_FILE):
tsdf = open(TS_DECLARATION_FILE, 'r')
declaration = tsd... | ea52512201450ed35ba7a902edf15bbe12b748de | 15,517 |
def readCSVPremadeGroups(filename, studentProperties=None):
"""studentProperties is a list of student properties in the order they appear in the CSV.
For example, if a CSV row (each group is a row) is as follows: "Rowan Wilson, rowan@harvard.edu, 1579348, Bob Tilano, bob@harvard.edu, 57387294"
Then the format is:... | f12de287b4a9f19e2e29302338f7233e34d54f0c | 15,518 |
def random_contrast(video, lower, upper, seed=None):
"""Adjust the contrast of an image or images by a random factor.
Equivalent to `adjust_contrast()` but uses a `contrast_factor` randomly
picked in the interval `[lower, upper)`.
For producing deterministic results given a `seed` value, use
`tf.i... | 6ea6a72100ad468d7692c0bb8c2837cba5eaa3e0 | 15,519 |
from typing import Dict
def load(df: DataFrame, config: Dict, logger) -> bool:
"""Write data in final destination
:param df: DataFrame to save.
:type df: DataFrame
:param config: job configuration
:type config: Dict
:param logger: Py4j Logger
:type logger: Py4j.Logger
:return: True
... | 70f962cc24f23264f23dce458c233466dc06d276 | 15,520 |
def phase_correct_zero(spec, phi):
"""
Correct the phases of a spectrum by phi radians
Parameters
----------
spec : float array of complex dtype
The spectrum to be corrected.
phi : float
Returns
-------
spec : float array
The phase corrected spectrum
... | 1647e8f99e10ba5f715e4c268907cbf995e99335 | 15,521 |
def upsample(s, n, phase=0):
"""Increase sampling rate by integer factor n with included offset phase.
"""
return np.roll(np.kron(s, np.r_[1, np.zeros(n-1)]), phase) | 997f48be57816efb11b77c258e945d3161b748be | 15,522 |
def parse_idx_inp(idx_str):
""" parse idx string
"""
idx_str = idx_str.strip()
if idx_str.isdigit():
idxs = [int(idx_str)]
if '-' in idx_str:
[idx_begin, idx_end] = idx_str.split('-')
idxs = list(range(int(idx_begin), int(idx_end)+1))
return idxs | 2dc1282169f7534455f2a0297af6c3079192cb66 | 15,523 |
import requests
def toggl_request_get(url: str, params: dict = False) -> requests.Response:
"""Send a GET request to specified url using toggl headers and configured auth"""
headers = {"Content-Type": "application/json"}
auth = (CONFIG["toggl"]["api_token"], "api_token")
response = requests.get(url, h... | bd4714bb0d92dcfb1e2ef27bb3fa3c67179b8b40 | 15,524 |
def sample_point_cloud(source, target, sample_indices=[2]):
""" Resamples a source point cloud at the coordinates of a target points
Uses the nearest point in the target point cloud to the source point
Parameters
----------
source: array
Input point cloud
target: array... | b490e598e68ef175a5cf80c052f2f82fc70ac4ba | 15,525 |
def make_satellite_gsp_pv_map(batch: Batch, example_index: int, satellite_channel_index: int):
"""Make a animation of the satellite, gsp and the pv data"""
trace_times = []
times = batch.satellite.time[example_index]
pv = batch.pv
for time in times:
trace_times.append(
make_sate... | fd0e0a7543da212f368849c3686277a7c8c42a95 | 15,526 |
def raw_to_engineering_product(product, idbm):
"""Apply parameter raw to engineering conversion for the entire product.
Parameters
----------
product : `BaseProduct`
The TM product as level 0
Returns
-------
`int`
How many columns where calibrated.
"""
col_n = 0
... | aaf5a92c53bfc41a5230593b96c0de7b8ad1ba4a | 15,527 |
def paginate(objects, page_num, per_page, max_paging_links):
"""
Return a paginated page for the given objects, giving it a custom
``visible_page_range`` attribute calculated from ``max_paging_links``.
"""
paginator = Paginator(objects, per_page)
try:
page_num = int(page_num)
except ... | cd8a7ef046a48c580ad12cfa44f1862312bb1aba | 15,528 |
def _get_crop_frame(image, max_wiggle, tx, ty):
"""
Based on on the max_wiggle, determines a cropping frame.
"""
pic_width, pic_height = image.size
wiggle_room_x = max_wiggle * .5 * pic_width
wiggle_room_y = max_wiggle * .5 * pic_height
cropped_width = pic_width - wiggle_room_x
cropped_h... | 18442a97544d6c4bc4116dc43811c9fcd0d203c6 | 15,529 |
from re import U
def __vigenere(s, key='virink', de=0):
"""维吉利亚密码"""
s = str(s).replace(" ", "").upper()
key = str(key).replace(" ", "").upper()
res = ''
i = 0
while i < len(s):
j = i % len(key)
k = U.index(key[j])
m = U.index(s[i])
if de:
if m < k:
... | 4deadfc9fdd1cb002c2f31a1de7763b0c49dd757 | 15,530 |
def mask_unit_group(unit_group: tf.Tensor, unit_group_length: tf.Tensor, mask_value=0) -> tf.Tensor:
""" Masks unit groups according to their length.
Args:
unit_group: A tensor of rank 3 with a sequence of unit feature vectors.
unit_group_length: The length of the unit group (assumes all unit f... | 758028075f793bad1165d0ca8992c78cb4a1318e | 15,531 |
def fill_session_team(team_id, session_id, dbsession=DBSESSION):
"""
Use the FPL API to get list of players in an FPL squad with id=team_id,
then fill the session team with these players.
"""
# first reset the team
reset_session_team(session_id, dbsession)
# now query the API
players = f... | 28118a527c009d90401b368d628725ee29e838ef | 15,532 |
def create_map(users_info):
"""
This function builds an HTML map with locations of user's friends on
Twitter.
"""
my_map = folium.Map(
location=[49.818396058511645, 24.02258071000576], zoom_start=10)
folium.TileLayer('cartodbdark_matter').add_to(my_map)
folium.TileLayer('stamentoner'... | cfe9649101906aa295ffc9984bbed15a99c7ed46 | 15,533 |
def l2sq(x):
"""Sum the matrix elements squared
"""
return (x**2).sum() | c02ea548128dde02e4c3e70f9280f1ded539cee9 | 15,534 |
def normalize(arr, axis=None):
"""
Normalize a vector between 0 and 1.
Parameters
----------
arr : numpy.ndarray
Input array
axis : integer
Axis along which normalization is computed
Returns
-------
arr : numpy.ndarray
Normalized version of the input array
... | 2c9689ee829e66bfd02db3c1c92c749ca068bd73 | 15,535 |
def successive_substitution(m, T, P, max_iter, M, Pc, Tc, omega, delta, Aij,
Bij, delta_groups, calc_delta, K, steps=0):
"""
Find K-factors by successive substitution
Iterate to find a converged set of K-factors defining the gas/liquid
partitioning of a mixture using su... | 1ad40642f940be0d1e967bf97a62e3b754312ae9 | 15,536 |
import re
def Match(context, pattern, arg=None):
"""Do a regular expression match against the argument"""
if not arg:
arg = context.node
arg = Conversions.StringValue(arg)
bool = re.match(pattern, arg) and boolean.true or boolean.false
return bool | 62007fcd4617b0dfebb1bc8857f89fa2e6075f41 | 15,537 |
def rr_rectangle(rbins, a, b):
""" RR_rect(r; a, b) """
return Frr_rectangle(rbins[1:], a, b) - Frr_rectangle(rbins[:-1], a, b) | 98e30791e114ce3e2f6529db92c0103d1477cd76 | 15,538 |
def update_type(title, title_new=None, description=None, col_titles_new={}):
"""Method creates data type
Args:
title (str): current type title
title_new (str): new type title
description (str): type description
col_titles_new (dict): new column values (key - col id, value - col valu... | 92e663d3bfd798de0367a44c4909a330ac9e4254 | 15,539 |
def api(repos_path):
"""Glottolog instance from shared directory for read-only tests."""
return pyglottolog.Glottolog(str(repos_path)) | a941a907050300bc89f6db8b4bd33cf9725cf832 | 15,540 |
from presqt.targets.osf.utilities.utils.async_functions import run_urls_async
import requests
def get_all_paginated_data(url, token):
"""
Get all data for the requesting user.
Parameters
----------
url : str
URL to the current data to get
token: str
User's OSF token
Retu... | cca997d479c63415b519de9cbd8ac2681abc42ed | 15,541 |
def alaw_decode(x_a, quantization_channels, input_int=True, A=87.6):
"""alaw_decode(x_a, quantization_channels, input_int=True)
input
-----
x_a: np.array, mu-law waveform
quantization_channels: int, Number of channels
input_int: Bool
True: convert x_mu (int) from int to float, bef... | a2e10eb590d5b7731227b96233c6b615c11d4af6 | 15,542 |
import os
def incoming(ui, repo, source="default", **opts):
"""show new changesets found in source
Show new changesets found in the specified path/URL or the default
pull location. These are the changesets that would have been pulled
if a pull at the time you issued this command.
For remote repo... | 2bc3d3d8b97d54b4f33dd70ae4ad54fb0c3e1792 | 15,543 |
def _ec_2d(X):
"""Function for computing the empirical Euler characteristic of a given
thresholded data array.
Input arguments:
================
Y : ndarray of floats
The thresholded image. Ones correspond to activated regions.
Output arguments:
=================
ec : float
... | ac71056a73131a8fa7ee7bc372d72c1678f028bc | 15,544 |
import dateutil
def swap_year_for_time(df, inplace):
"""Internal implementation to swap 'year' domain to 'time' (as datetime)"""
if not df.time_col == "year":
raise ValueError("Time domain must be 'year' to use this method")
ret = df.copy() if not inplace else df
index = ret._data.index
... | 790e8d24e6c4d87413dfc5d6205cbb04f7acefd6 | 15,545 |
from typing import Optional
from typing import List
def get_orders(
db: Session,
skip: int = 0,
limit: int = 50,
moderator: str = None,
owner: str = None,
desc: bool = True,
) -> Optional[List[entities.Order]]:
"""
Get the registed orders using filters.
Args:
- db: the dat... | a5c86ccaad8573bc641f531751370c264baa60f8 | 15,546 |
def create_data_loader(img_dir, info_csv_path, batch_size):
"""Returns a data loader for the model."""
img_transform = transforms.Compose([transforms.Resize((120, 120), interpolation=Image.BICUBIC),
transforms.ToTensor()])
img_dataset = FashionDataset(img_dir, img_tra... | 1a7df2b691c66ef5957113d5113353f34bf8c855 | 15,547 |
def comp_number_phase_eq(self):
"""Compute the equivalent number of phase
Parameters
----------
self : LamSquirrelCage
A LamSquirrelCage object
Returns
-------
qb: float
Zs/p
"""
return self.slot.Zs / float(self.winding.p) | f4679cf92dffff138a5a96787244a984a11896f9 | 15,548 |
import sympy
def exprOps(expr):
"""This operation estimation is not handling some simple optimizations that
should be done (i.e. y-x is treated as -1*x+y) and it is overestimating multiplications
in situations such as divisions. This is as a result of the simple method
of implementing this function ... | b6255707ef7475c893d9325358e7666b95c0e7c8 | 15,549 |
def ellipsis_reformat(source: str) -> str:
"""
Move ellipses (``...``) for type stubs onto the end of the stub definition.
Before:
.. code-block:: python
def foo(value: str) -> int:
...
After:
.. code-block:: python
def foo(value: str) -> int: ...
:param source: The source to reformat.
:re... | 162d9d863f7316bee87a04857366a7f78f68d75b | 15,550 |
def build_wtk_filepath(region, year, resolution=None):
"""
A utility for building WIND Toolkit filepaths.
Args:
region (str): region in which the lat/lon point is located (see
`get_regions`)
year (int): year to be accessed (see `get_regions`)
resolution (:obj:`str`, option... | 93da894523a6517faaf4fa4976ba986a3719494c | 15,551 |
import logging
def init_doc(args: dict) -> dict:
""" Initialize documentation variable
:param args: A dictionary containing relevant documentation fields
:return:
"""
doc = {}
try:
doc[ENDPOINT_PORT_KEY] = args[ENDPOINT_PORT_KEY]
except KeyError:
logging.warning("No port fo... | afa20f89595eac45e924ecdb32f9ef169fc72726 | 15,552 |
def decode_entities(string):
""" Decodes HTML entities in the given string ("<" => "<").
"""
# http://snippets.dzone.com/posts/show/4569
def replace_entity(match):
hash, hex, name = match.group(1), match.group(2), match.group(3)
if hash == "#" or name.isdigit():
if hex == ... | 480a7ed8a37b05bc65d10e513e021b00fcb718c4 | 15,553 |
def convert2board(chrom, rows, cols):
"""
Converts the chromosome represented in a list into a 2D numpy array.
:param rows: number of rows associated with the board.
:param cols: number of columns associated with the board.
:param chrom: chromosome to be converted.
:return: 2D numpy array.
"... | 9897965550793f54e55ce2c66c95a7584a987a4e | 15,554 |
def filter_halo_pnum(data, Ncut=1000):
""" Returns indicies of halos with more than Ncut particles"""
npart = np.array(data['np'][0])
ind =np.where(npart > Ncut)[0]
print("# of halos:",len(ind))
return ind | 3c89eb263399ef022c1b5492190aff282e4410e8 | 15,555 |
def _preprocess_sgm(line, is_sgm):
"""Preprocessing to strip tags in SGM files."""
if not is_sgm:
return line
# In SGM files, remove <srcset ...>, <p>, <doc ...> lines.
if line.startswith("<srcset") or line.startswith("</srcset"):
return ""
if line.startswith("<refset") or line.start... | 0a482c5ccf2c001dfd9b52458044a1feaf62e5b9 | 15,556 |
def discover(using, index="*"):
"""
:param using: Elasticsearch client
:param index: Comma-separated list or wildcard expression of index names used to limit the request.
"""
indices = Indices()
for index_name, index_detail in using.indices.get(index=index).items():
indices[index_name] =... | 32a53f15b0db3ba2b2c092e8dbd4ffdf57f133c8 | 15,557 |
from datetime import datetime
def quote_sql_value(cursor: Cursor, value: SQLType) -> str:
"""
Use the SQL `quote()` function to return the quoted version of `value`.
:returns: the quoted value
"""
if isinstance(value, (int, float, datetime)):
return str(value)
if value is None:
... | 17887be2440563a1321708f797310eb8f1731687 | 15,558 |
def create_admin_nova_client(context):
"""
Creates client that uses trove admin credentials
:return: a client for nova for the trove admin
"""
client = create_nova_client(context, password=CONF.nova_proxy_admin_pass)
return client | 3fdd56ae419b5228b209a9e00fb8828c17a0d847 | 15,559 |
def page_cache(timeout=1800):
"""
page cache
param:
timeout:the deadline of cache default is 1800
"""
def _func(func):
def wrap(request, *a, **kw):
key = request.get_full_path()
#pass chinese
try:
key = mkey.encode("utf-8")
except Exception, e:
key = str(key)
data = None
try:
d... | ca5be8d6ad1c1d0e627e2e22dbe44532d20af5cd | 15,560 |
def get_available_games():
"""Get a list of games that are available to join."""
games = Game.objects.filter(started=False) #pylint: disable=no-member
if len(games) == 0:
options = [('', '- None -')]
else:
options = [('', '- Select -')]
for game in games:
options.append((game... | 245d85ce623ffe3ed9eb718aafaf7889c67dada6 | 15,561 |
def _add_rays_single_cam(
camera_data: TensorDict,
*,
scene_from_frame: tf_geometry.Isometry,
) -> TensorDict:
"""Returns the camera, eventually with the rays added."""
if _has_precomputed_rays(camera_data):
return camera_data
else:
# Logic below for generating camera rays only applies to pers... | dc9836d3ebee9ccc3ab940dc3bfe0981f9362741 | 15,562 |
def process_ps_stdout(stdout):
""" Process the stdout of the ps command """
return [i.split()[0] for i in filter(lambda x: x, stdout.decode("utf-8").split("\n")[1:])] | c086cc88c51484abe4308b3ac450faaba978656e | 15,563 |
import shlex
def chpasswd(path, oldpassword, newpassword):
"""Change password of a private key.
"""
if len(newpassword) != 0 and not len(newpassword) > 4: return False
cmd = shlex.split('ssh-keygen -p')
child = pexpect.spawn(cmd[0], cmd[1:])
i = child.expect(['Enter file in which the key is',... | ee84bdccee24ea591db6d9c82bfce8374d1a420d | 15,564 |
def get_display_limits(VarInst, data=None):
"""Get limits to resize the display of Variables.
Function takes as argument a `VariableInstance` from a `Section` or
`Planform` and an optional :obj:`data` argument, which specifies how to
determine the limits to return.
Parameters
----------
Va... | d4864fccd8c282033d99fdc817e077d3f6d5b434 | 15,565 |
def plot_layer_consistency_example(eigval_col, eigvec_col, layernames, layeridx=[0,1,-1], titstr="GAN", figdir="", savelabel="", use_cuda=False):
"""
Note for scatter plot the aspect ratio is set fixed to one.
:param eigval_col:
:param eigvec_col:
:param nsamp:
:param titstr:
:param figdir:
... | 38191663fcf1c9f05aa39127179a3cbf5f29b219 | 15,566 |
def min_vertex_cover(left_v, right_v):
"""
Use the Hopcroft-Karp algorithm to find a maximum
matching or maximum independent set of a bipartite graph.
Next, find a minimum vertex cover by finding the
complement of a maximum independent set.
The function takes as input two dictionaries, one for t... | a94aaf6dd07b98e7f5a77b01ab6548bc401e8b03 | 15,567 |
def neighbor_dist(x1, y1, x2, y2):
"""Return distance of nearest neighbor to x1, y1 in x2, y2"""
m1, m2, d12 = match_xy(x2, y2, x1, y1, neighbors=1)
return d12 | 91b67e571d2812a9bc2e05b25a74fbca292daec7 | 15,568 |
import requests
def add_artist_subscription(auth, userid, artist_mbid):
"""
Add an artist to the list of subscribed artists.
:param tuple auth: authentication data (username, password)
:param str userid: user ID (must match auth data)
:param str artist_mbid: musicbrainz ID of the artist to add
... | 770be84ec9edb272c8c3d8cb1959f419f8867e1d | 15,569 |
from pathlib import Path
import pickle
def get_built_vocab(dataset: str) -> Vocab:
"""load vocab file for `dataset` to get Vocab based on selected client and data in current directory
Args:
dataset (str): string of dataset name to get vocab
Returns:
if there is no built vocab file for `da... | b03daba815ccddb7ff3aee2e2eac39de22ff6cff | 15,570 |
from typing import Optional
from typing import Iterable
def binidx(num: int, width: Optional[int] = None) -> Iterable[int]:
""" Returns the indices of bits with the value `1`.
Parameters
----------
num : int
The number representing the binary state.
width : int, optional
Minimum n... | 70d1895cf0141950d8e2f5efe6bfbf7bd8dbc30b | 15,571 |
import sys
import socket
def hashed_class_mix_score256(cycle_hash: bytes, identifier: bytes, ip: str, ip_bytes: bytearray) -> int:
"""
Nyzo Score computation from hash of IP start + end of last IP byte to effectively reorder the various c-class and their gaps.
Then complete the score with first half lates... | 172663529b625c73ab91147864ce17cd2a4d4108 | 15,572 |
import math
def distance_vinchey(f, a, start, end):
"""
Uses Vincenty formula for distance between two Latitude/Longitude points
(latitude,longitude) tuples, in numeric degrees. f,a are ellipsoidal parameters
Returns the distance (m) between two geographic points on the ellipsoid and... | df5ae92a12af6ab656af65a12145436089202cf2 | 15,573 |
def py_cpu_nms(dets, thresh):
"""Pure Python NMS baseline."""
# x1、y1、x2、y2、以及score赋值
dets = np.array(dets)
x1 = dets[:, 0]
y1 = dets[:, 1]
x2 = dets[:, 2]
y2 = dets[:, 3]
scores = dets[:, 4]
#每一个检测框的面积
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
#按照score置信度降序排序
order = score... | d85822e8076bf1695c6f9e7b7271b21572ebf7d6 | 15,574 |
def _romanize(word: str) -> str:
"""
:param str word: Thai word to be romanized, should have already been tokenized.
:return: Spells out how the Thai word should be pronounced.
"""
if not isinstance(word, str) or not word:
return ""
word = _replace_vowels(_normalize(word))
res = _RE... | 5e464faa1011893eb63f1f9afedd42768a8527c8 | 15,575 |
def lookup_beatmap(beatmaps: list, **lookup):
""" Finds and returns the first beatmap with the lookup specified.
Beatmaps is a list of beatmap dicts and could be used with beatmap_lookup().
Lookup is any key stored in a beatmap from beatmap_lookup().
"""
if not beatmaps:
return None
fo... | fa5f126502b5398934882139f01af8f4f80e1ea5 | 15,576 |
def scott(
x: BinaryFeatureVector, y: BinaryFeatureVector, mask: BinaryFeatureVector = None
) -> float:
"""Scott similarity
Scott, W. A. (1955).
Reliability of content analysis: The case of nominal scale coding.
Public opinion quarterly, 321-325.
Args:
x (BinaryFeatureVector): binary f... | 6b950cb2b716d2e93638b169682cdd99230cbb89 | 15,577 |
import xmlrunner
def get_test_runner():
"""
Returns a test runner instance for unittest.main. This object captures
the test output and saves it as an xml file.
"""
try:
path = get_test_dir()
runner = xmlrunner.XMLTestRunner(output=path)
return runner
except Exception, ... | 6b2db3207c278a7f07ed6fd7922042beea1bfee7 | 15,578 |
def _construct_capsule(geom, pos, rot):
"""Converts a cylinder geometry to a collider."""
radius = float(geom.get('radius'))
length = float(geom.get('length'))
length = length + 2 * radius
return config_pb2.Collider(
capsule=config_pb2.Collider.Capsule(radius=radius, length=length),
rotation=_vec... | a4bddb7c64468515d3a36ebaac22402eeb4f16b0 | 15,579 |
def file_root_dir(tmpdir_factory):
"""Prepares the testing dirs for file tests"""
root_dir = tmpdir_factory.mktemp('complex_file_dir')
for file_path in ['file1.yml',
'arg/name/file2',
'defaults/arg/name/file.yml',
'defaults/arg/name/file2',
... | 834e0d850e7a7dd59d792e98ed25b909d5a20567 | 15,580 |
from typing import Iterable
def path_nucleotide_length(g: BifrostDiGraph, path: Iterable[Kmer]) -> int:
"""Compute the length of a path in nucleotides."""
if not path:
return 0
node_iter = iter(path)
start = next(node_iter)
k = g.graph['k']
length = g.nodes[start]['length'] + k - 1... | 612cff39bcf859a995d90c22e2dacb54e9c0b4c9 | 15,581 |
def extract_static_links(page_content):
"""Deliver the static asset links from a page source."""
soup = bs(page_content, "html.parser")
static_js = [
link.get("src")
for link in soup.findAll("script")
if link.get("src") and "static" in link.get("src")
]
static_images = [
... | 8ea99171d55db182fe4265042c84deca36176d84 | 15,582 |
def zero_inflated_nb(n, p, phi=0, size=None):
"""Models a zero-inflated negative binomial
Something about hte negative binomail model here...
This basically just wraps the numpy negative binomial generator,
where the probability of a zero is additionally inflated by
some probability, psi...
P... | c20f28b33e070e035979093e6ebb9ed10611c5dd | 15,583 |
async def get_bot_queue(
request: Request,
state: enums.BotState = enums.BotState.pending,
verifier: int = None,
worker_session = Depends(worker_session)
):
"""Admin API to get the bot queue"""
db = worker_session.postgres
if verifier:
bots = await db.fetch("SELECT bot_id, prefix,... | bfbd51933b140bfd60cc7ec2a401d02048ffdeae | 15,584 |
def ask_for_rating():
"""Ask the user for a rating"""
heading = '{} {}'.format(common.get_local_string(30019),
common.get_local_string(30022))
try:
return int(xbmcgui.Dialog().numeric(heading=heading, type=0,
defaultt=''))
... | a7a854e02b11ac1313d69f508851d162a7748006 | 15,585 |
def isthai(text,check_all=False):
"""
สำหรับเช็คว่าเป็นตัวอักษรภาษาไทยหรือไม่
isthai(text,check_all=False)
text คือ ข้อความหรือ list ตัวอักษร
check_all สำหรับส่งคืนค่า True หรือ False เช็คทุกตัวอักษร
การส่งคืนค่า
{'thai':% อักษรภาษาไทย,'check_all':tuple โดยจะเป็น (ตัวอักษร,True หรือ False)}
"""
listext=list(t... | 6a6bff64ba3b3939414e9f3aa83d169cd026e1c3 | 15,586 |
from typing import List
from typing import Optional
def _convert_object_array(
content: List[Scalar], dtype: Optional[DtypeObj] = None
) -> List[Scalar]:
"""
Internal function ot convert object array.
Parameters
----------
content: list of processed data records
dtype: np.dtype, default i... | 7b093057b05afa93ced881289d22b1eda91018f0 | 15,587 |
def update_room_time(conn, room_name: str, req_time: int) -> int:
"""部屋のロックを取りタイムスタンプを更新する
トランザクション開始後この関数を呼ぶ前にクエリを投げると、
そのトランザクション中の通常のSELECTクエリが返す結果がロック取得前の
状態になることに注意 (keyword: MVCC, repeatable read).
"""
cur = conn.cursor()
# See page 13 and 17 in https://www.slideshare.net/ichirin2501... | 78066e9666ee28217f790fb8c26d2ade8c2ace7c | 15,588 |
def get_layer_coverage(cat, store, store_obj):
"""Get correct layer coverage from a store."""
coverages = cat.mosaic_coverages(store_obj)
# Find the correct coverage
coverage = None
for cov in coverages["coverages"]["coverage"]:
if store == cov['name']:
coverage = cov
... | 498c4a8db1a82dafd8569314e4faf13517e75aba | 15,589 |
import logging
import time
def retarget(songs, duration, music_labels=None, out_labels=None,
out_penalty=None, volume=None, volume_breakpoints=None,
springs=None, constraints=None,
min_beats=None, max_beats=None,
fade_in_len=3.0, fade_out_len=5.0,
**kwa... | 8ed317392e74545916d1ef33e282bce5c6846009 | 15,590 |
def st_get_ipfs_cache_path(user_did):
"""
Get the root dir of the IPFS cache files.
:param user_did: The user DID
:return: Path: the path of the cache root.
"""
return _st_get_vault_path(user_did) / 'ipfs_cache' | 4217b178025c395619d9def035d11cc96f2b139a | 15,591 |
def create_img_caption_int_data(filepath):
""" function to load captions from text file and convert them to integer
format
:return: dictionary with image ids and associated captions in int format
"""
print("\nLoading caption data : started")
# load caption data
img_caption_dict = load... | 6d1a449c1b5be7759c65740440865c72546514ef | 15,592 |
def eigenvector_2d_symmetric(a, b, d, eig, eps=1e-8):
"""Returns normalized eigenvector corresponding to the provided eigenvalue.
Note that this a special case of a 2x2 symmetric matrix where every element of the matrix is passed as an image.
This allows the evaluation of eigenvalues to be vectorized over ... | 88a97af77e3f3097b6742db340f8e9559fb8164a | 15,593 |
from typing import Optional
def get_protection_path_name(protection: Optional[RouteProtection]) -> str:
"""Get the protection's path name."""
if protection is None:
return DEFAULT_PROTECTION_NAME
return protection | f3abaf21c9ba3cfe6c0ae793afaf018fce20dec9 | 15,594 |
def _get_object_description(target):
"""Return a string describing the *target*"""
if isinstance(target, list):
data = "<list, length {}>".format(len(target))
elif isinstance(target, dict):
data = "<dict, length {}>".format(len(target))
else:
data = target
return data | 57ad3803a702a1199639b8fe950ef14b8278bec1 | 15,595 |
def build_tf_xlnet_to_pytorch_map(model, config, tf_weights=None):
""" A map of modules from TF to PyTorch.
I use a map to keep the PyTorch model as
identical to the original PyTorch model as possible.
"""
tf_to_pt_map = {}
if hasattr(model, "transformer"):
if hasattr(model, "l... | b822a5f5effcf1d925dec0e6c6b166ecb89b6627 | 15,596 |
def dynamicviewset(viewset):
"""
The activate route only makes sense if
user activation is required, remove the
route if activation is turned off
"""
if not settings['REQUIRE_ACTIVATION'] and hasattr(viewset, 'activate'):
delattr(viewset, 'activate')
return viewset | f31a191c7c4d51163f588fa4e728f92fb7d43816 | 15,597 |
import random
def generate_arabic_place_name(min_length=0):
"""Return a randomly generated, potentially multi-word fake Arabic place name"""
make_name = lambda n_words: ' '.join(random.sample(place_names, n_words))
n_words = 3
name = make_name(n_words)
while len(name) < min_length:
n_word... | 7efc760b8dcf5f8807e2d203542fa637908cbad2 | 15,598 |
def find_cutoffs(x,y,crdist,deltas):
"""function for identifying locations of cutoffs along a centerline
and the indices of the segments that will become part of the oxbows
from MeanderPy
x,y - coordinates of centerline
crdist - critical cutoff distance
deltas - distance between neighboring poin... | 82de02759c70ab746d2adcfafd04313cbb0a8c4e | 15,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.