content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Any
def suggested_params(**kwargs: Any) -> transaction.SuggestedParams:
"""Return the suggested params from the algod client.
Set the provided attributes in ``kwargs`` in the suggested parameters.
"""
params = _algod_client().suggested_params()
for key, value in kwargs.items()... | 678f207bdd1152f6a8cb98e9c4964dd43b9dd761 | 25,000 |
def norm_rl(df):
"""
Normalizes read length dependent features
"""
rl_feat = ["US_r", "US_a", "DS_a", "DS_r", "UXO_r", "UXO_a", "DXO_r", "DXO_a", "UMO_r", "UMO_a", "DMO_r", "DMO_a", "MO_r", "MO_a", "XO_r", "XO_a"]
rl = df['MO_r'].max()
df[rl_feat] = df[rl_feat]/rl
return df | 0f7c36a447f04bc647773e99a83f59f3789849d4 | 25,001 |
import json
def sendRequest(self, channel, params=None):
"""发送请求"""
# 生成请求
d = {}
d['event'] = 'addChannel'
d['channel'] = channel
# 如果有参数,在参数字典中加上api_key和签名字段
if params is not None:
params['api_key'] = apiKey
params['sign'] = buildMySign(params, secreteKey)
d['par... | ddaae8800e0fbcf69ce1e15abba4725ef70eadfa | 25,002 |
def altCase(text: str):
"""
Returns an Alternate Casing of the Text
"""
return "".join(
[
words.upper() if index % 2 else words.lower()
for index, words in enumerate(text)
]
) | 1d8c25f9b81e360c254ac10ce105f99ca890a87c | 25,003 |
def makeObjectArray(elem, graph, num, tag=sobject_array):
"""
Create an object array of num objects based upon elem, which becomes the
first child of the new object array
This function also can create a delay when passed a different tag
"""
p = elem.getparent()
objarray = etree.Element(etree... | 5ef896b6514dc0d5ce00bbf0322c9e775fb4a152 | 25,004 |
def convert_escaped_utf8_literal(
text: str
) -> str:
"""Convert any escaped UTF-8 hexadecimal character bytes into the proper
string characters(s).
This function will convert a string, that may contain escaped UTF-8
literal hexadecimal bytes, into a string with the proper characters.
Args... | 17dc6da0c0f4aef9a3586f139874760bbfcf4823 | 25,005 |
def convert_mg_l_to_mymol_kg(o2, rho_0=1025):
"""Convert oxygen concentrations in ml/l to mymol/kg."""
converted = o2 * 1/32000 * rho_0/1000 * 1e6
converted.attrs["units"] = "$\mu mol/kg$"
return converted | 5925cf1f5629a0875bdc777bc3f142b9a664a144 | 25,006 |
import xml
from typing import List
def parse_defines(root: xml.etree.ElementTree.Element,
component_id: str) -> List[str]:
"""Parse pre-processor definitions for a component.
Schema:
<defines>
<define name="EXAMPLE" value="1"/>
<define name="OTHER"/>
</de... | 0f2b06581d89f9be3ff4d733e1db9b56e951cc89 | 25,007 |
def make_f_beta(beta):
"""Create a f beta function
Parameters
----------
beta : float
The beta to use where a beta of 1 is the f1-score or F-measure
Returns
-------
function
A function to compute the f_beta score
"""
beta_2 = beta**2
coeff = (1 + beta_2)
def... | f0e6993ac956171c58415e1605706c453d3e6d61 | 25,008 |
def _autohint_code(f, script):
"""Return 'not-hinted' if we don't hint this, else return the ttfautohint
code, which might be None if ttfautohint doesn't support the script.
Note that LGC and MONO return None."""
if script == 'no-script':
return script
if not script:
script = noto_fonts.script_key_to... | 4341098cbd9581ef989a65d352493fe28c7ddbd7 | 25,009 |
def infostring(message=""):
"""Info log-string.
I normally use this at the end of tasks.
Args:
message(str): A custom message to add.
Returns:
(str)
"""
message.rstrip().replace("\n", " ")
return tstamp() + "\t## INFO ## " + message + "\n" | 14e3012ad9c6e4c7cd10ea885098e31a3eef3ead | 25,010 |
def handler(event, _):
"""
Lambda handler
"""
# Input event:
# https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html#cognito-user-pools-lambda-trigger-event-parameter-shared
logger.debug({
"message": "Input event",
... | 0482f29b0088b6bbf72b8027b2da83b802f4d551 | 25,011 |
def geo_point_n(arg, n):
"""Return the Nth point in a single linestring in the geometry.
Negative values are counted backwards from the end of the LineString,
so that -1 is the last point. Returns NULL if there is no linestring in
the geometry
Parameters
----------
arg : geometry
n : in... | 6da6e0f362fac5e63093e0b93b5cf75b4f05bb5f | 25,012 |
def replace_pasture_scrubland_with_shrubland(df, start_col, end_col):
"""Merge pasture and scrubland state transitions into 'shrubland'.
1. Remove transitions /between/ scrubland and pasture and vice versa.
2. Check there are no duplicate transitions which would be caused by an
identical set of cond... | 9f3102a157e8fbaad1cca3631a117ab45470bae3 | 25,013 |
from typing import List
def get_storage_backend_descriptions() -> List[dict]:
"""
Returns:
"""
result = list()
for backend in SUPPORTED_STORAGE_BACKENDS:
result.append(get_storage_backend(backend).metadata)
return result | 2ec097a7c70788da270849332f845316435ac746 | 25,014 |
from typing import Tuple
def get_business_with_most_location() -> Tuple:
"""
Fetches LA API and returns the business with most locations
from first page
:return Tuple: business name and number of locations
"""
response = _fetch_businesses_from_la_api()
business_to_number_of_location = dict... | ee0d7f432387e4587f615bd294cc8c8276d5baf1 | 25,015 |
from typing import AbstractSet
def degrees_to_polynomial(degrees: AbstractSet[int]) -> Poly:
"""
For each degree in a set, create the polynomial with those
terms having coefficient 1 (and all other terms zero), e.g.:
{0, 2, 5} -> x**5 + x**2 + 1
"""
degrees_dict = dict.fromkeys(degrees, ... | 6c6a27b499f766fae20c2a9cf97b7ae0352e7dc5 | 25,016 |
def validate_set_member_filter(filter_vals, vals_type, valid_vals=None):
"""
Validate filter values that must be of a certain type or
found among a set of known values.
Args:
filter_vals (obj or Set[obj]): Value or values to filter records by.
vals_type (type or Tuple[type]): Type(s) of... | a48639473ed0ac303776d50fb4fb09fa45a74d8e | 25,017 |
def update_many(token, checkids, fields, customerid=None):
""" Updates a field(s) in multiple existing NodePing checks
Accepts a token, a list of checkids, and fields to be updated in a
NodePing check. Updates the specified fields for the one check.
To update many checks with the same value, use update... | b96d3e29c6335b6bbec357e42a008faa654c72ab | 25,018 |
def main(start, end, csv_name, verbose):
"""Run script conditioned on user-input."""
print("Collecting Pomological Watercolors {s} throught {e}".format(s=start, e=end))
return get_pomological_data(start=start, end=end, csv_name=csv_name, verbose=verbose) | fd0c619f8e24929e705285bc9330ef1d21825d8b | 25,019 |
import hashlib
def _sub_fetch_file(url, md5sum=None):
"""
Sub-routine of _fetch_file
:raises: :exc:`DownloadFailed`
"""
contents = ''
try:
fh = urlopen(url)
contents = fh.read()
if md5sum is not None:
filehash = hashlib.md5(contents).hexdigest()
... | 0a92aaa55661469686338631913020a99aab0d8c | 25,020 |
def get_path_to_config(config_name: str) -> str:
"""Returns path to config dir"""
return join(get_run_configs_dir(), config_name) | 3a4092c66ea18929d001e7bb4e8b5b90b8a38439 | 25,021 |
import io
def get_orig_rawimage(raw_file, debug=False):
"""
Read a raw, original LRIS data frame.
Ported from LOWREDUX long_oscan.pro lris_oscan()
Parameters
----------
raw_file : :obj:`str`
Filename
debug : :obj:`bool`, optional
Run in debug mode (doesn't do anything)
... | 724fe9058a7430db565014922f3fd65a7756b743 | 25,022 |
def scan_db_and_save_table_info(data_source_id, db_connection, schema, table):
"""Scan the database for table info."""
table_info = get_table_info(
{}, schema, table, from_db_conn=True, db_conn=db_connection
)
old_table_info = fetch_table_info(data_source_id, schema, table, as_obj=True)
data... | 050183b68891ff0ab0f45435d29206a5800b704c | 25,023 |
def _get_non_heavy_neighbor_residues(df0, df1, cutoff):
"""Get neighboring residues for non-heavy atom-based distance."""
non_heavy0 = df0[df0['element'] != 'H']
non_heavy1 = df1[df1['element'] != 'H']
dist = spa.distance.cdist(non_heavy0[['x', 'y', 'z']], non_heavy1[['x', 'y', 'z']])
pairs = np.ar... | b27a341cb1e5e5dd74c881036d7002a107270cd5 | 25,024 |
def j0(ctx, x):
"""Computes the Bessel function `J_0(x)`. See :func:`besselj`."""
return ctx.besselj(0, x) | c2defd50be3feb3791f5be5709e5312d1e232590 | 25,025 |
def mysql2df(host, user, password, db_name, tb_name):
"""
Return mysql table data as pandas DataFrame.
:param host: host name
:param user: user name
:param password: password
:param db_name: name of the pydb from where data will be exported
:param tb_name: name of the table from where data ... | a4ea75b9fa13e6cb48650e69f5d8216f24fdaf07 | 25,026 |
def is_int(number):
""" Check if a variable can be cast as an int.
@param number: The number to check
"""
try:
x = int(number)
return True
except:
return False | e8e8956942d96956cb34b424b34fb028620f8be1 | 25,027 |
import pathlib
def get_versions(api_type=DEFAULT_TYPE):
"""Search for API object module files of api_type.
Args:
api_type (:obj:`str`, optional):
Type of object module to load, must be one of :data:`API_TYPES`.
Defaults to: :data:`DEFAULT_TYPE`.
Raises:
:exc:`exc... | 58b2df442901b080db12951ab48991371689e955 | 25,028 |
def model_flux(parameters_dict, xfibre, yfibre, wavelength, model_name):
"""Return n_fibre X n_wavelength array of model flux values."""
parameters_array = parameters_dict_to_array(parameters_dict, wavelength,
model_name)
return moffat_flux(parameters_array, x... | c3cf75fab6b8b4965aefeebf82d40378bcd1de19 | 25,029 |
def new_rnn_layer(cfg, num_layer):
"""Creates new RNN layer for each parameter depending on whether it is bidirectional LSTM or not.
Uses the fast LSTM implementation backed by CuDNN if a GPU is available.
Note: The normal LSTMs utilize sigmoid recurrent activations so as to retain compatibility CuDNN... | 341ca96549f40c8607e44b9ef353313107a8fb0a | 25,030 |
def firfreqz(h, omegas):
"""Evaluate frequency response of an FIR filter at discrete frequencies.
Parameters
h: array_like
FIR filter coefficient array for numerator polynomial.
e.g. H(z) = 1 + a*z^-1 + b*z^-2
h = [1, a, b]
"""
hh = np.zeros(omegas.shape, dtype='comple... | 4463b1dcd73090d2dedbdd0e78066e4d26d19655 | 25,031 |
import pickle
def write_np2pickle(output_fp: str, array, timestamps: list) -> bool:
"""
Convert and save Heimann HTPA NumPy array shaped [frames, height, width] to a pickle file.
Parameters
----------
output_fp : str
Filepath to destination file, including the file name.
array : np.ar... | 96956829a41f3955440693f0d754b013a218e941 | 25,032 |
from re import S
import logging
import webbrowser
def run(
client_id_: str, client_secret_: str, server_class=HTTPServer, handler_class=S, port=8080
) -> str:
"""
Generates a Mapillary OAuth url and prints to screen as well as opens it automatically in a browser. Declares some
global variables to pull... | 152e4c0ae5c20b8e39693478ff5d06c1cc5fa8a5 | 25,033 |
def sort_by_rank_change(val):
"""
Sorter by rank change
:param val: node
:return: nodes' rank value
"""
return abs(float(val["rank_change"])) | ff5730e7cc765949dcfcfd4a3da32947ce3a411a | 25,034 |
def ping():
"""always 200"""
status = 200
return flask.Response(response='\n', status=status, mimetype='application/json') | 8407d4ef4188badbeff5ba34868d530b06dd5158 | 25,035 |
import json
import logging
def lambda_handler(event=None, context=None):
"""Entry point for lambda, simple try/except/finally with return and raise values"""
print(f"EVENT: {json.dumps(event)}")
try:
response = actions(event)
return response
except Exception as e:
logging.debug... | 5224552193839d56cd264104a226227ff459223d | 25,036 |
def add_gtid_ranges_to_executed_set(existing_set, *new_ranges):
"""Takes in a dict like {"uuid1": [[1, 4], [7, 12]], "uuid2": [[1, 100]]} (as returned by e.g. parse_gtid_range_string)
and any number of lists of type [{"server_uuid": "uuid", "start": 1, "end": 3}, ...]. Adds all the ranges in the lists to
th... | 47a71f2a55054d83092ffbb2119bcab7760f28a8 | 25,037 |
def fetch_rgb(img):
"""for outputing rgb values from click event to the terminal.
:param img: input image
:type img: cv2 image
:return: the rgb list
:rtype: list
"""
rgb_list = []
def click_event(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDOWN:
red = i... | 16ff0359d47eb31a4f9c529740a9813680937e22 | 25,038 |
import functools
def _get_date_filter_consumer(field):
"""date.{lt, lte, gt, gte}=<ISO DATE>"""
date_filter = make_date_filter(functools.partial(django_date_filter, field_name=field))
def _date_consumer(key, value):
if '.' in key and key.split(".")[0] == field:
prefix, qualifier = key... | 37b7938ef5cebd29d487ec1e53cfc86d13a726d3 | 25,039 |
def data_path(fname):
"""
Gets a path for a given filename. This ensures that relative filenames to
data files can be used from all modules.
model.json -> .../src/data/model.json
"""
return join(dirname(realpath(__file__)), fname) | 294c91a041227fd9da6d1c9c8063de283281e85e | 25,040 |
def _parse_special_functions(sym: sp.Expr, toplevel: bool = True) -> sp.Expr:
"""
Recursively checks the symbolic expression for functions which have be
to parsed in a special way, such as piecewise functions
:param sym:
symbolic expressions
:param toplevel:
as this is called recur... | b560521ceee7cb4db16b808e44b1e538e236c00e | 25,041 |
from sys import path
import glob
def load_oxfordiiitpets(breed=True) -> core.SceneCollection:
"""Load the Oxford-IIIT pets dataset. It is not divided into
train, validation, and test because it appeared some files were missing
from the trainval and test set documents
(e.g., english_cocker_spaniel_164)... | a53e242f04df7a04455dc693111d3eed5820b15d | 25,042 |
import re
def _do_process_purpose(action):
""" Does all the 'hard work' in processing the purpose. Returns a single
line of the form
symbol, ex_date(yyyy-mm-dd), purpose(d/b/s), ratio(for b/s), value(for d),
"""
symbol = action.sym.upper()
purpose = action.purpose.lower()
ex_date = action.... | 60d704e22a754f28639a81b4a49b9aba858cb50f | 25,043 |
def get_airflow_config(version, timestamp, major, minor, patch, date, rc):
"""Return a dict of the configuration for the Pipeline."""
config = dict(AIRFLOW_CONFIG)
if version is not None:
config['VERSION'] = version
else:
config['VERSION'] = config['VERSION'].format(
major=major, minor=minor, pa... | 87c76949dba717b801a8d526306d0274eb193cc5 | 25,044 |
def find_duplicates(treeroot, tbl=None):
"""
Find duplicate files in a directory.
"""
dup = {}
if tbl is None: tbl = {}
os.path.walk(treeroot, file_walker, tbl)
for k,v in tbl.items():
if len(v) > 1:
dup[k] = v
return dup | 0a959e443b7a4f5c67e57b8fc7bf597fee96065a | 25,045 |
def attach_capping(mol1, mol2):
"""it is connecting all Nterminals with the desired capping
Arguments:
mol1 {rdKit mol object} -- first molecule to be connected
mol2 {rdKit mol object} -- second molecule to be connected - chosen N-capping
Returns:
rdKit mol object -- mol1 updated (... | 24a80efd94c4a5d4e0ddba478240d7c1b82ad52b | 25,046 |
def gather_point(input, index):
"""
**Gather Point Layer**
Output is obtained by gathering entries of X indexed by `index`
and concatenate them together.
.. math::
Out = X[Index]
.. code-block:: text
Given:
X = [[1, 2, 3],
[3, 4, 5],
[5, 6, 7]]
... | dc4298ccf7df084abfc7d63f88ae7edb03af4010 | 25,047 |
def _apply_size_dependent_ordering(input_feature, feature_level, block_level,
expansion_size, use_explicit_padding,
use_native_resize_op):
"""Applies Size-Dependent-Ordering when resizing feature maps.
See https://arxiv.org/abs/1912.01106
... | c44206246102bbddc706be2cb0644676650c4675 | 25,048 |
def distance(s1, s2):
"""Return the Levenshtein distance between strings a and b."""
if len(s1) < len(s2):
return distance(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = xrange(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
... | d7bb6e7a374349fd65bde621a29ee110402d18aa | 25,049 |
def check_diversity(group, L):
"""check if group satisfy l-diversity
"""
SA_values = set()
for index in group:
str_value = list_to_str(gl_data[index][-1], cmp)
SA_values.add(str_value)
if len(SA_values) >= L:
return True
return False | 7e87f96a80651608688d86c9c9e921d793fb6a9e | 25,050 |
import urllib
def getEntries(person):
""" Fetch a Advogato member's diary and return a dictionary in the form
{ date : entry, ... }
"""
parser = DiaryParser()
f = urllib.urlopen("http://www.advogato.org/person/%s/diary.xml" % urllib.quote(person))
s = f.read(8192)
while s:
... | 9ed0b46aa694201817fd4c341a992c81d809abf5 | 25,051 |
def sum_values(p, K):
"""
sum the values in ``p``
"""
nv = []
for v in itervalues(p):
nv = dup_add(nv, v, K)
nv.reverse()
return nv | c92ac3492f0aa750879f899dde145918d4a9616d | 25,052 |
def define_permit_price_targeting_constraints(m):
"""Constraints used to get the absolute difference between the permit price and some target"""
# Constraints to minimise difference between permit price and target
m.C_PERMIT_PRICE_TARGET_CONSTRAINT_1 = pyo.Constraint(
expr=m.V_DUMMY_PERMIT_PRICE_TA... | eb31f63963e0a66491e31d3f4f8f816e21c47de9 | 25,053 |
def predict4():
"""Use Xception to label image"""
path = 'static/Images/boxer.jpeg'
img = image.load_img(path,target_size=(299,299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
pclass = decode_predictions(preds, top=5)
... | 033fcde3cb670b8a66b430451f6b341ae2e7b980 | 25,054 |
def augment_data(image, label, seg_label, perform_random_flip_and_rotate,
num_channels, has_seg_labels):
"""
Image augmentation for training. Applies the following operations:
- Horizontally flip the image with probabiliy 0.5
- Vertically flip the image with probability 0.5
... | c243ae36a1d38cd36131bbd2f51347d2d29ca9ff | 25,055 |
def protobuf_open_channel(channel_name, media_type):
"""func"""
open_channel_request = pb.OpenChannelRequest()
open_channel_request.channel_name = channel_name
open_channel_request.content_type = media_type
return open_channel_request.SerializeToString() | 0d665788cbc37d8a15c276c41d2c28e5c12ee2ea | 25,056 |
def action(update, context):
"""A fun command to send bot actions (typing, record audio, upload photo, etc). Action appears at top of main chat.
Done using the /action command."""
bot = context.bot
user_id = update.message.from_user.id
username = update.message.from_user.name
admin = _admin(use... | 5df8260a8787293187bba86712bf07505f915f39 | 25,057 |
import os
def findPartsLists(path):
"""gets a list of files/folders present in a path"""
walkr = os.walk(path)
dirlist = [a for a in walkr]
#print dirlist
expts = []
for fle in dirlist[0][2]:
#print fle
if(fle[-4:]=='xlsx'):
try:
xl_file = pd.read_ex... | d065351152367e13178a9453387b30e56ca61cd0 | 25,058 |
def borehole_vec(x, theta):
"""Given x and theta, return vector of values."""
(Hu, Ld_Kw, Treff, powparam) = np.split(theta, theta.shape[1], axis=1)
(rw, Hl) = np.split(x[:, :-1], 2, axis=1)
numer = 2 * np.pi * (Hu - Hl)
denom1 = 2 * Ld_Kw / rw ** 2
denom2 = Treff
f = ((numer / ((deno... | 15f39f80d7ead4bb807dbb5c365acb900bbf405d | 25,059 |
import requests
import json
def read_datastore(resource_id):
"""
Retrieves data when the resource is part of the CKAN DataStore.
Parameters
----------
resource_id: str
Id for resource
Returns
----------
pd.DataFrame:
Data records in table format
"""
r = reque... | 80ff1b26960e7d33b0a68d286769736617353881 | 25,060 |
import hashlib
import binascii
def new_server_session(keys, pin):
"""Create SRP server session."""
context = SRPContext(
"Pair-Setup",
str(pin),
prime=constants.PRIME_3072,
generator=constants.PRIME_3072_GEN,
hash_func=hashlib.sha512,
bits_salt=128,
bits... | 5c3c20269dce31b4f7132d123845d7a46354373f | 25,061 |
def lenzi(df):
"""Check if a pandas series is empty"""
return len(df.index) == 0 | 561705e6ff0da3bfb03407a721f2aff71a4d42a1 | 25,062 |
def m_step(counts, item_classes, psuedo_count):
"""
Get estimates for the prior class probabilities (p_j) and the error
rates (pi_jkl) using MLE with current estimates of true item classes
See equations 2.3 and 2.4 in Dawid-Skene (1979)
Input:
counts: Array of how many times each rating was giv... | 00d93803dd7f3f56af47f8fb455613d223fe0a89 | 25,063 |
from typing import Callable
def make_parser(fn: Callable[[], Parser]) -> Parser:
"""
Make typed parser (required for mypy).
"""
return generate(fn) | 491888a666718d84447ff9de1b215a9e9c0f8ff0 | 25,064 |
def mfcc_htk(y, sr, hop_length=2**10, window_length=22050, nmfcc=13, n_mels=26, fmax=8000, lifterexp=22):
"""
Get MFCCs 'the HTK way' with the help of Essentia
https://github.com/MTG/essentia/blob/master/src/examples/tutorial/example_mfcc_the_htk_way.py
Using all of the default parameters from there exc... | e3beb95a027e963549df6a164b0d99345137540b | 25,065 |
def num_to_int(num):
"""
Checks that a numerical value (e.g. returned by robot) is an integer and
not a float.
Parameters
----------
num : number to check
Returns
-------
integer : num cast to an integer
Raises
------
ValueError : if n is not an integer
"""
if ... | af470940eb035fe8dd0160dfe9614c2b6d060194 | 25,066 |
def shuffle_blocks(wmx_orig, pop_size=800):
"""
Shuffles pop_size*pop_size blocks within the martrix
:param wmx_orig: original weight matrix
:param pop_size: size of the blocks kept together
:return: wmx_modified: modified weight matrix
"""
assert nPCs % pop_size == 0
np.random.seed(123... | aec38fe296b877ab79932aa675c5d04820e391af | 25,067 |
def change():
"""
Change language
"""
lang = request.args.get("lang", None)
my_id = None
if hasattr(g, 'my') and g.my:
my_id = g.my['_id']
data = core.languages.change(lang=lang, my_id=my_id)
return jsonify(data) | a5186669db31b533e1ca9bc146b11d577be4f845 | 25,068 |
import shutil
def make_pkg(pkgname, context):
"""Create a new extension package.
:param pkgname: Name of the package to create.
:param context: Mapping with keys that match the placeholders in the
templates.
:return: True if package creation succeeded or a tuple with False and a... | 6e2be6e991e2061a7b07e5e44a3479dbf0c2f1b1 | 25,069 |
def view_explorer_node(node_hash: str):
"""Build and send an induction query around the given node."""
node = manager.get_node_by_hash_or_404(node_hash)
query = manager.build_query_from_node(node)
return redirect_to_view_explorer_query(query) | 3534d546ba540dcfc6db1110c0a4a1086515dc3d | 25,070 |
import math
def encode_into_any_base(number, base, encoded_num):
"""Encode number into any base 2-36. Can be fractional or whole.
Parameters:
number: float -- integer representation of number (in base 10)
base: int -- base to convert to
encoded_num: str -- representation (so far) of n... | f6dd94e173a3844dc6d858d1c6b360354624d3f1 | 25,071 |
def handle_forbidden(error: Forbidden) -> Response:
"""Render the base 403 error page."""
return respond(error.description, status=HTTPStatus.FORBIDDEN) | 89c59dd66ce63ceef9e60cf8beea0da7895a0394 | 25,072 |
def getval(l, b, map='sfd', size=None, order=1):
"""Return SFD at the Galactic coordinates l, b.
Example usage:
h, w = 1000, 4000
b, l = numpy.mgrid[0:h,0:w]
l = 180.-(l+0.5) / float(w) * 360.
b = 90. - (b+0.5) / float(h) * 180.
ebv = dust.getval(l, b)
imshow(ebv, aspect='auto', norm=ma... | 0c864577e545dccf9ced52c6ef88a616457006ac | 25,073 |
def format_timedelta(tdelta):
"""Return the timedelta as a 'HH:mm:ss' string."""
total_seconds = int(tdelta.total_seconds())
hours, remainder = divmod(total_seconds, 60*60)
minutes, seconds = divmod(remainder, 60)
return "{0:02d}:{1:02d}:{2:02d}".format(hours, minutes, seconds) | 852902e7972bcd13df8b60864ebcb2d75b2b259d | 25,074 |
def video_data_to_df(videos_entries, save_csv):
"""
Creating a dataframe from the video data stored as tuples
:param videos_entries: (list) list of tuples containing topics, subtopics, videos and durations
:param save_csv: (boolean) condition to specify if the df is saved locally as a csv file
:ret... | 11bb3d9293aa3689286cde76aea8bfff72594639 | 25,075 |
def create_mysql_entitySet(username, databaseName):
""" Create a new entity set in the databaseName """
password = get_password(username)
entitySetName = request.json['entitySetName']
attributes = request.json['attributes']
addToSchema(request.get_json(),"mysql")
pks = []
sql = "CREATE TABLE... | 00510e850d4c10f24defe7af070c652d3b390b5c | 25,076 |
def m6(X, Y, Xp, Yp, alpha=1.0, prev='ident', post='ident', **kwargs):
"""Computes a matrix with the values of applying the kernel
:math:`m_4` between each pair of elements in :math:`X` and :math:`Y`.
Args:
X: Numpy matrix.
Y: Numpy matrix.
Xp: Numpy matrix with the probabilities of... | 94d1651500ec9177a14a2c8ad80abc6ca7c3948b | 25,077 |
import time
import json
from unittest.mock import call
def serve_communications_and_statuses(erpnext_support_user, erpnext_support_issues, bench_site):
"""
returns a dict of support issue communications and statuses
response = {
"issue_name_1": {
"communications": [],
"status": "status",
"last_syn... | ceaeeb5a1f5cbe956aeaef681b5e37c3d4ed58d2 | 25,078 |
def answer_view(answerid):
"""route to view a specific answer"""
return jsonify({"answer":"Your updated answer: {} ".format(user_answers[answerid])}) | 82c7697bfe601b54dcb1fd9c8667565886a09c34 | 25,079 |
def jwk_factory(acct_priv_key_path: str) -> _JWKBase:
"""generate jwk object according private key file"""
with open(acct_priv_key_path, 'rb') as f:
acct_priv = serialization.load_pem_private_key(
data=f.read(),
password=None,
backend=default_backend()
)
... | fc08dd7294ddb067534c05a7e13b26e053ac3c42 | 25,080 |
from pathlib import Path
def execute(
scan_definition: str | Path,
df: DataFrame,
*,
soda_server_client: SodaServerClient | None = None,
) -> ScanResult:
"""
Execute a scan on a data frame.
Parameters
----------
scan_definition : Union[str, Path]
The path to a scan file or... | 7bf0bedfb8865de117565110be4225b502e2fed2 | 25,081 |
def jaccard_similarity(emb1: np.ndarray, emb2: np.ndarray) -> float:
""" 计算特征向量的Jaccard系数
:param emb1: shape = [feature,]
:param emb2: shape = [feature,]
:return: Jaccard 系数
"""
up = np.double(np.bitwise_and((emb1 != emb2), np.bitwise_or(emb1 != 0, emb2 != 0)).sum())
down = np.double(np.bit... | 18e95d7f14ca093892770364fc5af75b95bebe2a | 25,082 |
from typing import Tuple
from typing import Dict
from typing import List
def _share_secret_int_indices(s_i: int, n: int, t: int) -> Tuple[Dict[int, int], List[PointG1]]:
""" Computes n shares of a given secret such that at least t + 1 shares are required for recovery
of the secret. Additionally returns t... | b822bd79337be741bbd626751f9d745b4b9e23fc | 25,083 |
def auto_type(key, redis=None, default=None, o=True):
"""Returns datatype instance"""
if redis is None:
redis = config.redis
key = compress_key(key)
if redis.exists(key):
datatype = redis.type(key)
if datatype == 'string':
test_string = RedisString(key, redis=red... | 3d1751c14c4b0c04d11ab265395dce94822558d8 | 25,084 |
from pathlib import Path
def get_user_data_dir(app_name=DEFAULT_APP_NAME, auto_create=True) -> Path:
"""
Get platform specific data folder
"""
return _get_user_dir(
app_name=app_name,
xdg_env_var='XDG_DATA_HOME', win_env_var='APPDATA',
fallback='~/.local/share', win_fallback='~... | 321b885983affcc5cf4d4baf0410ae9ad6b6f443 | 25,085 |
import codecs
import csv
import os
import re
def parse_evidence(
fixed_labels=None,
evidence_files=None,
molecules=None,
evidence_score_field=None,
return_raw_csv_data=False,
unimod_file_list=None,
):
"""
Reads in the evidence file and returns the final formatted fixed labels,
the ... | f01615da155fdea090c49f54049f1e57837c20cf | 25,086 |
import copy
import numpy
def calculateDominantFrequency(signal, fs, fMin = 0, fMax = None, applyWindow = True,
fftZeroPaddingFactor = 1
):
"""
calculates the dominant frequency of the given signal
@param signal input signal
@param fs sampling frequency
@param fMin the minimum frequency [Hz] that should be con... | ab5f2818d309202f57230197c87c54b67a0f849c | 25,087 |
def check_title(file_path):
"""
return 'has title' if found
no title, None, if not found
file_path is full path with file name and extension
"""
#print('is text file: ', tool.is_utf8_text_file(file_path))
if tool.is_utf8_text_file(file_path):
with open(file_path, 'r') as f:
... | 4559772c1e50e807935c6112cfa6001a857b9dc4 | 25,088 |
from typing import Tuple
import torch
def permute_adjacency_twin(t1,t2) -> Tuple[torch.Tensor,torch.Tensor]:
"""
Makes a permutation of two adjacency matrices together. Equivalent to a renaming of the nodes.
Supposes shape (n,n)
"""
n,_ = t1.shape
perm = torch.randperm(n)
return t1[perm,:]... | df3dc6507b8eae9d148ec9b2e664a427813d93a7 | 25,089 |
from collections import defaultdict,deque
def rad_extract(eventfiles,center,radius_function,return_cols=['PULSE_PHASE'],cuts=None,apply_GTI=True,theta_cut=66.4,zenith_cut=105,return_indices=False):
""" Extract events with a radial cut.
Return specified columns and perform additional boolean cuts.
... | bb0a5f96764c0a1edec1f408f283a2473ed630bf | 25,090 |
import distutils
def strtobool(value):
"""Cast a string to a bool."""
if value is None:
return None
if type(value) is bool:
return value
return distutils.util.strtobool(value) | 57cb071725959072fe478c44be130709a0ebf8f9 | 25,091 |
import re
def list_to_exp(str_list, term_padding_exp=r'\b', compile=True):
"""
Returns a regular expression (compiled or not) that will catch any of the strings of the str_list.
Each string of the str_list will be surrounded by term_padding_exp (default r'\b' forces full word matches).
Note: Also orde... | f9a1d7002a36f0348179b9997c5dec672455f077 | 25,092 |
def prepare_ddp_loader(loader: DataLoader, num_processes: int, process_index: int) -> DataLoader:
"""
Transfers loader to distributed mode. Experimental feature.
Args:
loader: pytorch dataloder
num_processes (:obj:`int`, `optional`, defaults to 1):
The number of processes runnin... | 4f57b1888fdf43fcb910d802faee8ba997ee095f | 25,093 |
import logging
def __validate_exchange(value: str) -> str:
"""
Check to see if passed string is in the list of possible Exchanges.
:param value: Exchange name.
:return: Passed value or No Return
"""
valid_values = EXCHANGE_VALUES
if value in valid_values:
return value
else:
... | 001472e1485da0fc410dceafa67b78fe5dfe1058 | 25,094 |
def main(content, title="", classes=[]):
"""Generate a 'Material for MkDocs' admonition.
"""
md = markdown.markdown(content)
return '<div class="admonition {0}">\n'.format(" ".join(classes)) + \
' <p class="admonition-title">{0}</p>\n'.format(title) + \
' <p>{0}</p>\n'.format... | e29942de52b73d8652a54c64dd22c8bac6e8496c | 25,095 |
def get_bprop_matrix_set_diag(self):
"""Generate bprop for MatrixSetDiag"""
get_dtype = P.DType()
def bprop(x, y, z, out, dout):
input_shape = F.shape(x)
batch_shape = input_shape[:-2]
matrix_shape = input_shape[-2:]
diag_shape = batch_shape + (_get_min(matrix_shape),)
... | c35f69a957b30bcefeba858e7e9bd4ee9e4591b8 | 25,096 |
from yt import load_particles
def fake_sph_grid_ds(hsml_factor=1.0):
"""Returns an in-memory SPH dataset useful for testing
This dataset should have 27 particles with the particles arranged uniformly
on a 3D grid. The bottom left corner is (0.5,0.5,0.5) and the top right
corner is (2.5,2.5,2.5). All ... | 9f32616d325fde7941cbcea814b3133fbcc988e5 | 25,097 |
async def _async_get_image_sessions(device: Device) -> dict[str, ImageSession]:
"""Return image events for the device."""
events = await device.event_media_manager.async_image_sessions()
return {e.event_token: e for e in events} | 4406abc1ac08d39bb0127be1d02f5c664c167e04 | 25,098 |
def make_element_weight_parser(weight_column):
""" Parameterize with the column - this allows us
to generate data from different analysis result types.
"""
def parse_element_weight(csv_row):
name = csv_row[0]
weight = float(csv_row[weight_column]) # Assert not zero?
return name, weight
return parse_element... | ddc3a4f82ecd0fe4833683759b1a1c4296839a54 | 25,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.