content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
def auth(options) -> bool:
"""Set up auth and nothing else."""
objectStore = FB_ObjectStore(options)
if options.get("test", False):
# If we only care if it's valid, just check and leave
auth_token = objectStore.get_cached_auth_token()
# Validate and return cached aut... | be2acdd2564ee05e746ba99fbb10a50e9dc92eb1 | 29,700 |
def _parse_detector(detector):
"""
Check and fix detector name strings.
Parameters
----------
detector : `str`
The detector name to check.
"""
oklist = ['n0', 'n1', 'n2', 'n3', 'n4', 'n5', 'n6', 'n7', 'n8', 'n9',
'n10', 'n11']
altlist = [str(i) for i in range(12)]
... | f78d7eb5004b3cb6d3276b0c701263c71668e36e | 29,701 |
def mobius_area_correction_spherical(tria, mapping):
"""
Find an optimal Mobius transformation for reducing the area distortion of a spherical conformal parameterization
using the method in [1].
Input:
tria : TriaMesh (vertices, triangle) of genus-0 closed triangle mesh
mapping: nv x 3 vertex c... | 08d58e2e2ff13533ac733ef49a4f57d4e1d6f41d | 29,702 |
def rel_ordered(x1,x2,x3,x4):
"""
given 4 collinear points, return true if the direction
from x1->x2 is the same as x3=>x4
requires x1!=x2, and x3!=x4
"""
if x1[0]!=x2[0]:
i=0 # choose a coordinate which is varying
else:
i=1
assert x1[i]!=x2[i]
assert x3[i]!=x4[i]
... | 2649250e2ea2619c7f6c21b8dd2cebaeec10647b | 29,703 |
def min_rl(din):
"""
A MIN function should "go high" when any of its
inputs arrives. Thus, OR gates are all that is
needed for its implementation.
Input: a list of 1-bit WireVectors
Output: a 1-bit WireVector
"""
if len(din) == 1:
dout = din[0]
... | 06f0bbce664367307669ddb28c60c65b79de91d3 | 29,704 |
def fetch(u, data, indices, indptr, lmbda):
"""
"""
is_skip = 1
if lmbda > 0:
u0, u1 = indptr[u], indptr[u + 1]
val, ind = data[u0:u1], indices[u0:u1]
if u1 > u0:
is_skip = 0
else:
val = np.empty(0, dtype=data.dtype)
ind = np.empty(0, dtype=np.int3... | cd1d9ffe7ead7711b5e6cd1f2601c1456ce1baaa | 29,705 |
from typing import List
import re
def _gcc_parse_params(gcc: Gcc) -> List[Option]:
"""Parse the param help string from the GCC binary to find options."""
# Pretty much identical to _gcc_parse_optimize
logger.debug("Parsing GCC param space")
result = gcc("--help=param", "-Q", timeout=60)
out = re... | 17af97340602f00f9437ea259cac4430b920eb6e | 29,706 |
def pgrrec(CONST_STRING, lon, lat, alt, re, f):
"""pgrrec(ConstSpiceChar * CONST_STRING, SpiceDouble lon, SpiceDouble lat, SpiceDouble alt, SpiceDouble re, SpiceDouble f)"""
return _cspyce0.pgrrec(CONST_STRING, lon, lat, alt, re, f) | a1a9889e8c9e2d4b34e480688aeb8a26cb7699b7 | 29,707 |
from operator import add
def set(isamAppliance, name, properties, attributes=None, description=None, type="JavaScript", new_name=None,
check_mode=False, force=False):
"""
Creating or Modifying a JavaScript PIP
"""
ret_obj = search(isamAppliance, name=name)
id = ret_obj['data']
if id =... | 6c7f097eb22a1f3033dce2cdf3264bff5f7c9acb | 29,708 |
import logging
def init_model(model, opt, argv):
"""select the network initialization method"""
if hasattr(opt, 'weight_init') and opt.weight_init == 'xavier':
network_weight_xavier_init(model)
elif hasattr(opt, 'weight_init') and opt.weight_init == 'MSRAPrelu':
network_weight_MSRAPrelu_in... | 5c53efd15af6403a6323d25dc877dc652e4a49b1 | 29,709 |
def get_bash_commands(root_parser, root_prefix, choice_functions=None):
"""
Recursive subcommand parser traversal, returning lists of information on
commands (formatted for output to the completions script).
printing bash helper syntax.
Returns:
subparsers : list of subparsers for each parse... | 49ada910c5610634a9cbb5b2fd7c2ee639c2f9c0 | 29,710 |
import math
def shoulders_up(x, y, max_angle=10):
"""
1:"Neck",
2:"RShoulder",
5:"LShoulder".
looks at line from left shoulder to neck, and
line from right shoulder to neck
if either are not straight returns 1
if both are flat (slope of 0 or close to 0) returns 1
"""
left_degre... | 2a6adce5dad431c91cac77bd79e4011964f76341 | 29,711 |
def str(x: i32) -> str:
"""
Return the string representation of an integer `x`.
"""
if x == 0:
return '0'
result: str
result = ''
if x < 0:
result += '-'
x = -x
rev_result: str
rev_result = ''
rev_result_len: i32
rev_result_len = 0
pos_to_str: list... | 6af580da343eb6adab58021eb489cf837b50571c | 29,712 |
def grad_spsp_mult_entries_x_reverse(b_out, entries_a, indices_a, entries_x, indices_x, N):
""" Now we wish to do the gradient with respect to the X matrix in AX=B
Instead of doing it all out again, we just use the previous grad function on the transpose equation X^T A^T = B^T
"""
# get the transp... | 64e5fbf5ca12fb9516c7aab2a357823c201d3d5a | 29,713 |
import os
def start_replica_cmd(builddir, replica_id):
"""
Return a command that starts an skvbc replica when passed to
subprocess.Popen.
Note each arguments is an element in a list.
"""
statusTimerMilli = "500"
viewChangeTimeoutMilli = "10000"
path = os.path.join(builddir, "tests", "... | c3e85d132214c8cd2801d795a255f0868dda168a | 29,714 |
def execute_until_false(method, interval_s):
"""Executes a method forever until the method returns a false value.
Args:
method: The callable to execute.
interval_s: The number of seconds to start the execution after each method
finishes.
Returns:
An Interval object.
"""
interval = Interval... | eee730604ea98080e669d02f18a6ca55c4a4fe97 | 29,715 |
def vecnorm(a):
"""Return a/|a|"""
return a / mdamath.norm(a) | 425de4c8ddae138e1528ada448f86781b4c5130e | 29,716 |
def count_qubits(operator):
"""Compute the minimum number of qubits on which operator acts.
Args:
operator: FermionOperator, QubitOperator, DiagonalCoulombHamiltonian,
or PolynomialTensor.
Returns:
num_qubits (int): The minimum number of qubits on which operator acts.
Rais... | 9963c7b8202a825725ca3906b95f16d0243f81ed | 29,717 |
def datenum_to_date(date_num):
"""Transform date_num to datetime object.
Returns pd.NaT on invalid input"""
try:
total_seconds = round(dt.timedelta(days=date_num - 366).total_seconds())
return dt.datetime(1, 1, 1) + dt.timedelta(seconds=total_seconds) - dt.timedelta(days=1)
except Overf... | f2a523f0e1c1af15835ae042fdeac8ebcf0a5717 | 29,718 |
def save_ground_truth_part(name, tuple_path, mean, sem, std, sestd):
"""Saves a ground truth part to strings.
This is meant to be called with outputs of
`nest.flatten_with_tuple_paths(ground_truth_mean)`.
Args:
name: Python `str`. Name of the sample transformation.
tuple_path: Tuple path of the part o... | a4b769383dd0b250375205efeed363161b28ed0a | 29,719 |
def parse_cpe(cpe):
"""
Split the given CPE name into its components.
:param cpe: CPE name.
:type cpe: str
:returns: CPE components.
:rtype: list(str)
"""
ver = get_cpe_version(cpe)
if ver == "2.2":
parsed = [cpe22_unquote(x.strip()) for x in cpe[5:].split(":")]
if ... | 4dfbac57d3719a1c6ed00b5884be1321800827f5 | 29,720 |
def draw_points(xs, ys, covs, M):
"""
Resample a set of points M times, adding noise according to their covariance matrices.
Returns
-------
x_samples, y_samples : np.array
Every column j, is x[j] redrawn M times.
Has M rows, and every row is a realization of xs or ys.
"""
#... | 5609efcf6ba42fc2a059d308e8391b6057de3a16 | 29,721 |
def k_folds_split(raw_indexes, n_splits, labels=default_pars.validation_pars_labels,
shuffle=default_pars.validation_pars_shuffle, random_state=default_pars.random_state,
return_original_indexes=default_pars.validation_pars_return_original_indexes):
"""Splits a raw set of indexes... | 77394ca5d345d97423abaa0fe421e50cb0017762 | 29,722 |
def element_wise_entropy(px):
"""
Returns a numpy array with element wise entropy calculated as -p_i*log_2(p_i).
Params
------
px (np.array)
Array of individual probabilities, i.e. a probability vector or distribution.
Returns
-------
entropy (np.array)
Array of element... | 7637cac96e51ce6b89a395c306a6104e77bcef0d | 29,723 |
def score_page(preds, truth):
"""
Scores a single page.
Args:
preds: prediction string of labels and center points.
truth: ground truth string of labels and bounding boxes.
Returns:
True/false positive and false negative counts for the page
"""
tp = 0
fp = 0
fn = ... | 25b3d4280db734ded586eb627fe98d417164601d | 29,724 |
import re
def _validate_eida_token(token):
"""
Just a basic check if the string contains something that looks like a PGP
message
"""
if re.search(pattern='BEGIN PGP MESSAGE', string=token,
flags=re.IGNORECASE):
return True
return False | 746fbd011b38abab43be983a1a054505526dcf78 | 29,725 |
def dn_histogram_mode_5(y, y_min, y_max):
"""
Mode of z-scored distribution (5-bin histogram)
"""
return histogram_mode(y, y_min, y_max, 5) | 0dc10f46136e60e2523f4ca79449f18aaedd4854 | 29,726 |
def _make_element(spec, parent, attributes=None):
"""Helper function to generate the right kind of Element given a spec."""
if (spec.name == constants.WORLDBODY
or (spec.name == constants.SITE
and (parent.tag == constants.BODY
or parent.tag == constants.WORLDBODY))):
return _Attac... | 7635e8380e8238541544495f250e78a5da3ad441 | 29,727 |
import argparse
def create_hook_mock() -> TmTcHookBase:
"""Create simple minimal hook mock using the MagicMock facilities by unittest
:return:
"""
tmtc_hook_base = TmTcHookBase()
tmtc_hook_base.add_globals_pre_args_parsing = MagicMock(return_value=0)
tmtc_hook_base.add_globals_post_args_parsin... | 56880c4cf724ae129ef53450e567b4eafd566703 | 29,728 |
def read_sounding(timestamp, index_col=0, caching=True, **kws):
"""read wyoming sounding with optional caching (default)"""
if caching:
if in_cache(timestamp, **kws):
data = cache_read(timestamp, **kws)
# TODO: index col swapping
return data
skiprows = (0,1,2,3,4,... | 2dc2ba1d6d9af45728752817205b951213f4817e | 29,729 |
def nlf_css(parser, token):
"""Newsletter friendly CSS"""
args = token.split_contents()
css = {}
css_order = []
for item in args[1:]:
tag, value = item.split("=")
tag, value = tag.strip('"'), value.strip('"')
css[tag] = value
css_order.append(tag)
nodelist = parse... | eadf74cdd6e58fb4e1551f1b951ad74226e175c2 | 29,730 |
def data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_peak_information_rate_put(uuid, tapi_common_capacity_value=None): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_peak_information_rate_put
create... | c9ee5c8751e8424732f066598525a44d1c66d1c5 | 29,731 |
import logging
def _get_default_dataset_statistics(
statistics: statistics_pb2.DatasetFeatureStatisticsList
) -> statistics_pb2.DatasetFeatureStatistics:
"""Gets the DatasetFeatureStatistics to use for validation.
If there is a single DatasetFeatureStatistics, this function returns that. If
there are multi... | 8466e67c9ea5d795ea9b6c16c637b9a55048056c | 29,732 |
from typing import Callable
from re import A
def foldr(_folder: Callable[[A, B], B], _init: B, _linked_list: LinkedList[A]) -> B:
""" foldr """
if _linked_list.content is None:
return _init
else:
head = _linked_list.content[0]
tail = _linked_list.content[1]
return _folder(h... | 93aa3749442d8028dd115619e358e8fcf40ada46 | 29,733 |
def get_per_lane_sample_dist_plot(sample_data: pd.DataFrame) -> dict:
"""
A function for returing sample distribution plots
:params sample_data: A Pandas DataFrame containing sample data
:returns: A dictionary containing sample distribution plots
"""
try:
lane_plots = dict()
for... | 143094fc909ac9044c5986c958cff79e9e218414 | 29,734 |
def mark_volatile(obj):
"""DEPRECATED(Jiayuan Mao): mark_volatile has been deprecated and will be removed by 10/23/2018; please use torch.no_grad instead."""
return stmap(_mark_volatile, obj) | 2e299889fe7982069fb5987f6af0e56ae365a9ee | 29,735 |
def list_keys(bucket):
"""
Lists all the keys in a bucket.
:param bucket: (string) A bucket name.
:return: (string list) Keys in the bucket.
"""
_check_bucket(bucket)
bucket_path = _bucket_path(bucket)
keys = []
for key_path in bucket_path.iterdir():
keys.append(key_path.name... | 0a84c72165cf76970221974196911853d0db027a | 29,736 |
def h6(content, accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: str="", translate... | c68a5ba229643571ce49e535b32e99580443e56c | 29,737 |
def extractUniversesWithMeaning(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Angel of Death' in item['title']:
return buildReleaseMessageWithType(item, 'Angel of Death', vol, chp, frag=frag, ... | 0a00cc344bdb1d5a2498252f529536b2c58f2825 | 29,738 |
def get_provenance(message):
"""Given a message with results, find the source of the edges"""
prov = defaultdict(lambda: defaultdict(int)) # {qedge->{source->count}}
results = message['message']['results']
kg = message['message']['knowledge_graph']['edges']
edge_bindings = [ r['edge_bindings'] for r... | 1f6dfe9e48da49b72cb55f3f949146db3db164f2 | 29,739 |
def bricklinkColorToLEGO(colornum):
"""
Get the LEGO equivalent to a bricklink color number if it exists
:param colornum:
:return:
"""
default = {"name": "Unknown", "Lego": colornum, "BrickLink": colornum}
if colornum < 0:
return default
for color in color_data:
if colo... | 9ed77c271168025c5864a28624470c26ae3a0a9e | 29,740 |
def bounds(gdf):
"""Calculates the bounding coordinates (left, bottom, right, top) in the given GeoDataFrame.
Args:
gdf: A GeoDataFrame containing the input points.
Returns:
An array [minx, miny, maxx, maxy] denoting the spatial extent.
"""
bounds = gdf.to... | 48242e870edd1db9b1191518c4b9ba7433420610 | 29,741 |
from typing import OrderedDict
def controls_receptor():
"""Control for receptor network.
TODO: remain to be added to manuscript
"""
config = FullConfig()
config.data_dir = './datasets/proto/standard'
config.max_epoch = 100
config.train_pn2kc = False
config.receptor_layer = True
... | b01bb691c697a0efad2ebfef0a688021cda39598 | 29,742 |
def powerport_get_row_boot_strap (port_id, raw = False):
""" Get boot strapping setting
"""
result = powerport_get_port_status (port_id + 24, "pdu", raw)
state = result.pop ("Port State", None)
if (state):
result["Boot Strap"] = "Normal" if (state == "Off") else "Network"
... | 00d41e0a505c6d88ce44c4a701865556ccff0f89 | 29,743 |
def inv_ltri(ltri, det):
"""Lower triangular inverse"""
inv_ltri = np.array((ltri[2], -ltri[1], ltri[0]), dtype=ltri.dtype) / det
return inv_ltri | 539bbcec02286f991d5cc426ebe631d1cbe0b890 | 29,744 |
def create_dummy_review(user, title='Review 1'):
"""Simple function for creating reviews of a user"""
review = Review.objects.create(
reviewer=user,
title=title,
rating=5,
summary='This is my first review!!!',
ip='190.190.190.1',
... | ffa9ad526072fa48eff513f9b6d10628e700a266 | 29,745 |
import os
import time
def checkOneFile(path):
"""Process one file and return analysis result as element object"""
# Create output elementtree object
if config.inputRecursiveFlag or config.inputWrapperFlag:
# Name space already declared in results element, so no need to do it
# here
... | 3242809b99bd71afbec2d3a9f27e4dabeb1a920d | 29,746 |
def check_user(update):
"""verify that a user has signed up"""
user = update.message.from_user
if db.tel_get_user(user.id) is not None:
return True
else:
return False | 6654ba29d15158b63f78cea16d796f26f9199b07 | 29,747 |
def acmg():
"""Calculate an ACMG classification from submitted criteria."""
criteria = request.args.getlist("criterion")
classification = get_acmg(criteria)
return jsonify(dict(classification=classification)) | 83e70afcd986ca8b7fe0e442130615cff2e84a1b | 29,748 |
def import_bin(filename, **kwargs):
"""
Read a .bin file generated by the IRIS Instruments Syscal Pro System and
return a curated dataframe for further processing. This dataframe contains
only information currently deemed important. Use the function
reda.importers.iris_syscal_pro_binary._import_bin... | 2ec4d3febad7eae08db4b2df5b4552459b627dd9 | 29,749 |
def get_messages(receive_address, send_address, offset, count):
""" return most recent messages from offset to count from both communicators """
conn = connect_db()
cur = conn.cursor()
cur.execute(
"(SELECT * FROM message WHERE (recvAddress=%s AND sendAddress=%s) ORDER by id DESC LIMIT %s OFFSET... | 13e46a46a4bc15931de77374249ae701f5b65c1a | 29,750 |
def get_test_node(context, **kw):
"""Return a Node object with appropriate attributes.
NOTE: The object leaves the attributes marked as changed, such
that a create() could be used to commit it to the DB.
"""
db_node = db_utils.get_test_node(**kw)
# Let DB generate ID if it isn't specified expli... | 6ce089c0d6643f2c58633ce846a4a46d2c9e5732 | 29,751 |
from typing import OrderedDict
def GlobalAttributes(ds, var):
"""
Creates the global attributes for the netcdf file that is being written
these attributes come from :
https://www.unidata.ucar.edu/software/thredds/current/netcdf-java/metadata/DataDiscoveryAttConvention.html
args:
runinfo Table containing all t... | b5fcf1627f8c23964a1ec2fe4fa657a60cb8efa3 | 29,752 |
from typing import List
from typing import Tuple
def extend_path(path: List[Tuple[MerkleTree, hash.HashTriple]],
tree: MerkleTree,
) -> List[List[Tuple[MerkleTree, hash.HashTriple]]]:
"""Extend path if possible."""
paths = []
for t in (tree.left, tree.right):
if t i... | 294ea5b1e2b844065a2fd962768f1b6501b4513f | 29,753 |
import os
def main(argv):
"""Cleans the generated Amplitude binary assets.
Returns:
Returns 0 on success.
"""
projectPath = common.get_o3de_project_path()
try:
common.clean_flatbuffer_binaries(
common.get_conversion_data(os.path.join(
projectPath, "soun... | 3a7a322716a6240fcea25c6fa93620b42e579127 | 29,754 |
def calculate_debt(runsdim, runstot, low_bound, high_bound):
""" calculates tech debt and bugs """
debt_indexes = np.random.uniform(low_bound, high_bound, runstot)
debt_indexes = runsdim * debt_indexes
debt_indexes = np.rint(debt_indexes)
return np.int64(debt_indexes) | 697e2520c019ca8d46cdfebf092207e17a95ee0e | 29,755 |
def load_dictionary(loc):
"""
Load a dictionary
"""
with open(loc, 'r') as f:
worddict = pkl.load(f)
return worddict | f659ebb94410e02bbeab51b04b60e727cc749641 | 29,756 |
import json
def get_specific_post(post_id):
"""Get specific post"""
value = posts.get(post_id)
if not value:
return json.dumps({"error": "Post Not Found"}), 404
return json.dumps(value), 200 | 86ca2ee5847c3e7043dbd52f1a713477ea6191c5 | 29,757 |
def first_half(dayinput):
"""
first half solver:
"""
houses = { (0,0): 1 }
coords = [0, 0]
for h in dayinput:
coords = change_coords(h, coords)
home = (coords[0], coords[1])
if houses.get(home, None):
houses[home] += 1
else:
houses[home] = ... | c0ed5c66c3f259257e14c2c6bc4daec406028135 | 29,758 |
def compute_cluster_metrics(neighbor_mat, max_k=10, included_fovs=None,
fov_col='SampleID'):
"""Produce k-means clustering metrics to help identify optimal number of clusters
Args:
neighbor_mat (pandas.DataFrame):
a neighborhood matrix, created from create_neighb... | bc13b2eb1b4bd9824e4134395ed5d31a9cfa7cb0 | 29,759 |
def map_flat_line(x, y, data, linestyles='--', colors='k', ax=None, **kwargs):
"""Plot a flat line across every axis in a FacetGrid.
For use with seaborn's map_dataframe, this will plot a horizontal or
vertical line across all axes in a FacetGrid.
Parameters
----------
x, y : str, float, or li... | dd46189458ee0da79785d2c9119a41969dc1357e | 29,760 |
from sys import api_version
def validate_api_version():
"""
A decorator that validates the requested API version on a route
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
req_api_version = kwargs.get("api_version", 1)
if req_api_version > a... | 317894ea92d6f0815a2bdaad8d8eb2776251d060 | 29,761 |
def build_dictionary(sentences, size):
"""
Create dictionary containing most frequent words in the sentences
:param sentences: sequence of sentence that contains words
Caution: the sequence might be exhausted after calling this function!
:param size: size of dictionary you want
:return: dict... | 24a998d9df539b44c2dad1ffabb2737a189e7a3e | 29,762 |
import re
def simplestr(text):
"""convert a string into a scrubbed lower snakecase. Intended use is converting
human typed field names deterministically into a string that can be used for a
key lookup.
:param text: type str text to be converted
"""
text = text.strip()
text = text.replace(... | b030c50cd300dd97d69a9d2b8421892bb1f0c23a | 29,763 |
def lti_launch(request):
"""
This method is here to build the LTI_LAUNCH dictionary containing all
the LTI parameters and place it into the session. This is nessesary as we
need to access these parameters throughout the application and they are only
available the first time the application loads.
... | a65d4395095e36f4e27ae802ae7c2635f211521e | 29,764 |
import os
import subprocess
def compress_file(filename):
"""
Compresses file with gzip
:param filename: path to file to be compressed
:type filename: str
:rtype: str or None
"""
if not os.path.isfile(filename):
msg = "File not found or cannot be accessed: '{f}'".format(f=filename)... | c082cef5c38540f0e6daec1c0b079e1d551ef323 | 29,765 |
def cartesian_to_altaz(x):
""" Converts local Cartesian coordinates to Alt-az,
inverting altaz_to_cartesian
"""
x, y, z = x
return np.arcsin(z), np.arctan2(-y, x) | e585fb57a9509fab277e15f08e76e1367c8334d4 | 29,766 |
import sys
import re
import subprocess
def main():
"""Main function."""
argv = sys.argv
assert len(argv) == 4, 'Invalid arguments'
global kernel_path
global install_path
global arch
kernel_path = argv[1]
install_path = argv[2]
arch = argv[3]
# avoid the conflic with the 'ne... | 9f590599152325c72bb46c0a3befa15f047bf4be | 29,767 |
def discount_opex(opex, global_parameters, country_parameters):
"""
Discount opex based on return period.
Parameters
----------
cost : float
Financial cost.
global_parameters : dict
All global model parameters.
country_parameters : dict
All country specific parameter... | 6e079ffc9accc7679bada3b31d07748c93d4b18c | 29,768 |
import os
import logging
def load_dataset_from_path(path):
"""
Build a dataset in the form of a pandas dataframe where
the schema is: <LYRIC_PATH, EMOTION>
"""
rows = list()
# Traverse the dataset directory
for root, dirs, files in os.walk(path):
for f in files:
fields = f.split('_')
... | 73dfd29b65c09dd2f6f96bd8c19e95c9add67c93 | 29,769 |
import torch
def permute(x, perm):
"""Permutes the last three dimensions of the input Tensor or Array.
Args:
x (Tensor or Array): Input to be permuted.
perm (tuple or list): Permutation.
Note:
If the input has fewer than three dimensions a copy is returned.
"""
if is_tens... | 513164bfc6d25a82f2bfeba05427bd69c8df181c | 29,770 |
def is_hr_between(time: int, time_range: tuple) -> bool:
"""
Calculate if hour is within a range of hours
Example: is_hr_between(4, (24, 5)) will match hours from 24:00:00 to 04:59:59
"""
if time_range[1] < time_range[0]:
return time >= time_range[0] or time <= time_range[1]
return time_... | 70d874f0a5dee344d7638559101fc6be2bcca875 | 29,771 |
def calc_Topt(sur,obs,Tvals,objfunc='nse'):
"""
Function to calibrate the T parameter using a brute-force method
Args: sur (pandas.Series): pandas series of the surface soil moisture
obs (pandas.Series): pandas series of the soil moisture at layer x to calibrate
Tvals (list,tuple,set... | 39df23619ea364cbf477f02665a86e72cef86e11 | 29,772 |
def share_file(service, file_id):
"""Make files public
For a given file-id, sets role 'reader' to 'anyone'. Returns public
link to file.
:param: file_id (string)
:return: (string) url to shared file
"""
permission = {
'type': "anyone",
'role': "reader",
... | 70a1132667663fa85cf7f00fd3ced2fb81b03cc4 | 29,773 |
import os
def getlocal():
"""Get the path to the local directory where OCRopus data is
installed. Checks OCROPUS_DATA in the environment first,
otherwise defaults to /usr/local/share/ocropus."""
local = os.getenv("OCROPUS_DATA") or modeldir
return local | a1cef507e92d0d39ab50316f749c0e377543d2b9 | 29,774 |
import data
def convert_image_for_visualization(image_data, mean_subtracted=True):
"""
Convert image data from tensorflow to displayable format
"""
image = image_data
if mean_subtracted:
image = image + np.asarray(data.IMAGE_BGR_MEAN, np.float32)
if FLAGS.image_channel_order == 'BGR':
image = ima... | 9fe138051f7886d3c3e8e70e75f23b636a1ccd02 | 29,775 |
def mld(returns_array, scale=252):
"""
Maximum Loss Duration
Maximum number of time steps when the returns were below 0
:param returns_array: array of investment returns
:param scale: number of days required for normalization. By default in a year there are 252 trading days.
:return: MLD
"""... | 2d78d76c1456ebb4df606a9450f45e47b5e49808 | 29,776 |
from typing import Union
from typing import List
from typing import Dict
from typing import Any
def json2geodf(
content: Union[List[Dict[str, Any]], Dict[str, Any]],
in_crs: str = DEF_CRS,
crs: str = DEF_CRS,
) -> gpd.GeoDataFrame:
"""Create GeoDataFrame from (Geo)JSON.
Parameters
----------
... | de9e956a79821611d6f209e9b206d3c15e24708e | 29,777 |
from typing import Optional
from typing import List
from typing import Tuple
from typing import Any
import logging
def build_block_specs(
block_specs: Optional[List[Tuple[Any, ...]]] = None) -> List[BlockSpec]:
"""Builds the list of BlockSpec objects for SpineNet."""
if not block_specs:
block_specs = SPIN... | 6046b2ee33d15254ff6db989b63be4276d0bad19 | 29,778 |
def est_agb(dbh_mat, sp_list):
"""
Estimate above ground biomass using the allometric equation in Ishihara et al. 2015.
"""
# wood density
wd_list = [
dict_sp[sp]["wood_density"]
if sp in dict_sp and dict_sp[sp]["wood_density"]
else None
for sp in sp_list
]
#... | ab0d80408bc9d216e387565cde3d6e758f738252 | 29,779 |
from typing import Optional
def parse_json_and_match_key(line: str) -> Optional[LogType]:
"""Parse a line as JSON string and check if it a valid log."""
log = parse_json(line)
if log:
key = "logbook_type"
if key not in log or log[key] != "config":
log = None
return log | c4efa103730ac63d2ee6c28bba2de99a450f6b8d | 29,780 |
def nearDistance(img, centers):
"""
Get the blob nearest to the image center, which is probably the blob for cells, using euclidian distance.
Parameters: img, image with labels defined;
centers, list of label' centers of mass.
Returns: nearestLabel, label nearest to the image center.
... | 6414d30cb1d591b5bf6f8101c084823f92605f1e | 29,781 |
from flask_swagger import swagger
import json
def create_app(config_object=ProdConfig):
"""This function is an application factory.
As explained here: http://flask.pocoo.org/docs/patterns/appfactories/.
:param config_object: The configuration object to use.
"""
app = Flask(__name__.split('.')[0]... | b9214ee822c8012a5273cf72daa04f33b9b99539 | 29,782 |
def get_f1_dist1(y_true, y_pred, smooth=default_smooth):
"""Helper to turn the F1 score into a loss"""
return 1 - get_f1_score1(y_true, y_pred, smooth) | c200bbe75f7013a75b2801fbb7de4cbf588bb873 | 29,783 |
def get_date_info_for_pids_tables(project_id, client):
"""
Loop through tables within all datasets and determine if the table has an end_date date or a date field. Filtering
out the person table and keeping only tables with PID and an upload or start/end date associated.
:param project_id: bq name of p... | e75dd8176583673e8ee6e89a8c75312fe06216bc | 29,784 |
def preprocess_sent(sentence):
"""input: a string containing multiple sentences;
output: a list of tokenized sentences"""
sentence = fill_whitespace_in_quote(sentence)
output = tokenizer0(sentence)
# tokens = [token.text for token in tokenizer.tokenize(sentence)]
tokens = list(map(lambda x: x.te... | eddaa08e3b0a8ad43f410541793f873449101904 | 29,785 |
import os
def save_attention_visualization(source_img_path, att_map, dest_name):
"""
Visualize the attention map on the image and save the visualization.
"""
img = cv2.imread(source_img_path) # cv2.imread does auto-rotate
# downsample source image
img = downsample_image(img)
img_h, img_w,... | 0e91320054f2084c3dfc3228951224b882c69af6 | 29,786 |
def average_slope_intercept(image, lines):
"""
This function combines line segments into one or two lane lines
"""
left_fit = [] # contains the coordinate of on the line in the left
right_fit = []
if lines is None:
return None
# now loop through very line we did previously
f... | b6dbd56555d5c9d71905b808db20e4f8be6de15f | 29,787 |
def build_upper_limb_roll_jnts(main_net, roll_jnt_count=3):
"""Add roll jnts, count must be at least 1"""
increment = 1.0/float(roll_jnt_count)
def create_joints(jnt_a, jnt_b, net, lower_limb=False, up_axis='-Z'):
"""
:param jnt_a: Start Joint
:param jnt_b: End Joint
:param... | 0985a33a9fac3b218042cac4d1213df13f606464 | 29,788 |
import os
import json
import re
def upload():
"""UEditor文件上传接口
config 配置文件
result 返回结果
"""
mimetype = 'application/json'
result = {}
action = request.args.get('action')
# 解析JSON格式的配置文件
with open(os.path.join(app.static_folder, 'ueditor', 'php',
'config.... | 435ad167be5235bea594e709025ed66c7c84f156 | 29,789 |
def create_one(**kwargs):
""" Create a Prediction object with the given fields.
Args:
Named arguments.
date: Date object. Date of the predicted changes.
profitable_change: Decimal. Predicted profitable change in pips.
instrument: Instrument object... | d71d14445c5e53c032b529652f3ed5fb12df6544 | 29,790 |
def get_lane_lines(img_parms):
"""
Main jumping into function
"""
titles = list()
images = list()
cmaps = list()
print("Starting Lane Detection")
print("************************")
img_in = mpimg.imread(img_parms["image"])
if debug >= 3:
make_save_dir(img_parms["... | 37e9b516a8314f99e8cd9b0eb3fd2020f418ce30 | 29,791 |
import math
def get_distance_wgs84(lon1, lat1, lon2, lat2):
"""
根据https://github.com/googollee/eviltransform,里面的算法:WGS - 84
:param lon1: 经度1
:param lat1: 纬度1
:param lon2: 经度2
:param lat2: 纬度2
:return: 距离,单位为 米
"""
earthR = 6378137.0
pi180 = math.pi / 180
arcLatA = lat1 * p... | 8da67a3a690ff0cb548dc31fb65f3b2133fa3e3f | 29,792 |
def make_uuid(ftype, size=6):
"""
Unique id for a type.
"""
uuid = str(uuid4())[:size]
return f'{ftype}-{uuid}' | 3cb779431e5cb452f63f8bab639e9a437d7aa0f9 | 29,793 |
def region_of_interest(img, vertices):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
`vertices` should be a numpy array of integer points.
Args:
img (image): Mas... | bd22cd8b6642dd820e786f88d54c63f4811c5221 | 29,794 |
import pytz
def _adjust_utc_datetime_to_phone_datetime(value, phone_tz):
"""
adjust a UTC datetime so that it's comparable with a phone datetime
(like timeEnd, modified_on, etc.)
returns a timezone-aware date
"""
phone_tz = _soft_assert_tz_not_string(phone_tz)
assert value.tzinfo is None... | 48a875af1082d1538c6bf09905afacc411e1408c | 29,795 |
def cache_function(length=CACHE_TIMEOUT):
"""
A variant of the snippet posted by Jeff Wheeler at
http://www.djangosnippets.org/snippets/109/
Caches a function, using the function and its arguments as the key, and the return
value as the value saved. It passes all arguments on to the function, as
... | 81c2574621e81c485712e456f9b34c638f47cdf8 | 29,796 |
import os
import yaml
import logging
def get_yaml_config(file_name):
"""Return a dict parsed from a YAML file within the config directory.
Args:
file_name: String that defines the config file name.
Returns:
A dict with the parsed YAML content from the config file or
an empty dict... | e1f484322b7e3eb74a4ef204309dc8b22563f40e | 29,797 |
def plot_contour_1d(X_grid, Y_grid, data,
xlabel, ylabel, xticks, yticks,
metric_bars, fillblack=True):
"""Create contour plots and return the figure and the axes."""
n = len(metric_bars)
assert data.shape == (*X_grid.shape, n), (
"data shape must be (X, Y, ... | 2eb534ebe841a96386976fa477ec357b5ea07ea7 | 29,798 |
def dataset_to_rasa(dataset: JsonDict) -> JsonDict:
"""Convert dataset to RASA format, ignoring entities
See: "https://rasa.com/docs/nlu/dataformat/"
"""
return {
"rasa_nlu_data": {
"common_examples": [
{"text": text, "intent": intent, "entities": []}
... | 64a9b6291b0a2d2af297e3fb0ca214b8d65792f4 | 29,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.