content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
import calendar
def create_calendar(year=None, month=None):
"""
Create an inline keyboard with the provided year and month
"""
now = datetime.datetime.now()
if year is None:
year = now.year
if month is None:
month = now.month
data_ignore = crea... | edd7dd0245bbcb4269eaa4767cf16eb382db29e8 | 3,642,600 |
def read_image(link, size):
""" Read image on link and convert it to given size
Usage:
image = readImage(link, size)
Input variables:
link: path to image
size: output size of image
Output variables:
image: read and resized image
"""
image ... | 8465fc3ef8f6d8829da251cc924b442a4b7f3d07 | 3,642,601 |
def make_send_data(application_preset):
"""Generate the data to send to the protocol."""
if application_preset == 'none':
# data = bytes([i for i in range(32)])
# data = bytes([i for i in range(54)]) # for teensy 4.0
data = bytes([i for i in range(54)]) # for teensy lc & micro
... | 2b04a0bf977e44c3bd2a2aa6df0834ad458364bc | 3,642,602 |
def dp4a(x_scope="local", y_scope="local", z_scope="local", dtypes=("int8", "int8")):
"""
Int8 dot product reduced by every 4 elements using __dp4a
Parameters
----------
x_scope : str, optional
The storage scope of buffer for lhs
y_scope : str, optional
The storage scope of buff... | 7d384867b9854c880288dd6ad2be6400d861282a | 3,642,603 |
def fileexists(filename):
"""Replacement method for os.stat."""
try:
f = open( filename, 'r' )
f.close()
return True
except:
pass
return False | 126460a04e7a8faf7517cb46c480670f5a067b1a | 3,642,604 |
def test_knowledge_graph_init(graph_mutation_client, graph_mutation_responses):
"""Test knowldge graph client initialization."""
return graph_mutation_client.named_types | 932a425e4bbdc301ef223e0f91936ecacf3bd5aa | 3,642,605 |
def read_camera_matrix(filename):
"""
Read camera matrix from text file exported by PhotoScan
"""
with open(filename, 'r') as f:
s = f.read()
s = s.split(',')
s = [x.strip('\Matrix([[') for x in s]
s = [x.strip(']])') for x in s]
s = [x.strip('[') for x in s]
s = [x.strip(']... | be01c60d3c8940250c578a67de2c06110fb403e4 | 3,642,606 |
def find_child_joints(model, joint_name):
""" Find all the joints parented to the given joint. """
joint_id = joint_name_to_index(model)
link_id = link_name_to_index(model)
# FIXME : Add exception to catch invalid joint names
joint = model.joints[joint_id[joint_name]]
clink = joint.child
ret... | 35deab9fca062e90547cf6a550f9e14d654f0462 | 3,642,607 |
import pathlib
def stem(path: str) -> str:
"""returns the stem of a path (path without parent directory and without extension)
e.g
j.sals.fs.stem("/tmp/tmp-5383p1GOmMOOwvfi.tpl") -> 'tmp-5383p1GOmMOOwvfi'
Args:
path (str): path we want to get its stem
Returns:
str: path with... | ec7507becb31bda7662122668b490148ca15d347 | 3,642,608 |
import json
import re
def fluent_text(field, schema):
"""
Accept multilingual text input in the following forms
and convert to a json string for storage:
1. a multilingual dict, eg.
{"en": "Text", "fr": "texte"}
2. a JSON encoded version of a multilingual dict, for
compatibility w... | e07b8f7d83500bd79662f36df5ff2a4cf42af092 | 3,642,609 |
def palette_color_brewer_q_Set3(reverse=False):
"""Generate set3 Brewer palette of a given size ... interpolate as needed ... best for discrete mapping
Args:
reverse: order the colors backward as compared to standard Brewer palette
Returns:
lambda: generates a list of colors
See Also:... | 38355f8b9f7a69ad7c7f4951d324e9b8bbd233bb | 3,642,610 |
from magmap.io import export_rois
from magmap.io import export_rois
import os
def process_file(path, proc_mode, series=None, subimg_offset=None,
subimg_size=None, roi_offset=None, roi_size=None):
"""Processes a single image file non-interactively.
Assumes that the image has already been set ... | 980c30c822119a788e9a0da142b68c0a67506be1 | 3,642,611 |
def get_loss_function(identifier):
"""
Gets the loss function from `identifier`.
:param identifier: the identifier
:type identifier: str or dict[str, str or dict]
:raise ValueError: if the function is not found
:return: the function
:rtype: function
"""
return _get(identifier, loss_... | 060a14f21332ad47273febeb7d4a8347a2fd3957 | 3,642,612 |
def find_defender(ships, side):
"""Crude method to find something approximating the best target when attacking"""
enemies = [x for x in ships if x['side'] != side and x['hp'] > 0]
if not enemies:
return None
# shoot already wounded enemies first
wounded = [x for x in enemies if x['hp'] < x[... | 4c58ec01abae1f59ced47e61e257abe7f8923aea | 3,642,613 |
import os
def get_parameters(image_path):
"""
Parses the image path to dictionary
:param str image_path: image path
:rtype dict
"""
image_path = image_path
image_directory = os.path.dirname(image_path)
image_filename = os.path.basename(image_path)
image_name = image_filename.split(... | cffef64001c81fd3459d49239b1ce863c546b6ca | 3,642,614 |
import csv
def Create_clump_summaries(feature_file,simplify_threshold):
""" Employs Panda Shapely library to simplify polygons by eliminating almost
colinear vertices. Generates two data structures: First - sort_clump_df: Panda Dataframe
containing the longest line in the simplified and unsimplifie... | 3b846760d78ad44630de0005e70e26f00b44b7d4 | 3,642,615 |
from re import S
def norm(point):
"""Returns the Euclidean norm of a point from origin.
Parameters
==========
point: This denotes a point in the dimensional space.
Examples
========
>>> from sympy.integrals.intpoly import norm
>>> from sympy.geometry.point import Point
>>> norm(P... | 8e341bb7e623d2ef7a998b91a15e8a6735403860 | 3,642,616 |
def read_reducing():
"""Return gas resistance for reducing gases.
Eg hydrogen, carbon monoxide
"""
setup()
return read_all().reducing | 3e0d78fc999909d29c469f3399e845df542e1e68 | 3,642,617 |
def access_rights_to_metax(data):
"""
Cherry pick access right data from the frontend form data and make it comply with Metax schema.
Arguments:
data {object} -- The whole object sent from the frontend.
Returns:
object -- Object containing access right object that comply to Metax schem... | f66167028d86b5af4f15149bd21ab52fab9c3ba4 | 3,642,618 |
def read_toml_file(input_file, config_name = None, confpaths = [".", TCFHOME + "/" + "config"]):
"""
Function to read toml file and returns the toml content as a list
Parameters:
- input_file is any toml file which need to be read
- config_name is particular configuration to pull
- d... | 9f0e05dfd556f06ed0323e6484e804f7813c626c | 3,642,619 |
def and_sum (phrase):
"""Returns TRUE iff every element in <phrase> is TRUE"""
for x in phrase:
if not x:
return False
return True | d65953c5811aedef0a7c76cd3191aba8236f02fa | 3,642,620 |
def load_data(filename: str):
"""
Load house prices dataset and preprocess data.g
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Series]
"""
... | a01179d470262bdc77e9d5417c1bd00415e4ccbd | 3,642,621 |
def eccanom(M, e):
"""Finds eccentric anomaly from mean anomaly and eccentricity
This method uses algorithm 2 from Vallado to find the eccentric anomaly
from mean anomaly and eccentricity.
Args:
M (float or ndarray):
mean anomaly
e (float or ndarray):
eccentrici... | 433ee8d5f6c247626316d953ecf35a9805b70390 | 3,642,622 |
def transform_frame(frame: np.array,
transform: AffineTransformation,
rotate: bool = False,
center_crop: bool = False) -> np.array:
""" Perform affine transformation of a single image-frame.
Parameters
----------
frame : array
Image fr... | 7e29b2a0abf62e1388c6715cfb30958046f1ff18 | 3,642,623 |
def TEMA(equity, start=None, end=None, timeperiod=30):
"""Triple Exponential Moving Average
:param timeperiod:
:return:
"""
close = np.array(equity.hp.loc[start:end, 'close'], dtype='f8')
real = talib.TEMA(close, timeperiod=timeperiod)
return real | 0494e2cd6fedfc6b8ea8880808090f481c1128bc | 3,642,624 |
def get_miner_pool_by_owner_id():
"""
存储提供者详情
:return:
"""
owner_id = request.form.get("owner_id")
data = MinerService.get_miner_pool_by_no(owner_id)
return response_json(data) | aa9fb36843d8999ac428d492463432de096628fe | 3,642,625 |
def notFound(e):
"""View for 404 page."""
return render_template('content/notfound.jinja.html'), 404 | d1bb53d22351ecbceda60ea28bdf8e7b688ad77d | 3,642,626 |
from datetime import datetime
def get_stay(admission_date, exit_date):
"""Method to get exit date."""
try:
if not exit_date:
exit_date = datetime.now().date()
no_days = exit_date - admission_date
# Get More
years = ((no_days.total_seconds()) / (365.242 * 24 * 3600))... | bba3aa63884608500793c9f97c0c6e0e5d9e69ef | 3,642,627 |
def compress(X, halve, g = 0, indices = None):
"""Returns Compress coreset of size 2^g sqrt(n) or, if indices is not None,
of size 2^g sqrt(len(indices)) as row indices into X
Args:
X: Input sequence of sample points with shape (n, d)
halve: Algorithm that takes an input a set of points an... | 34503bf6602ef4577811c6fe449ae6109fa25007 | 3,642,628 |
def filter_objects(objs, labels, none_val=0):
"""Keep objects specified by label list"""
out = objs.copy()
all_labels = set(nonzero_unique(out))
labels = set(labels)
remove_labels = all_labels - labels
for l in remove_labels:
remove_object(out, l)
return out | 8fccf936a5e74e274a2df5c182764e346e39dafb | 3,642,629 |
def get_index_freq(freqs, fmin, fmax):
"""Get the indices of the freq between fmin and fmax in freqs
"""
f_index_min, f_index_max = -1, 0
for freq in freqs:
if freq <= fmin:
f_index_min += 1
if freq <= fmax:
f_index_max += 1
# Just check if f_index_max is not... | f3e014626d763f18ce6b661cabeb244bfabe9782 | 3,642,630 |
def get_gene_mod(gene_id, marker_id):
"""Retrieves a GeneMod model if the gene / marker pair already exists,
or creates a new one
"""
if gene_id in ("None", None):
gene_id = 0
if marker_id in ("None", None):
marker_id = 0
gene_mod = GeneMod.query.filter_by(gene_id=gene_id, mar... | 26f29cbaa33c6fb7d40626152977c583fa5bcf57 | 3,642,631 |
def random_matrix(shape, tt_rank=2, mean=0., stddev=1.,
dtype=tf.float32, name='t3f_random_matrix'):
"""Generate a random TT-matrix of the given shape with given mean and stddev.
Entries of the generated matrix (in the full format) will be iid and satisfy
E[x_{i1i2..id}] = mean, Var[x_{i1i2..id... | 01f81199a71966ce379d2acc01d237ec47d346ec | 3,642,632 |
def triangulate_polylines(polylines, holePts, lowQuality = False, maxArea = 0.01):
"""
Convenience function for triangulating a polygonal region using the `triangle` library.
Parameters
----------
polylines
List of point lists, each defining a closed polygon (with coinciding
first a... | e2ae0eb5339d51d02eb1d26302fc18229ff85f83 | 3,642,633 |
def inclination(x, y, z, u, v, w):
"""Compute value of inclination, I.
Args:
x (float): x-component of position
y (float): y-component of position
z (float): z-component of position
u (float): x-component of velocity
v (float): y-component of velocity
... | bf85358fc6f002cdb4e0d47e6af0a93b8f9e4024 | 3,642,634 |
def OctahedralGraph():
"""
Return an Octahedral graph (with 6 nodes).
The regular octahedron is an 8-sided polyhedron with triangular faces. The
octahedral graph corresponds to the connectivity of the vertices of the
octahedron. It is the line graph of the tetrahedral graph. The octahedral is
s... | d2abce73e747890f992301bb4814cfa52e55bce4 | 3,642,635 |
def peak_detect(y, delta, x=None):
""" Find local maxima in y.
Args:
y (array): intensity data in which to look for peaks
delta (float): a point is considered a maximum peak if it has the maximal value, and was preceded (to the left) by a value lower by DELTA.
x (array, optional): corre... | def69cfcea7ccaed931fd764eab88de9fbb8773a | 3,642,636 |
def quadruplet_fixated_egomotion( filename ):
"""
Given a filename that contains 4 different point-view combos, parse the filename
and return the pair-wise camera pose.
Parameters:
-----------
filename: a filename in the specific format.
Returns:
-----------
egomotion: a nu... | 5b40e8cfac7362c361ebe9119e5e4753c8e03978 | 3,642,637 |
def moshinsky(state1,state2,stater,statec,state,type):
"""
calculates the moshinsky coefficients used to transform between the two-particle and relative-center of mass frames.
w1 x w2->w
wr x wc->w
type can be either "SU3" or "SO3"
if type=="SU3":
state1,state2,stater,statec,state are simply SU3State class
... | ee53cc25f2723b95179e1e190d94536de18f6321 | 3,642,638 |
def test_lie_algebra_nqubits_check():
"""Test that we warn if the system is too big."""
@qml.qnode(qml.device("default.qubit", wires=5))
def circuit():
qml.RY(0.5, wires=0)
return qml.expval(qml.Hamiltonian(coeffs=[-1.0], observables=[qml.PauliX(0)]))
with pytest.warns(UserWarning, mat... | b4e296eabab9dc1fd250d391e8c12d2b2f12c59c | 3,642,639 |
def get_elastic_apartments_not_for_sale():
"""
Get apartments not for sale but with published flags
"""
s_obj = (
ApartmentDocument.search()
.filter("term", publish_on_oikotie=True)
.filter("term", publish_on_etuovi=True)
.filter("term", apartment_state_of_sale__keyword=A... | 080afdfa61f40f966ad498b3e292224bbfac262d | 3,642,640 |
def promptYesNoCancel(prompt, prefix=''):
"""Simple Yes/No/Cancel prompt
:param prompt: string, message to the user for selecting a menu entry
:param prefix: string, text to print before the menu entry to format the display
:returns: string, menu entry text
"""
menu = [
{'index': 1, 'te... | bf71ac635ef83ce370350bd352a7e0d619a956c7 | 3,642,641 |
def gradcheck_naive(f, x):
"""
Implements a manual gradient check: this functions is used as a helper function in many places
- f should be a function that takes a single argument and outputs the cost and its gradients
- x is the point (numpy array) to check the gradient at
"""
rndstate = ran... | c99f687ae8fad8ea890119e014294879f97fce33 | 3,642,642 |
def cal_mae_loss(logits, gts, reduction):
"""
:param preds: (N,C,H,W) logits predicted by the model.
:param gts: (N,1,H,W) ground truths.
:param reduction: specifies how all element-level loss is handled.
:return: mae loss
"""
probs = logits.sigmoid()
loss = (probs - gts).abs()
retur... | 6cc813552c46c4c6ea92fb1295478e8770cb255c | 3,642,643 |
def divideByFirstColumn(matrix):
"""This function devide a matrix by its first column to resolve
wrong intemsity problems"""
result = (matrix.T / matrix.sum(axis=1)).T
return result | 348bbaa1a3c16a42be90978a0fcc65b1a7daf557 | 3,642,644 |
def loglikehood_coefficient(n_items, X, Y):
"""
Considering the rows of X (and Y=X) as vectors, compute the
distance matrix between each pair of vectors.
Parameters
----------
n_items: int
Number of items in the model.
X: array of shape (n_samples_1, n_features)
Y: array of sh... | 220090c944c9e9c6b97fb8a576aa416ec0493c26 | 3,642,645 |
def get_archive_by_path(db, vault_name, path, retrieve_subpath_archs=False):
"""
Will attempt to find the most recent version of an archive representing a given path.
If retrieve_subpath_archs is True, then will also retrieve latest versions of archives representing
subdirs of the path.
:param path:... | af30d33e90ef1b509a75f1c96a85b0457d454b71 | 3,642,646 |
import random
def superpixel_colors(
num_pix:int = 1536,
schema:str = 'rgb',
interleave:int = 1,
stroke:str = '',
) -> list:
"""
Generate color (attribute) list for superpixel SVG paths
Parameters
----------
num_pix : int
Number of super pixels to account for (default ... | 7a574b48dff30126052c2acd5d06e01a9f4a9af0 | 3,642,647 |
from typing import List
def build_module_op_list(m: tq.QuantumModule, x=None) -> List:
"""
serialize all operations in the module and generate a list with
[{'name': RX, 'has_params': True, 'trainable': True, 'wires': [0],
n_wires: 1, 'params': [array([[0.01]])]}]
so that an identity module can be ... | e14bbfe8122e05d0b65e93246494fa1414bcdf1b | 3,642,648 |
import argparse
def _get_args():
""" Parses the command line arguments and returns them. """
parser = argparse.ArgumentParser(description=__doc__)
# Argument for the mode of execution (human or random):
parser.add_argument(
"--mode", "-m",
type=str,
default="human",
ch... | fdccca9d6ba518d7b3c1732070667b0b82018fc5 | 3,642,649 |
import json
def file_to_dict(filename, data):
"""Converts JSON file to dict
:param filename: filename
:param data: string
:return: dict object
"""
try:
try:
json_data = to_json(data)
return json.loads(json_data)
except Exception as _:
return... | 3d6ff02246081dce83097545b5290dbbeedddab7 | 3,642,650 |
def reorganizeArray(id_A, id_B, gids_tuple, unordered_coordinates ):
"""
From a tuple of genome ID's representing a coordinate array's structure (gidI, gidJ).
and the corresponding coordinate np-array (n x 4) of design [[locI1, locJ1, fidI1, fidJ2, Kn, Ks],
... | c4ac1add615f21e4238ad3cd65e1fb9797c02b27 | 3,642,651 |
def compile_model_output(i,j,files,model):
""" compiles the model variables over severl files into a single array at a j,i grid point.
Model can be "Operational", "Operational_old", "GEM".
returns wind speed, wind direction, time,pressure, temperature, solar radiation, thermal radiation and humidity.
"... | d42b3b8b4222b1ac15d1f8d7643c994efec0bb5e | 3,642,652 |
def read_audio(path, Fs=None, mono=False):
"""Read an audio file into a np.ndarray.
Args:
path (str): Path to audio file
Fs (scalar): Resample audio to given sampling rate. Use native sampling rate if None. (Default value = None)
mono (bool): Convert multi-channel file to mono. (Default... | 6b3f88ae00b1d9dab8016b33cc5a2d7c58d5b87e | 3,642,653 |
import os
import re
import sys
def energies_from_mbe_log(filename):
"""Monomer dimer energies from log file."""
monomers, dimers, trimers, tetramers = {}, {}, {}, {}
hf, os_, ss_ = True, False, False
mons, dims, tris, tets = True, False, False, False
energies = False
def storeEnergy(dict_, k... | ef7fdae5580a490423b42714d6f1b5c3a8485b09 | 3,642,654 |
from numpy import array
def build_varied_y_node_mesh(osi, xs, ys, zs=None, active=None):
"""
Creates an array of nodes that in vertical lines, but vary in height
The mesh has len(xs)=ln(ys) nodes in the x-direction and len(ys[0]) in the y-direction.
If zs is not None then has len(zs) in the z-directi... | 878386f1b815840d198de106f57e11883aec3d1c | 3,642,655 |
def self_quarantine_end_10():
"""
Real Name: b'self quarantine end 10'
Original Eqn: b'50'
Units: b'Day'
Limits: (None, None)
Type: constant
b''
"""
return 50 | bb5fa131866d337460a37237b711d8c21588250d | 3,642,656 |
import analysis as an
import phasecurves as pc
from astropy.io import fits as pyfits
import pyfits
def spexsxd_scatter_model(dat, halfwid=48, xlims=[470, 1024], ylims=[800, 1024], full_output=False, itime=None):
"""Model the scattered light seen in SpeX/SXD K-band frames.
:INPUTS:
dat : str or numpy a... | e4653a62f7d98a253034fd2908d4231ca23cff8b | 3,642,657 |
def newff(minmax, size, transf=None):
"""
Create multilayer perceptron
:Parameters:
minmax: list of list, the outer list is the number of input neurons,
inner lists must contain 2 elements: min and max
Range of input value
size: the length of list equal to the number of laye... | b488298fea98877cd7097374576722ea4b24e9c3 | 3,642,658 |
import importlib
def write(*args, package="gw", file_format="dat", **kwargs):
"""Read in a results file.
Parameters
----------
args: tuple
all args are passed to write function
package: str
the package you wish to use
file_format: str
the file format you wish to use. D... | b7246e035f13b60fc8047abd768fae4bb1937600 | 3,642,659 |
def photo(el, dict_class, img_with_alt, base_url=''):
"""Find an implied photo property
Args:
el (bs4.element.Tag): a DOM element
dict_class: a python class used as a dictionary (set by the Parser object)
img_with_alt: a flag to enable experimental parsing of alt attribute with img (set by th... | 304fea5700a8fcc2b95636265dbbc9c5c6dd1635 | 3,642,660 |
def calc_TOF(t_pulse, t_signal):
"""Calculate TOF from pulse and signal time arrays."""
tof = []
idxs = [-1]
dbls = []
for t in t_signal:
idx = bisect_left(t_pulse, t)
if idx == len(t_pulse):
t_0 = t_pulse[-1]
else:
t_0 = t_pulse[idx - 1]
if id... | b58b14396c85f297e6454195fba597635b5fb54d | 3,642,661 |
def get_nodes_ips(node_subnets):
"""Get the IPs of the trunk ports associated to the deployment."""
trunk_ips = []
os_net = clients.get_network_client()
tags = CONF.neutron_defaults.resource_tags
if tags:
ports = os_net.ports(status='ACTIVE', tags=tags)
else:
# NOTE(ltomasbo: if ... | 5472d184a4483355c81679ec6df41bc16ca7b32e | 3,642,662 |
def get_visualizations_info(exp_id, state_name, interaction_id):
"""Returns a list of visualization info. Each item in the list is a dict
with keys 'data' and 'options'.
Args:
exp_id: str. The ID of the exploration.
state_name: str. Name of the state.
interaction_id: str. The intera... | 6ce3875be2244bcb3564d1ca006db62f56883a7f | 3,642,663 |
def push(array, *items):
"""Push items onto the end of `array` and return modified `array`.
Args:
array (list): List to push to.
items (mixed): Items to append.
Returns:
list: Modified `array`.
Warning:
`array` is modified in place.
Example:
>>> array = [... | 2c43c6b4c5691d7f40601cdb7747ecf6e063f778 | 3,642,664 |
import csv
def compute_list(commandline_argument):
"""
Returns a list of booking or revenue data opening booking data file with
first parameter
"""
# utf-8_sig
# Open booking CSV and read everything into memory
with open(commandline_argument, "r", encoding="shift_jis") as database:
... | 115725f5ab35c04412a2fe4f982a72c6b2e4c297 | 3,642,665 |
import re
def calculate_saving(deal, item_prices):
"""
Parse the deal string and calculate how much money is saved
when this deal gets applied. Also returns deal requirement.
Args:
deal (str): deal information
item_prices (dict): {item: price}
Returns:
requirements (collect... | b67e5c53551866a8b390eb49fa4bc29ff9d3261a | 3,642,666 |
def fetchone_from_table(database, table, values_dict, returning):
"""
Constructs a generic fetchone database command from a generic table with provided table_column:value_dictionary mapping.
Mostly used for other helper functions.
:param database: Current active database connection.
:param table: ... | 8b757bb5e9e7ba50a335a4917630543ef6989714 | 3,642,667 |
import os
def recover_buildpack(app_folder):
"""
Given the path to an app folder where an app was just built, return a
BuildPack object pointing to the dir for the buildpack used during the
build.
Relies on the builder.sh script storing the buildpack location in
/.buildpack inside the contain... | e82f70b06caee2d275820136e58c2b5b5860f5d5 | 3,642,668 |
def ParseMultiCpuMask(cpu_mask):
"""Parse a multiple CPU mask definition and return the list of CPU IDs.
CPU mask format: colon-separated list of comma-separated list of CPU IDs
or dash-separated ID ranges, with optional "all" as CPU value
Example: "0-2,5:all:1,5,6:2" -> [ [ 0,1,2,5 ], [ -1 ], [ 1, 5, 6 ], [ 2... | c114d931567ba3fdfc50b3eb7cd6cc7764bdd1d6 | 3,642,669 |
def _call(arg):
"""Shortcut for comparing call objects
"""
return _Call(((arg, ), )) | d7ec1e0c29b52f7d77daec3d2fa7c5f8ba6ea1f8 | 3,642,670 |
from typing import List
def gather_directives(
type_object: GraphQLNamedType,
) -> List[DirectiveNode]:
"""Get all directive attached to a type."""
directives: List[DirectiveNode] = []
if hasattr(type_object, "extension_ast_nodes"):
if type_object.extension_ast_nodes:
for ast_node... | 211108bd35940e412e68e0b092ada050ce745c8e | 3,642,671 |
def get_request(language=None):
"""
Returns a Request instance populated with cms specific attributes.
"""
request_factory = RequestFactory()
request = request_factory.get("/")
request.session = {}
request.LANGUAGE_CODE = language or settings.LANGUAGE_CODE
request.current_page = None
... | 1ef86666693118ccd36f8d9818e70566e895cb13 | 3,642,672 |
from typing import cast
def validate_hash(value: str) -> bool:
"""
Validates a hash value.
"""
return cast(bool, HASH_RE.match(value)) | c273e5287e2e0448c2e58173813d725f61f3210a | 3,642,673 |
def string_to_digit(string, output):
"""Convert string to float/int if possible (designed to extract number
from a price sting, e.g. 250 EUR -> 250)
:argument string: string to convert
:type string: str
:argument output: output type
:type output: type
:returns float/int or None
"""
... | dc83485e7ffa4548aee019b67f23ba6db385421d | 3,642,674 |
def calc_B_phasors(current, xp, yp, cable_array):
"""It calculates the phasors of the x and y components of the
magnetic induction field B in a given point for a given cable.
Given the input, the function rectifies the current phase
extracting respectively the real and imaginary part of it.
Then, ... | 66f696121f3a26a99e4d662b3680d21199bedcc1 | 3,642,675 |
def get_shortest_text_value(entry):
"""Given a JSON-LD entry, returns the text attribute that has the
shortest length.
Parameters
----------
entry: dict
A JSON-LD entry parsed into a nested python directionary via the json
module
Returns
-------
short_text: str
... | c63511a830f56c610230e0c7e208a926b0304b3c | 3,642,676 |
from datetime import datetime
def generate_token(user_id, expires_in=3600):
"""Generate a JWT token.
:param user_id the user that will own the token
:param expires_on expiration time in seconds
"""
secret_key = current_app.config['JWT_SECRET_KEY']
return jwt.encode(
{'user_id': user_i... | 62a92d7903e941446dbef3097b12ba2adf9a1fd5 | 3,642,677 |
import codecs
def debom(s):
"""
此函数是去除字符串中bom字符,
由于此字符出现再文件的头位置
所以对csv 的header造成的影响, 甚至乱码
通过此函数可以避免这种情况
"""
boms = [ k for k in dir(codecs) if k.startswith('BOM') ]
for bom in boms:
s = s.replace(getattr(codecs, bom), '')
return s | 4ac056a8ba93f00a0a31e3a447e62810c5b68687 | 3,642,678 |
def rolling_window(array, window):
"""
apply a rolling window to a np.ndarray
:param array: (np.ndarray) the input Array
:param window: (int) length of the rolling window
:return: (np.ndarray) rolling window on the input array
"""
shape = array.shape[:-1] + (array.shape[-1] - window + 1, wi... | cde677c20c6a4d5f096d2f36bae2fc1087b73ccf | 3,642,679 |
def calculate_timezone_distance_matrix(df):
"""
Calculate timezone distance matrix from a given dataframe
"""
n_users = len(df)
timezone_df = df[['idx', 'timezone', 'second_timezone']]
timezone_df.loc[:, 'timezone'] = timezone_df.timezone.map(
lambda t: remove_text_parentheses(t).split('... | d788ab8758d0300516ecde2749cd438597775440 | 3,642,680 |
import platform
def pyxstyle_path(x, venv_dir="venv"):
"""Calculate the path to py{x}style in the venv directory relative to project root."""
extension = ".exe" if platform.system() == "Windows" else ""
bin_dir = "Scripts" if platform.system() == "Windows" else "bin"
return [str(path_here / f"{venv_di... | 2eaf3686f20db6ca26b55dc5cf065e926d6fd5ef | 3,642,681 |
def update_tc_junit_resultfile(tc_junit_obj, kw_junit_list, tc_timestamp):
"""loop through kw_junit object and attach keyword result to testcase
Arguments:
1. tc_junit_obj = target testcase
2. kw_junit_list = list of keyword junit objects
3. tc_timestamp = target testcase timestamp
"""
for m... | 97c85b6b197a5e325c51bcb70d0f7e173f1feb1d | 3,642,682 |
from OpenGL.error import GLError
def checkFramebufferStatus():
"""Utility method to check status and raise errors"""
status = glCheckFramebufferStatus( GL_FRAMEBUFFER )
if status == GL_FRAMEBUFFER_COMPLETE:
return True
description = None
for error_constant in [
GL_FRAMEBUFFER_INCO... | 9a603cde0b4f9cda340f969eb8b8137cbf34fede | 3,642,683 |
def load_sentences(filename):
"""give us a list of sentences where each sentence is a list of tokens.
Assumes the input file is one sentence per line, pre-tokenized."""
out = []
with open(filename) as infile:
for line in infile:
line = line.strip()
tokens = line.split()
out.a... | 6a4c458f9a0d9b17eaa38c38570dacc4c40e86c0 | 3,642,684 |
def imageSequenceRepr(files, strFormat='{pre}[{firstNum}:{lastNum}]{post}', forceRepr=False):
""" Takes a list of files and creates a string that represents the sequence.
Args:
files (list): A list of files in the image sequence.
format (str): Used to format the output. Uses str.format() command and requires the ... | 9f8b63594eb86f54bf8d264b12bd006c2c50da20 | 3,642,685 |
def farthest_point_sampling(D, k, random_init=True):
"""
Samples points using farthest point sampling
Parameters
-------------------------
D : (n,n) distance matrix between points
k : int - number of points to sample
random_init : Whether to sample the first point random... | d5ab5c3f30048cd16bf38bc73bf48f58f88ef383 | 3,642,686 |
def part2(lines):
"""
>>> part2(load_example(__file__, '9'))
982
"""
return run(lines, max) | c243792fc4b3e32a5bc41f5185cbbe1ef2d6b840 | 3,642,687 |
import os
import subprocess
import shlex
import pandas
def load_description():
"""
Reads pandas dataframe with name(description) and category for FG phenos
"""
description = "./description.txt"
if not os.path.isfile(description):
cmd = f"gsutil cp {pheno_description} {description}"
... | 91d2cb5bf2a4224ae912db59c417d2ca293edd35 | 3,642,688 |
def get_utility_function(args):
"""
Select the utility function.
:param args: the arguments for the program.
:return: the utility function (handler).
"""
if args.mode == 'entropy':
utility_function = compute_utility_scores_entropy
elif args.mode == 'entropyrev': # Reverse entropy m... | fc49a9f3456a187b6015c9fbbdaa4faba0dfc778 | 3,642,689 |
def convertRequestToStringWhichMayBeEmpty(paramName, source):
""" Handle strings which may be empty or contain "None".
Empty strings should be treated as "None". The "None" strings are from the timeSlicesValues
div on the runPage.
Args:
paramName (str): Name of the parameter in which we ar... | d620197e60e15d48d450a9406cbe3f4ea61a64d8 | 3,642,690 |
import re
def find_am(list_tokens:list):
"""[summary]
Parameters
----------
list_tokens : list
list of tokens
Returns
-------
tuple(list,list)
matches tokens,
token indexes
"""
string = "START"+" ".join(list_tokens).lower()
match = re.findall(am_p... | 91663e71882764045d679b24c5cb793f1c192410 | 3,642,691 |
import os
def fetch_seq_assembly(mygroup, assembly_final_df, keyargs):
"""
Function that will fetch the genome from the taxid in group and
concat the assembly that is created by ngs
"""
keyargs['taxids'] = [str(taxid) for taxid in mygroup.TaxId.tolist()]
#ngd.download(**keyargs)
get_c... | 8e289038d17b9e75ef0d608b63828c82048080cc | 3,642,692 |
def calculate_min_cost_path(source_node: int, target_node: int, graph: nx.Graph) -> (list, int):
"""
Calculates the minimal cost path with respect to node-weights from terminal1 to terminal2 on the given graph by
converting the graph into a line graph (converting nodes to edges) and solving the respective s... | ad48d0930f010ffa04f142710bd7f3aafd932e76 | 3,642,693 |
def promote(name):
"""
Promotes a clone file system to no longer be dependent on its "origin"
snapshot.
.. note::
This makes it possible to destroy the file system that the
clone was created from. The clone parent-child dependency relationship
is reversed, so that the origin fi... | 7d6ddd76525096c13f7ff4b1a07121d52e688b24 | 3,642,694 |
def otp_verification(request):
"""Api view for verifying OTPs """
if request.method == 'POST':
serializer = OTPVerifySerializer(data = request.data)
if serializer.is_valid():
data = serializer.verify_otp(request)
return Response(data, status=status.HT... | 513dff831deca69a8087fe99d27f1f54108d4ae2 | 3,642,695 |
import os
def parse_tag_file(doc: ET.ElementTree) -> dict:
"""
Takes in an XML tree from a Doxygen tag file and returns a dictionary that looks something like:
.. code-block:: python
{'PolyVox': Entry(...),
'PolyVox::Array': Entry(...),
'PolyVox::Array1DDouble': Entry(...),
... | 9b35f07a63df87a3aa4f95d5ce87a813d2d73ea3 | 3,642,696 |
def hpd_grid(sample, alpha=0.05, roundto=2):
"""Calculate highest posterior density (HPD) of array for given alpha.
The HPD is the minimum width Bayesian credible interval (BCI).
The function works for multimodal distributions, returning more than one mode
Parameters
----------
sample : ... | ee3a24f056a038b5e9ec08875d37f39e0a8180f1 | 3,642,697 |
import sys
def get_internal_modules(key='exa'):
"""
Get a list of modules belonging to the given package.
Args:
key (str): Package or library name (e.g. "exa")
"""
key += '.'
return [v for k, v in sys.modules.items() if k.startswith(key)] | d97618ba37ad403a74fc13a7587c6369fab540fb | 3,642,698 |
import re
def emph_rule(phrase: str) -> Rule:
"""
Check if the phrase only ever appears with or without a surrounding \\emph{...}.
For example, "et al." can be spelled like "\\emph{et al.}" or "et al.", but it should be
consistent.
"""
regex = r"(?:\\emph\{)?"
regex += r"(?:" + re.escape(... | a6eb0eb716a265876efd857dd51dc6106a24f35b | 3,642,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.