content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
def get_current_time():
"""Return timestamp for current system time in UTC time zone.
Returns
-------
datetime
Current system time
"""
return datetime.datetime.utcnow() | 606761fa1aabe0b9d0d1682b978efbae1a524fa3 | 33,500 |
def calculate_average(result):
"""Calculates the average package size"""
vals = result.values()
if len(vals) == 0:
raise ValueError("Cannot calculate average on empty dictionary.")
return sum(vals)/float(len(vals)) | ea4b66b41533b0e8984b5137c39c744eec9d3e1f | 33,501 |
def score_vectore(vector):
"""
:type vector: list of float
:return:
"""
x = 0.
y = 0.
for i in range(0, len(vector)):
if i % 2 == 0:
if vector[i] > 12:
x += vector[i]
else:
y += vector[i] + min(vector[i-1], vector[i])
return x, y | 8fc60cb3cec65d5a3b8f0fea62777739e17249a4 | 33,502 |
def loudness_contour_equivalence(mean_loudness_value, phon_ref_value):
""" Function that serves for the validation of the hearing model presented in Annex F of ECMA-74.
Parameters
----------
Returns
-------
"""
# Conversion to phons of the loudness result that is in sones.
phon_loudne... | 410d6469caad75a2d9387ada9868a747a457dd86 | 33,503 |
import threading
from sys import path
def sound():
"""
Play a sound
:header sound_name: is the filename with the extension (must be inside the sounds folder)
"""
check_api_key()
sound_name = get_body('sound_name')
threading.Thread(target=playsound(path + "/sounds/" + sound_name)).start(... | 82ac09c32d7637d6c14556cc976a25bb85f31f05 | 33,504 |
def _compound_register(upper, lower):
"""Return a property that provides 16-bit access to two registers."""
def get(self):
return (upper.fget(None) << 8) | lower.fget(None)
def set(self, value):
upper.fset(None, value >> 8)
lower.fset(None, value)
return property(get, set) | 00f315cc4c7f203755689adb5004f152a8b26823 | 33,505 |
import os
def get_file_extension(path: str) -> str:
"""Returns extension of the file"""
return os.path.basename(path).split(".")[-1] | fc883ba45b8c7dbeb38b18c3a730c715dcf933a4 | 33,506 |
def get_joining_type_property(value, is_bytes=False):
"""Get `JOINING TYPE` property."""
obj = unidata.ascii_joining_type if is_bytes else unidata.unicode_joining_type
if value.startswith('^'):
negated = value[1:]
value = '^' + unidata.unicode_alias['joiningtype'].get(negated, negated)
... | ad2f590658c927a91ef5d90ac09d5b927e2091f3 | 33,507 |
from typing import List
def select_record_fields(
record: dict,
fields: List[str]) -> dict:
"""
Selects a subset of fields from a dictionary
"""
return {k: record.get(k, None) for k in fields} | 4b56ba4bc683eb8d49540ccb8de79c08b900e7c8 | 33,508 |
def to_TProfile2D(
fName,
fTitle,
data,
fEntries,
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fTsumwy,
fTsumwy2,
fTsumwxy,
fTsumwz,
fTsumwz2,
fSumw2,
fBinEntries,
fBinSumw2,
fXaxis,
fYaxis,
fZaxis=None,
fScalefactor=1.0,
fZmin=0.0,
fZmax=0.... | 6886a90bc4e134d03f255c2fcec211dbdbd435b0 | 33,509 |
def decode_check(string: str, digestfunc=sha256d_32) -> bytes:
"""
Convert base58 encoded string to bytes and verify checksum.
"""
result = decode(string)
return verify_checksum(result, digestfunc) | e3cdca3d66a2822cf6d47756959f136c84bcae65 | 33,510 |
import pandas
def label_by_wic(grasp_wic, exclude_C0=False):
"""Label each grasp by the whiskers it contains
grasp_wic : DataFrame
Index: grasp keys. Columns: whisker. Values: binarized contact.
exclude_C0 : bool
If False, group by all whiskers.
If True, ignore C0, and gr... | 0f1e552c68be0b77bad442b2432e071a74db4947 | 33,511 |
def selectBestFeature(dataSet: list):
"""
计算信息增益,挑选最好的特征值
:param dataSet: 数据集
:return:
"""
# 不使用最后一列标签列
best_feature_idx = 0
gain = float('-inf')
for feature_idx in range(len(dataSet[0])-1):
gain_tmp = calcOneFeatureGain(dataSet, feature_idx)
if gain_tmp > gain:
... | ced59e8748eb12a17951fb511c7cc6b8d5f88555 | 33,512 |
from typing import Callable
import json
def __interact_instances(client, action: Callable, status: str) -> dict:
"""
Interacts with the instances. It executes the callable from action.
:param client: Sagemaker boto3 client.
:param action: a callable (e.g. client.start_notebook_instance).
:param st... | f067ce6d4d32718e6d25edb735534b3427eb9cc6 | 33,513 |
def _chordfinisher(*args, **kwargs):
"""
Needs to run at the end of a chord to delay the variant parsing step.
http://stackoverflow.com/questions/
15123772/celery-chaining-groups-and-subtasks-out-of-order-execution
"""
return "FINISHED VARIANT FINDING." | b68d09e755c2da468b98ab0466821770d2f7f4a7 | 33,514 |
def plot_reg_path(model, marker='o', highlight_c="orange", include_n_coef=False, figsize=None, fontsize=None):
"""Plots path of an L1/L2 regularized sklearn.linear_model.LogisticRegressionCV.
Produces two adjacent plots.
The first is a plot of mean coefficient values vs penalization strength.
The second... | f868bf2ef5375598e29675b42234a5be470235f0 | 33,515 |
def create_object_count(app=None):
"""fetches all models of the passed in app and returns a
dict containg the name of each class and the number of instances"""
if app:
models = ContentType.objects.filter(app_label=app)
result = []
for x in models:
modelname = x.model
... | a0697f9847e3a200fd235cbb000c7d67e711f9fd | 33,516 |
def unique_name(prefix: str, collection) -> str:
"""
Prepares a unique name that is not
in the collection (yet).
Parameters
----------
prefix
The prefix to use.
collection
Name collection.
Returns
-------
A unique name.
"""
if prefix not in collection:
... | 8438588bd17e097ffc5bbe7b88f4c2aba2363250 | 33,517 |
async def get_pic(image_type: str, group_id: int, sender: int) -> list:
"""
Return random pics message
Args:
image_type: The type of picture to return
image type list:
setu: hPics(animate R-15)
setu18: hPics(animate R-18)
real: hPics(real ... | 37f06676b508503ba54fab37e1e7418df0d144bc | 33,518 |
def dispatch(req):
"""run the command specified in req.args; returns an integer status code"""
err = None
try:
status = _rundispatch(req)
except error.StdioError as e:
err = e
status = -1
ret = _flushstdio(req.ui, err)
if ret:
status = ret
return status | 1874580fff23796b025fc2cd2ecce9f21a5af692 | 33,519 |
def get_settings(from_db=False):
"""
Use this to get latest system settings
"""
if not from_db and 'custom_settings' in current_app.config:
return current_app.config['custom_settings']
s = Setting.query.order_by(desc(Setting.id)).first()
app_environment = current_app.config.get('ENV', 'p... | 2154122bcdde3e0bc023103ed825d76234d489c1 | 33,520 |
def get_currency_crosses_list(base=None, second=None):
"""
This function retrieves all the available currency crosses from Investing.com and returns them as a
:obj:`dict`, which contains not just the currency crosses names, but all the fields contained on
the currency_crosses file is columns is None, ot... | da6588be01510c96d6e1dc85c82d7beed877002b | 33,521 |
def define_git_repo(*, name: 'name',
repo, treeish=None):
"""Define [NAME/]git_clone rule."""
(define_parameter.namedtuple_typed(GitRepoInfo, name + 'git_repo')
.with_default(GitRepoInfo(repo=repo, treeish=treeish)))
relpath = get_relpath()
@rule(name + 'git_clone')
@rule... | 78dcd536c306020d2ffd6fe4355992b10fb0d9ad | 33,522 |
import random
import multiprocessing
import concurrent
import tqdm
def solve_lineage_instance(
_target_nodes,
prior_probabilities=None,
method="hybrid",
threads=8,
hybrid_cell_cutoff=200,
hybrid_lca_cutoff=None,
time_limit=1800,
max_neighborhood_size=10000,
seed=None,
num_iter=... | 6babbb6c071a17f9a5bfe2fbe402d1cb72a6c330 | 33,523 |
def split_in_chunks(
data,
chunk_size,
train_size=None,
val_size=None,
test_size=None,
shuffle=True,
seed=None,
):
"""Split data into train-test, where chunks of data are held together
Assume `data` is a list of numpy arrays
"""
chunks = []
for rollout in data:
f... | fad3ebdc99731ad95ff0200e70e2e64d4a9acdc8 | 33,524 |
import warnings
import os
import joblib
def fetch_googlenet_architecture(caffemodel_parsed=None,
caffemodel_protobuffer=None):
"""Fetch a pickled version of the caffe model, represented as list of
dictionaries."""
default_filename = os.path.join(GOOGLENET_PATH, 'bvlc_goog... | 4605132705b27fb118b3e558773d1a3684ea84db | 33,525 |
import re
def check_id(id):
"""
Check whether a id is valid
:param id: The id
:return: The result
"""
return bool(re.match(r"^[a-f0-9]{24}$", id)) | f336d34de12f4f5520d4c88a838ebdb396857d2b | 33,526 |
def totaled_tbr_no_lgtm(cc, sql_time_specification):
"""Counts the number of commits with a TBR that have not been lgtm'ed
in a given timeframe
Args:
cc(cursor)
sql_time_specification(str): a sql command to limit the dates of the
returned results
Return:
count(i... | 25666c4f741f6bdd2c8358468a54c6e261cc57e3 | 33,527 |
import unicodedata
def normalize_text(text: str) -> str:
"""Normalize the text to remove accents
and ensure all the characters are valid
ascii symbols.
Args:
text : Input text
Returns:
Output text
"""
nfkd_form = unicodedata.normalize("NFKD", text)
only_ascii = nfkd_f... | fa1c5362caa9946e79152f9e14ccf2131754f258 | 33,528 |
def rotate_y(x, z, cosangle, sinangle):
"""3D rotaion around *y* (roll). *x* and *z* are values or arrays.
Positive rotation is for positive *sinangle*. Returns *xNew, zNew*."""
return cosangle*x + sinangle*z, -sinangle*x + cosangle*z | 0a1b28548f771b9ca8cec29ba4060be7b0919182 | 33,529 |
import base64
import html
def json_file_upload(contents, file_names, dates):
"""
Reads a JSON file from disk and saves it in the default path
The goal is to keep that file over there for the Draw JSON
Function to read and draw it.
Args:
ontents, file_names, dates: inputs from the Dash UI... | 88d06880fb4e102260ef7df6f931ee541d8c98fc | 33,530 |
from ..cov import Covariance
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
from mpl_toolkits.axes_grid1 import make_axes_locatable
import copy
def plot_cov(cov, info, exclude=(), colorbar=True, proj=False, show_svd=True,
show=True, verbose=None):
"""Plot Covariance data.
... | ca3a4c3c954e3f676c0e6229be9243e7be31f4f2 | 33,531 |
import getpass
def ask_credential(login=None, password=None):
""" Ask for a login and a password when not specified.
Parameters
----------
login: str, default None
a login.
password: str, defualt None
a password.
Returns
-------
login: str, default None
a logi... | 55ba7425cd2016212c897345c21b6d24ce3d8578 | 33,532 |
import numpy
def zeros_like(a, dtype=None, bohrium=None):
"""
Return an array of zeros with the same shape and type as a given array.
With default parameters, is equivalent to ``a.copy().fill(0)``.
Parameters
----------
a : array_like
The shape and data-type of `a` define these same ... | 6d831ead77b55229121f85d005a426e86565353a | 33,533 |
import random
def rand():
"""
Returns a random number.
"""
return random.random() | efad85c9f169d39358ed034a29f166df175d0ea7 | 33,534 |
def read_counters():
"""read_counters()
Get current counts and reset counters.
:rtype: list(int)
:raises PapiInvalidValueError: One or more of the arguments is invalid
(this error should not happen with PyPAPI).
:raises PapiSystemError: A system or C library call failed inside PAPI.
"... | d82c3b186aadc0b61e848a838549cf8393fa1010 | 33,535 |
def is_monotonic_decreasing(series_or_index):
"""
Return boolean scalar if values in the object are
monotonic_decreasing.
Returns
-------
Scalar
"""
return check_monotonic(series_or_index, decreasing=True, strict=False) | 3b5c2f989d53cc96fc6e9131cb2b3a78945befaa | 33,536 |
def mprint(m,fmt):
"""
This function will print a VSIPL matrix or vector suitable for pasting into Octave or Matlab.
usage: mprint(<vsip matrix/vector>, fmt)
fmt is a string corresponding to a simple fmt statement.
For instance '%6.5f' prints as 6 characters wide with 5 decimal dig... | 36b555720a8908f2552dbbec7f03c648e34f168a | 33,537 |
import os
import collections
def get_stationxml_filename(str_or_fct, network, station, channels,
starttime, endtime):
"""
Helper function getting the filename of a StationXML file.
:param str_or_fct: The string or function to be evaluated.
:type str_or_fct: function or str... | f0d2d648610f99c0f20fc93e9742c5089335643a | 33,538 |
import requests
def fetch_reviews(app_id, page_num):
"""Fetch a single page of reviews for a given app_id.
:param app_id: The ID of the app in the app store.
:param page_num: The page of reviews to fetch.
:return: A list of Review objects.
"""
# page=1 is the same as if the "page" param was l... | 99b71a41ae7bc96e40d6d1798dd676c6a889f80b | 33,539 |
def graph_push_point(graph_id):
"""
Push points to graph
"""
request_data, error = parseHTTPRequest(request, ["value"])
if error:
response = jsonify({
"error": error
})
return response, 422
try:
# data = {"value":10, "date": datetime.datetime.... | cf6522e294887370a3f8ad76ff66e96fb9b79291 | 33,540 |
def or_operator():
"""|: Bitwise "or" operator."""
class _Operand:
def __or__(self, other):
return " ~or~ ".join(('east coast', other))
return _Operand() | 'dirty south' | 9ccfc124dd6c7aae8035b336788cc07cdff983d1 | 33,541 |
import tqdm
def computeAlignmentScores(vocabulary, sub_mat, gap_open, gap_extend):
"""
Pre-computes the alignment scores between all the k-mer pairs
Args:
vocabulary (list [str]): The list of all possible k-mers
sub_mat (dict[tuple[str,str],int]): Substitution matrix as represented in Bio.SubsMat.MatrixInfo.b... | 0b7aeb6b592586b827e19969a418146800805687 | 33,542 |
import os
from pathlib import Path
import time
import random
def setup(version, verbose=True):
"""
:param version:
Supported version values (examples):
1. Unstable versions:
- unstable/master:2020-12-20T00:11:59Z
- unstable/enterprise:2020-08-18T14:49:18Z
... | 23396bf3401305a0f04a181bddaa6b47e1487c75 | 33,543 |
import re
def _get_version(basename):
"""Returns the _get_next_version of a file."""
match = re.search(r"\(\d*\)", basename)
if match:
v = int(match.group(0)
.replace('(', '')
.replace(')', ''))
return v
return 0 | 7340b74dca04ecb5520c03b046ec650c34527b4c | 33,544 |
def list_tags():
"""Show all the known tags."""
streets_with_tags = (
db.session.query(Street).filter(Street.tags != None).all() # noqa
)
all_tags = set()
for street in streets_with_tags:
all_tags.update(set(street.tags))
all_tags = sorted(list((all_tags)))
return render_t... | 737e65e7088357407c71eb19b9b3a4ddc948e26a | 33,545 |
def get_records(field_id):
"""Return TOP 10 records for selected field"""
if not request.is_xhr:
abort(403)
if field_id == 0:
field_id = session.get('current_field_id', 2)
field = Field.query.get(field_id)
records = field.records.limit(10)
top_10 = []
for record in records:... | c9fcf236ee765d2a09148367293ea882093ab001 | 33,546 |
def self_play_iterator_creator(hparams, num_workers, jobid):
"""create a self play iterator. There are iterators that will be created here.
A supervised training iterator used for supervised learning. A full text
iterator and structured iterator used for reinforcement learning self play.
Full text iterators fee... | 618179a8694a2df0edbd1401a6caf18e607b2652 | 33,547 |
def utf8_product_page():
"""
Single product page with utf8 content.
"""
with open('data/product_utf8.html') as f:
return ''.join(f) | 56a70e463cebdaef632ebd2997be4a523289da02 | 33,548 |
def detect_Nir2011(dat_orig, s_freq, time, opts):
"""Spindle detection based on Nir et al. 2011
Parameters
----------
dat_orig : ndarray (dtype='float')
vector with the data for one channel
s_freq : float
sampling frequency
time : ndarray (dtype='float')
vector with the ... | f4e4c1cd22944fd09121c0f43bb28a4dd3e7d629 | 33,549 |
def is_indel(variant):
"""Is variant an indel?
An indel event is simply one where the size of at least one of the alleles
is > 1.
Args:
variant: third_party.nucleus.protos.Variant.
Returns:
True if the alleles in variant indicate an insertion/deletion event
occurs at this site.
"""
# redact... | dc44642a011ac292c73a163b29bb1f3c4cb36624 | 33,550 |
import functools
def project_access_required(f):
"""Decorator function to verify the users access to the project."""
@functools.wraps(f)
def verify_project_access(current_user, project, *args, **kwargs):
"""Verifies that the user has been granted access to the project."""
if project["id"... | 4689e05ae330e360ca0e1ac221b571545608d5b4 | 33,551 |
def downloadRangesHelper(imageCount : int, downloadRange, downloadIndex):
"""Helper function for calculating download ranges and/or download index"""
# expected output should be [x,y], where x = zero-based image index start,
# and y = the amount of images in a post.
# check if downloadRange and downloa... | 2fa98a1111059d5c2f2126f19a8eccab9b23a596 | 33,552 |
import sqlite3
def removeProduct(product, connection=None):
"""
Remove a product tuple from the database.
Args:
products (str): The product to be removed from the database.
connection (sqlite3.Connection, optional): A connection to the database.
Returns:
bool: True if successful, f... | 131c013a4ee1569b91dd7f52b3c961877e4a9124 | 33,553 |
def health():
"""Return information about the health of the queue in a format that
can be turned into JSON.
"""
output = {'queue': {}, 'errors': {}}
output['queue']['all-jobs'] = Job.objects.all().count()
output['queue']['not-executed'] = Job.objects.filter(executed=None).count()
output['que... | f65ac55808d52ece96b6168137e78f8ad42c7d7f | 33,554 |
import sys
def pdsspect(inlist=None):
"""Run pdsspect from python shell or command line with arguments
Parameters
----------
inlist : :obj:`list`
A list of file names/paths to display in the pdsspect
Examples
--------
From the command line:
To view all images from current d... | db50921290eb9ac08625be7380bcca193d36e39b | 33,555 |
import os
import json
def _make_library(ydir):
"""
Make JSON library of YANG modules.
Args:
ydir (str): Name of the directory with YANG (sub)modules.
"""
for infile in os.listdir(ydir):
if not infile.endswith(".yang"):
continue
with open(
"{ydir}/{in... | 6255f1c9add7e4763764a2f8495121d75e1e3a56 | 33,556 |
def build_confirmation_msg(message_template: str, variables_arr: [], record):
"""Returns the full confirmation email as a string
Note: some email services also support sending HTML for future purposes.
"""
inserts = []
for variable in variables_arr:
inserts.append(record['fields'][variable.strip()])
mes... | 6d84b19f2bcce3fab298fe7ece2a011b423f9e90 | 33,557 |
import re
def _get_freq_label_by_month(date_value: str) -> str:
"""Gets frequency label for the date value which is aggregated by month.
Args:
date_value (str): The date value.
Returns:
str: The date value aggregated by month.
"""
if bool(re.match(r"^\d{4}M\d{1,2}$", date_value))... | a789d993bf390fba42dc5451302f3fe89623cb3d | 33,558 |
import torch
def get_depth_metrics(pred, gt, mask=None):
"""
params:
pred: [N,1,H,W]. torch.Tensor
gt: [N,1,H,W]. torch.Tensor
"""
if mask is not None:
num = torch.sum(mask) # the number of non-zeros
pred = pred[mask]
gt = gt[mask]
else:
num = pred.nume... | 2d4e617bbbf3823ee60dbf1480aed624fd7ba57b | 33,559 |
def run_ica(raw, n_components, max_pca_components=100,
n_pca_components=64, noise_cov=None, random_state=None,
algorithm='parallel', fun='logcosh', fun_args=None,
verbose=None, picks=None, start=None, stop=None, start_find=None,
stop_find=None, ecg_ch=None, ecg_score_func... | 56b36d33211123839ed61f6cc19e7c7ee4c2e336 | 33,560 |
def remove_member(context, request):
"""Remove a member from the given group."""
# Currently, we only support removing the requesting user
if request.matchdict.get("userid") == "me":
userid = request.authenticated_userid
else:
raise HTTPBadRequest('Only the "me" user value is currently s... | 494ddb9e824911680c8c4f80dbc7d1c6aa6f12d2 | 33,561 |
def convert_length(length, original_unit="kilometers", final_unit="kilometers"):
"""
:param length: length to be converted
:param original_unit: original unit of the length
:param final_unit: return unit of the length
:return: the converted length
"""
if not isinstance(length, (float, int))... | e76dcaa050eaa1a77621c7062ca2a187238d0ea3 | 33,562 |
import os
def pytest_ignore_collect(path, config): # pylint: disable = unused-argument
"""return True to prevent considering this path for collection.
This hook is consulted for all files and directories prior to
calling more specific hooks.
"""
relative_path = os.path.relpath(str(path), os.pat... | 0f48dcbf3bc15878d9c64a6712da996fa1556c67 | 33,563 |
import os
import sys
import pickle
def load_model_db(FLAGS):
"""
Load model database.
"""
# load models
if not os.path.exists(FLAGS.models_save_dir):
sys.exit("Model file " + FLAGS.model_save_dir + " does not exist!")
else:
return pickle.load(open(FLAGS.model_save_dir, "r")) | 3e8ce2e9b6e53a22129b3b1b64432e6f1d9308d3 | 33,564 |
def get_value_larger(threshold, value, step, direction, size_x, size_y):
"""Function for looping until correct coordinate is found"""
matrix = [[0 for _ in range(size_x)] for _ in range(size_y)]
current_x = size_x / 2
current_y = size_y / 2
while value <= threshold:
for _ in range(0, 2):
... | 49db166798446e98ae23800eb1428ba3baf0a026 | 33,565 |
def get_daq_device_inventory(interface_type, number_of_devices=100):
# type: (InterfaceType, int) -> list[DaqDeviceDescriptor]
"""
Gets a list of :class:`DaqDeviceDescriptor` objects that can be used
as the :class:`DaqDevice` class parameter to create DaqDevice objects.
Args:
interface_type... | abee7adb4fa57471e09a480a971e35e5081a9837 | 33,566 |
def statement_passive_verb(stmt_type):
"""Return the passive / state verb form of a statement type.
Parameters
----------
stmt_type : str
The lower case string form of a statement type, for instance,
'phosphorylation'.
Returns
-------
str
The passive/state verb form... | 21a34fc7270d0c9f9d4c096930ed5bcb9f6af72b | 33,567 |
import argparse
def parse_inputs():
""" Parses the input arguments
Input: Command line inputs specified by the user.
Output: Parsed command line inputs
"""
parser = argparse.ArgumentParser(description = 'This will make a prediction on an image')
parser.add_argument('image', type... | c8ae9d67092080183f59ac93a816e04e4c324a97 | 33,568 |
from typing import Iterable
def find_hpas(config: Config,) -> Iterable[client.models.v1_horizontal_pod_autoscaler.V1HorizontalPodAutoscaler]:
"""Find any HorizontalPodAutoscaler having klutch annotation."""
resp = client.AutoscalingV1Api().list_horizontal_pod_autoscaler_for_all_namespaces()
return filter(... | fcc34c83d7f50c25510eabfb6b60d6106fe97432 | 33,569 |
def bioacoustics_index (Sxx, fn, flim=(2000, 15000), R_compatible ='soundecology'):
"""
Compute the Bioacoustics Index from a spectrogram [1]_.
Parameters
----------
Sxx : ndarray of floats
matrix : Spectrogram
fn : vector
frequency vector
flim : tupple (fmin, fmax), ... | fcc557d1bbbe5d3c9758cb500cb8a98cd83510ce | 33,570 |
import os
def get_create_path_for(tlobject):
"""Gets the file path (and creates the parent directories)
for the given 'tlobject', relative to nothing; only its local path"""
# Determine the output directory
out_dir = 'methods' if tlobject.is_function else 'constructors'
if tlobject.namespace:... | abc4a376d462b29f7520d311bd7d065f03485b0c | 33,571 |
def ctm_to_dict(ctm_fn):
"""
Return a dictionary with a list of (start, dur, word) for each utterance.
"""
ctm_dict = {}
with open(ctm_fn, "r") as f:
for line in f:
utt, _, start, dur, word = line.strip().split(" ")
if not utt in ctm_dict:
ctm_dict[utt... | 7a0c58e544029fd118448b916c2c2966172c5d1b | 33,572 |
def qft_core(qubits, coef=1):
"""
Generates a quil programm that performs
quantum fourier transform on given qubits
without swaping qubits at the end.
:param qubits: A list of qubit indexes.
:param coeff: A modifier for the angle used in rotations (-1 for inverse
QFT, 1 f... | 79944c93ff2d3d5393d9f94e546d79b69334f005 | 33,573 |
def get_formatted_timestamp(app_type):
"""Different services required different date formats - return the proper format here"""
if app_type in {'duo', 'duo_admin', 'duo_auth'}:
return 1505316432
elif app_type in {'onelogin', 'onelogin_events'}:
return '2017-10-10T22:03:57Z'
elif app_type... | f5d4f2ac1d30383849b6149a46525e67439229df | 33,574 |
import sys
import os
def UseWin64():
"""Check if we are on 64 bit windows."""
if sys.platform != 'win32':
return False
arch32 = os.environ.get('PROCESSOR_ARCHITECTURE', 'unk')
arch64 = os.environ.get('PROCESSOR_ARCHITEW6432', 'unk')
if arch32 == 'AMD64' or arch64 == 'AMD64':
return True
return Fa... | 1a122fa6fff489a1c857082648de2b10c7d8adb1 | 33,575 |
import array
def preprocess(x, copy=False, float=False, axis=None):
"""
Ensure that `x` is a properly formatted numpy array.
Proper formatting means at least one dimension, and may include
optional copying, reshaping and coersion into a floating point
datatype.
Parameters
----------
... | b1632ca64fe315330d26f9beeef6fa9df8a40382 | 33,576 |
def detect_defaults_settings(output):
""" try to deduce current machine values without any
constraints at all
"""
output.writeln("\nIt seems to be the first time you run conan", Color.BRIGHT_YELLOW)
output.writeln("Auto detecting your dev setup to initialize conan.conf", Color.BRIGHT_YELLOW)
re... | 86e15908c6219e3f0f5caefe8a0a858ce602e484 | 33,577 |
def align_instance_center(dfi, original_patterns, aligned_patterns, trim_frac=0.08):
"""Align the center of the seqlets using aligned patterns
Args:
dfi: pd.DataFrame returned by `load_instances`
original_patterns: un-trimmed patterns that were trimmed using
trim_frac before scanning
... | 9e2ac982e593e4504b72d8d6502ade1e38988be4 | 33,578 |
from .continent import COUNTRY_TO_CONTINENT
def compute_continent_histogram(docs: DocumentSet, **kwargs) -> pd.DataFrame:
""" Compute a histogram of number of documents by affiliation
continent.
"""
def extract(doc):
result = set()
for author in doc.authors or []:
for ... | 031617c337850eeada50046acdade4fb7ada4fef | 33,579 |
from typing import OrderedDict
def calc_prod(corpus_context, envs, strict = True, all_info = False, ordered_pair = None,
stop_check = None, call_back = None):
"""
Main function for calculating predictability of distribution for
two segments over specified environments in a corpus.
Param... | 4c104b235bb6970573c2ea659c81038e266c40d3 | 33,580 |
import tqdm
def read_run_dict(file_name):
"""Read a run file in the form of a dictionary where keys are query IDs.
:param file_name: run file name
:return:
"""
result = {}
with FileWrapper(file_name) as f:
for ln, line in enumerate(tqdm(f, desc='loading run (by line)', leave=False)):
... | 2aa7937e259481c86ddaf13d9f6af8e49efb087c | 33,581 |
def parse_address(address):
"""Convert host:port or port to address to pass to connect."""
if ':' not in address:
return ('', int(address))
host, port = address.rsplit(':', 1)
return (host, int(port)) | 06eb172974c4e75d33ae205f952e8533c88acfeb | 33,582 |
from typing import List
import os
async def sync_bars_worker(sync_params: dict = None, secs: List[str] = None):
"""
worker's sync job
"""
logger.info("sync_bars_worker with params: %s, %s", sync_params, secs)
try:
frame_type, start, stop = _parse_sync_params(sync_params)
except Except... | bcc4f6c9faa61537d551d7d1853da938c4583066 | 33,583 |
def secure_host_url(request, secure_url=None):
"""Overrides ``host_url`` to make sure the protocol is secure."""
# Test jig.
if secure_url is None:
secure_url = secure_request_url
return secure_url(request, 'host_url') | d4a0b43a52170d7ac07d2cc8141e789a0005c2fa | 33,584 |
def search():
"""
Used by `nuget list`.
"""
logger.debug("Route: /search")
logger.debug(request.args)
# TODO: Cleanup this and db.search_pacakges call sig.
include_prerelease = request.args.get('includePrerelease', default=False)
order_by = request.args.get('$orderBy', default='Id')
... | 4700e7866d1909eba77ed25ccca3de37de4a2fc5 | 33,585 |
def get_resource_mutator(cpu=None, memory=None, gpu=None, gpu_vendor='nvidia'):
"""The mutator for getting the resource setting for pod spec.
The useful example:
https://github.com/kubeflow/fairing/blob/master/examples/train_job_api/main.ipynb
:param cpu: Limits and requests for CPU resources (Default... | 02cc5069470d6b255c2c8cb1e8eb27f282b66911 | 33,586 |
def gram_matrix(features):
"""
Calculates the gram matrix of the feature representation matrix
:param features: The feature matrix that is used to calculate the gram matrix
:return: The gram matrix
"""
return K.dot(features, K.transpose(features)) | ebc8a354de903b764e7cc5a214c9d6bbcbe5a1f8 | 33,587 |
def lp_dominate(w, U):
"""
Computes the belief in which w improves U the most.
With LP in White & Clark
:param w: np.ndarray
:param U: list of np.ndarray
:return: b if d >= 0 else None
"""
# print("LP dominate")
if len(U) == 0:
return w
S = len(w)
d = cvx.Variable()
... | 26ff577b8ad7d97b2062d37299ca59c84897c404 | 33,588 |
from typing import Union
import torch
def get_random_subset_dataloader(dataset: Dataset, subset_size: Union[float, int], **dataloader_kwargs) -> DataLoader:
""" Returns a random subset dataloader sampling data from given dataset, without replacement.
Args:
- dataset: PyTorch dataset from which random ... | a6dc4e70d6676a6e348339c90ffa99dc76772e9a | 33,589 |
import numpy
def _combine_pfs(pfa, pfb, coeff, operator):
""" Obtain the pf information of the multiplication of pfa and pfb
"""
tempsa, logqa, dq_dta, d2q_dt2a = pfa
_, logqb, dq_dtb, d2q_dt2b = pfb
if operator == 'multiply':
logq = [a+b+numpy.log(coeff) for a, b in zip(logqa, logqb)]
... | f89ee97ab5e5de348f42e71d9ad5fa86ba15f922 | 33,590 |
def epa_nei_nonpoint_parse(*, df_list, source, year, config, **_):
"""
Combine, parse, and format the provided dataframes
:param df_list: list of dataframes to concat and format
:param source: source
:param year: year
:param config: dictionary, items in FBA method yaml
:return: df, parsed an... | 0a411cd7ce130adafcc8b3615a2c41998454e585 | 33,591 |
from typing import Union
from typing import List
from typing import Dict
import ray
def create_auto_config(
dataset: Union[str, pd.DataFrame, dd.core.DataFrame, DatasetInfo],
target: Union[str, List[str]],
time_limit_s: Union[int, float],
tune_for_memory: bool,
user_config: Dict = None,
) -> dict:... | 1bd76497b71ed7163af9bddf87e7ee346ed9ff4d | 33,592 |
import os
def change_file_name(file_path, prefix=None, name=None, suffix=None):
"""
Change the file name from the given file path
:param file_path: Input file path
:param prefix: Prefix to the file name
:param name: Whether a new name is set instead of the current name.
If None, the curren... | c5123a55a122b9d4edb32acb9cdd6ee5624c4544 | 33,593 |
import numpy
def create_orbit_from_particles(particles, angular_velocity=0.|units.yr**-1):
"""
Use mass, position and velocity to determine orbital parameters.
Then setup Roche_Orbit
"""
roche = Roche_Orbit()
roche.mass_1, roche.mass_2 = particles.mass
position_vector = particles.... | e9314b582e4031a4ca5816f7d0980430c325dc53 | 33,594 |
def bitter_rivals(voting_dict):
"""
Input: a dictionary mapping senator names to lists representing
their voting records
Output: a tuple containing the two senators who most strongly
disagree with one another.
Example:
>>> voting_dict = {'Klein': [-1,0,1], 'Fox-Epstein': ... | 154e067add7a8d5b58d1474530e690bdfb40a7ea | 33,595 |
from operator import and_
def last_contacts(ts_start):
"""Get the last time each timeseries datapoint was updated.
Args:
config: Configuration object
ts_start: Timestamp to start from
Returns:
data: List of dicts of last contact information
"""
# Initialize key variables... | 6e46d10f0ad7ab1523cd21255cf659d791f551c4 | 33,596 |
import os
import glob
def directory_contents(path_to_dir):
"""
Returns list of paths to files and folders relatively from path_to_dir.
"""
cur_dir_backup = os.getcwd()
os.chdir(path_to_dir)
files = glob.glob('**', recursive=True)
os.chdir(cur_dir_backup)
return files | 669ac9c59582b8e2764f4f37a64a76f1ec17309b | 33,597 |
import torch
def train_one_epoch_loss_acc(net, train_iter, loss, updater):
"""训练模型一个迭代周期(定义见第3章)
Defined in :numref:`sec_softmax_scratch`
返回 train loss 和 train acc
"""
# 将模型设置为训练模式
if isinstance(net, torch.nn.Module):
net.train()
# 训练损失总和、训练准确度总和、样本数
metric = Accumulator(3)
... | 314fe27c20d690a3a09a02571a0e545aea73f845 | 33,598 |
def get_numeric_cache(hostname):
"""Get all the numeric cache entries we have for an hostname
"""
return [{
'collection': str(n.template.collection),
'template': str(n.template),
'value': n.value,
'last_modified': n.last_modified,
} for n in NumericCache.objects.filter(h... | 6adb7f3a17e6856ba9319e7cd10567e9cf820378 | 33,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.