content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def topleftlatlon_from_wkt(wkt_string):
"""Returns the (lat, lon) of the top-left point of a WKT string."""
wkt_type = wkt_string.split('(', 1)[0].rstrip(' ')
coord_string = wkt_string.lstrip(wkt_type + ' (')
if wkt_type not in ('POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT',
'MU... | c26b6eb78d8e9dca3ab38e04470cc025a15db4fa | 65,979 |
import time
def __date_since_epoch__(value):
"""Internal function used for Unix datetime format"""
day = time.strftime('%d',time.localtime(value))
month = time.strftime('%m',time.localtime(value))
year = time.strftime('%Y',time.localtime(value))
return day,month,year | 34e8ee15f7fa5d6f662a7850b3252a37a3926371 | 65,980 |
def get_unobs_nd_names(gname):
"""
For a graph named gname, this method returns a list of the names of its
unobserved nodes (i.e., either [], or ["U"] or ["U1", "U2"])
Parameters
----------
gname : str
Returns
-------
list[str]
"""
if gname in ["G2", "G3", "G5", "G6", "G10... | 3450293f464b1e7cc7ab343888a606bd96d0f094 | 65,982 |
def extract_archive(filename, path):
"""
Extract the contents of the given archive
:param filename: The name of the crx file
:param path: The path to the crx file
:return: Whether the contents of the crx file were extracted successfully or not
"""
dst_dir = os.path.join(get_script_path(), ... | 6307dafb19ddf5cef64dc6022e38cd0a15bf37eb | 65,983 |
import logging
def get_commodity_sources():
"""
Get a table with prices and emissions manly for 2014.
Returns
-------
pd.DataFrame
Examples
--------
>>> get_commodity_sources().loc[2014, 'hard coal']['emission'] * 1000
0.0934
"""
logging.info("Get prices and emissions for... | b8648a0c2abd8d02f00fca8fd4b945fb4d5ca6bd | 65,984 |
def named_entity(docs):
"""Creates a named entity visualization.
Taken from https://github.com/wandb/client/blob/master/wandb/plots/named_entity.py
"""
spacy = util.get_module(
"spacy",
required="part_of_speech requires the spacy library, install with `pip install spacy`",
)
ut... | e217e244ceef03e62decfdcfb1985171733eedea | 65,987 |
def brightness_state(value):
"""
Returns the brightness and state according to the current data of given
value.
"""
if value.data > 0:
return (value.data / 99) * 255, STATE_ON
else:
return 255, STATE_OFF | c8e6e8dfcf27bd62164478dbf1d899727246329e | 65,988 |
def find_matching_segments(gt_segments, id_key, sensed_segments):
"""
id_key represents the kind of segment that we are find matches for. e.g.
- trip_id for trips
- section_id for sections
"""
matching_segments_map = {}
if len(sensed_segments) == 0:
print("Found no sensed segmen... | e94f26b335d1c42af9a8fd1182dbee986543bb80 | 65,989 |
from typing import List
def recall_at_k(y_true: List[int], y_pred: List[List[np.ndarray]], k: int):
"""
Calculates recall at k ranking metric.
Args:
y_true: Labels. Not used in the calculation of the metric.
y_predicted: Predictions.
Each prediction contains ranking score of a... | cecf2ec6fc3e0d071672c096f42063a3962e081e | 65,990 |
def has_datapoint_with_all_dims(fake_ingest, dims):
"""
Tests if any datapoints has all of the given dimensions
"""
for datapoint in fake_ingest.datapoints:
if has_all_dims(datapoint, dims):
return True
return False | 9c3ed9ab42d6ac5eae80c30aaf6b8d123520601d | 65,991 |
def norm_weight(nin, nout=None, scale=0.01, ortho=True, **kwargs):
"""
Get a (orthogonal) Gaussian weight matrix W, scaled
if desired (and not orthogonal).
:param nin:
:param nout:
:param scale:
:param ortho:
:return W:
"""
logger.warn('Norm weight with range: +/-{}'.format(scale... | ce8120ec5e9a65bcfc5862bb95706b619049d194 | 65,992 |
def key_is_private(key):
"""Determine if a key has a name indicating it is private
"""
if PRIVATE_RE.search(key):
return True
else:
return False | 99809e5e0ea1e87b9deb7d01c01d2f9a83b73edc | 65,993 |
def anonymise_related_objects(obj, anonymised=None):
"""
See if there are any related models which need to be anonymised.
They will be any reverse relations to PrivacyModel subclasses where their
OneToOneField and ForeignKey on_delete is ANONYMISE.
"""
if anonymised is None:
anonymised ... | d1f168dbb42df28c44b19e2b7cae86c672d8794e | 65,994 |
import inspect
def all_links(cls):
"""
Each object will have the attributes declared directly on the object in the attrs dictionary. In addition there
may be attributes declared by a particular object's parent classes. This function walks the class hierarchy to
collect the attrs in the object's parent... | 2e3b1e4e527d339b0972345c81b6967857e54298 | 65,997 |
from typing import Dict
from typing import Callable
def get_losses_dict(
names_list: list = [],
) -> Dict[str, Callable]:
"""Get a dict with all the loss functions for semi supervised training.
The training step of a given model will iterate over these, instead of
manually computing each.
Args:
... | 9d6906b1a654b4e09d5a39753bf2e1955dd535ad | 65,998 |
def prepare(data, args):
"""
Run trimming and fastq for each fastq file
"""
workdir = op.abspath(safe_makedir("prepare"))
sample = data['name']
data['trimmed'] = _trimming(data['fastq'], workdir, data['name'], args.is_rrbs, args.is_directional)
return data | 79eed3f800acbf1d1ceb140913e1a10679053043 | 65,999 |
def individual_margin_diversity(i, ensemble_proba, target, alpha = 0.2):
"""
Computes the individual diversity of the classifier wrt. to the ensemble and its contribution to the margin. alpha controls the trade-off between both values. The original paper uses :math:`\\alpha = 0.2` in all experiments and reports... | 3d1e2976a383a77c698941883935dc7f89301fa3 | 66,000 |
def qr_for_geolocation(**kwargs):
"""Accepts a *'coordinates'* keyword argument or a triplet *'latitude'*, *'longitude'*, and *'altitude'*."""
return _make_geolocation_qr_code(embedded=True, **kwargs) | 712d94b13deec9c6020057c97507f2e24fc7e577 | 66,001 |
import requests
def update_host(token, current_ip, domain, subdomain='@'):
"""
Formulate and Execute an Update request on EntryDNS API for a given access token / IP
Args:
token: (string) Access Token for an EntryDNS Domain
current_ip: (string) IP to point EasyDNS Domain to
domain:... | ad9b97be6643ecb3662275aeb3dcda14ed08baf6 | 66,002 |
def nick_that_sent_message(tags, prefix):
"""Returns a nick that sent the message based on the given data passed to
the callback.
"""
# 'tags' is a comma-separated list of tags that WeeChat passed to the
# callback. It should contain a tag of the following form: nick_XYZ, where
# XYZ is the nick... | 973121bdf85d4a1c3df8f388f3564c8df5b4fb07 | 66,003 |
def Code_encoding(pred):
"""
Returns 2-D numpy array with codes corresponding to it's type in predict vector
0 column is peninsula cnt
1 column is bay cnt
pred: numpy 1-D array with types of puzzles
"""
code = np.ones((pred.shape[0], 2), dtype=int)
for i, typ in enumerate(pred):
... | b7d4e8a0df91363be493881ceb42a27871debcc1 | 66,004 |
from typing import Union
import pathlib
def pathlibify(item: Union[str, pathlib.Path]) -> pathlib.Path:
"""Converts string 'path' to pathlib.Path object.
Args:
item (Union[str, pathlib.Path]): either a string summary of a
path or a pathlib.Path object.
Returns:
pathlib.Path o... | cca9d213d47bb5033157887c5e19994020684331 | 66,005 |
import torch
def get_topk_logits_selector(logits, k=3):
""" takes logits[batch, nout, voc_size] and returns a mask with ones at k largest logits """
topk_logit_indices = torch.topk(logits, k=k).indices.cpu()
# indices = torch.stack([
# (torch.range(start=0, end=logits.shape[0] * logits.shape[1] * ... | d9b2b83da1856c5d355c22257b3acc4c445f5960 | 66,006 |
async def upload_tracks(csv_file: UploadFile = File(...)):
"""Upload a utf-8 encoded CSV file containing columns (with headings):
- `provider`
- `license`
- `title`
- `artist`
- `external_url`
- `mp3` (as url of audio file in format ffmpeg can read)
- `internal_preview_uri` (optional)
... | aa7d9768e97d2b3d5f5566ad1e41d482cebddb66 | 66,007 |
def and_(left: ds.Expression, right: ds.Expression) -> ds.Expression:
"""
Given a left and right expression combined them using the `AND` logical operator
Parameters
----------
left : pyarrow._dataset.Expression
A Dataset `Expression` to logically `AND`
right : pyarrow._dataset.Expressi... | e9ace739045a2c9421ed3bc65b0058ceb83c9225 | 66,008 |
from re import T
def interp(times, values, fill=0, name=None, **kw):
""" Generic interpolation function of t given `times` and `values`
Imterpolator such that:
f(times[i]) = values[i]
if t < times[0] or t > times[-1]:
f(t) = fill
See ``scipy.interpolate.interp1d`` for details of interp... | e288400d30613ebe66492a4e7751418a7cb66130 | 66,009 |
def rename_target(blend_shape, target, new_name):
"""
Rename the given blendshape target
:param blend_shape: str, name of blendshape to rename target from
:param target: str, blenshape target to rename
:param new_name: str, new name for the blendshpae target
:return: str
"""
check_blend... | c44ad137fe54ad2c88826045985104a685c34982 | 66,010 |
from scipy.stats import ks_2samp
def p_value_inflation_test(p_values):
"""
Test for p-value inflation using the Kolmogorov-Smirnov test.
However there are no assumptions to fail for this test.
:param p_values: array of p-values
:return: p-value (significant is bad)
"""
h_null = np.random.... | 57ad6124b56e799f1dcd2505392a089e52e1cdcb | 66,011 |
from typing import Dict
def templated_supplier(supplier_map: Dict[str, ValueSupplierInterface],
engine: RecordProcessor) -> ValueSupplierInterface:
"""
Creates a supplier that populates the template string from the supplier map
Args:
supplier_map: map of field name -> value... | 9a05242c309a8405b3ca5590609cf45f86fe06da | 66,012 |
def fp_mask_to_list(fp_mask):
"""Parse a fp_mask, eg 1-4,2,3 or 0x202
Returns fp cpus based on given mask
"""
if '0x' in fp_mask:
fp_cpus = [i for i in range(0, 64) if (1 << i) & int(fp_mask, 16)]
else:
fp_cpus = []
for rule in fp_mask.split(','):
if '-' in rule... | 6819495ac608d9e94845581da7567f56aebe51c9 | 66,013 |
def get_sub_objects(obj):
"""Get all the children of an object that were extracted and
are BioPaxObjects that need to be registered in the model."""
sub_objs = []
for attr in [a for a in dir(obj) if not a.startswith('__')]:
val = getattr(obj, attr)
if isinstance(val, BioPaxObject):
... | e76b0dd856e6e9e0abdac7e22adce5ad651ddf3e | 66,014 |
def color_check(origin_color: list, target_color: list) -> bool:
"""
Function that check if it is the color we're looking for in C.I.
Set C.I. properly for handling between accuracy and robustness.
"""
CI = 20 # Confidential Interval
if target_color[0]-CI <= origin_color[0] <= target_color[0]+CI\
and target_col... | 4a9e72f10779174eaa409ffb1aa2fe657382ba4a | 66,015 |
def get_obesity_label_bmi(pct, bmi, age, gender):
"""
Returns the obesity label as underweight, normal, overweight, obese, class I or class II severe obesity
"""
if 0 <= pct < 0.05:
return 'underweight'
elif 0.05 <= pct < 0.85:
return 'normal'
elif 0.85 <= pct < 0.95:
ret... | e04ea231b880ac3b20e6dc281d2b5ee0f0bf6d93 | 66,016 |
def make_bin_mtx(num_mtx, aa_table):
"""
Convert a numeric matrix into a binary matrix.
Each column of the alignment occupies a submatrix that has as many columns
as there are letters in the amino acid alphabet.
If we consider an amino acid alphabet of 21 letters
(all standard 20 amino acids pl... | e59d0fc187e2a15b646a298594e327f6ceed116b | 66,017 |
import gzip
import pickle
def read_pickle(filename):
"""
Helper to read pickle file which may be zipped or not.
Args:
filename (str): A valid string path.
Returns:
The file object.
"""
try:
with gzip.open(filename, "rb") as f:
loaded_object = pickle.load(f... | 3ea50f95713570075f14977591e17bad68ef9d24 | 66,018 |
def y0(si):
"""The initial conditions for y
:param si: the simulation info object
:type si: SimInfo
"""
i = 0
end_pg = 1 + si.n_pg
end_dg = 1 + si.n_pg + si.n_dg
f = np.zeros(shape=(si.n_entries(),), dtype=float)
f[i] = 1.0 # power is normalized is 1
for j in range(0, si.n_pg):... | 464d90692b405ec388e9a211637d4cc92924e28d | 66,019 |
def show_saxs_qmap(
img,
pargs,
width=200,
vmin=0.1,
vmax=300,
logs=True,
image_name="",
show_colorbar=True,
file_name="",
show_time=False,
save=False,
show_pixel=False,
aspect=1,
save_format="png",
cmap="viridis",
):
"""
Show a SAXS q-map by giving
... | 53155ac1b6de4936ce5272ccb7caceed4478e377 | 66,021 |
def load_img(path, gs=False):
"""Load an image and return it as a numpy ndarray"""
image = Image.open(path)
if gs: #Convert to single-channel greyscale, if desired
image = image.convert('LA')
width, height = image.size
return np.array(image)[0:height, 0:width, 0]
return np.array(... | d50869bd3ea7f99f402e7518e8a4907e1d9a4037 | 66,022 |
def results(hometeam, awayteam, scores_mat):
"""
Predict head-to-head score function
input:
hometeam: name of the home team as string
awayteam: name of the away team as string
scores_mat: stores the scores
output:
The result of the game
"""
#hometeam, awaytea... | 364e3731cd79c7c6d820a23ca13427cd1cd12fd6 | 66,023 |
def decimate_within_epochs(tsfinname, finname, foutname, dtype, sos,
buffer_len=16777216, max_len=None):
"""Docstring goes here.
This is TEMPORARY! Not how Jagular should be used! But we need resultzzz.
So, this function takes in a memmapped raw channel (say 15 GB) and an
IN... | d7c52ef3d3998b23789ca076c778755c1060228f | 66,024 |
import multiprocessing as mp
def gen_new_phiw_div_phib_arr(N_PROCESSES, phiw_div_phib_arr_new, cond_GT, fcn_D, fcn_eta, z_div_L_arr, phiw_div_phib_arr, Pi_div_DLP_arr, weight, gp_arr, gm_arr, yt_arr, phi_yt_arr, ID_yt_arr, Ieta_yt_arr):
""" Calculation phi_w/phi_b at the given z using Eq. (D3) in [1]
The deta... | 304be2f26d1df4414c8cd248fbc2f7d3eaa3217d | 66,027 |
from typing import Counter
def getRepeatedList(mapping_argmat, score_mat_size):
"""
Count the numbers in the mapping dictionary and create lists that contain
repeated indices to be used for creating the repeated affinity matrix for
fusing the affinity values.
"""
count_dict = dict(Counter(mapp... | fa2449379bf8bf2051c2492d56de11c2ee0191e4 | 66,028 |
def particle_velocity_fields(model, save, space_order):
"""
Create the particle velocity fields
"""
if model.grid.dim == 2:
x, z = model.space_dimensions
stagg_x = x
stagg_z = z
# Create symbols for forward wavefield, source and receivers
vx = TimeFunction(name='v... | c1897347d78423a9c725f7f57f8446ad1a7fbf0d | 66,029 |
import time
def _random_fixed_norm_serial(shape, dtype, seed, norm):
""" Handles `random_fixed_norm` for `serial=False`.
"""
if seed is None:
seed = int(time.time())
key = jax.random.PRNGKey(seed)
matrix = jax.random.normal(key, shape=shape, dtype=dtype)
if norm is not None:
matrix *= norm / jnp.l... | bf4e6c2dfcef6dc3938c6fc2cb4e8d08a8bbabef | 66,030 |
import torch
def model_logprobs(model, collator, input_texts, output_texts, length_penalty=0, batchsize=128):
"""Computes logprobabilities of input and output texts for a given model
Inputs:
model: conditional generation model to use
collator: collator to process texts
input_texts: it... | 721ea1b5e7d934d92dbb2ecacef0bc318a25be25 | 66,031 |
def no_repeats(n):
"""Returns number of arrangments with no repeats."""
return sum((-1)**k * comb(n//2, k) * num_pairs(n - 2*k) for k in range(n//2+1)) | 6af59c4e599cc151b6973eac74611837de93dbb6 | 66,034 |
def process(orography, landmask, site_list, metadata_dict=None,
all_methods=False, land_constraint=None, minimum_dz=None,
search_radius=None, node_limit=None, site_coordinate_system=None,
site_x_coordinate=None, site_y_coordinate=None):
"""Module to create neighbour cubes for ext... | 92fd5eb6b5ce7ad7c2facb8bf95c6e0d61a3e38a | 66,035 |
def _get_text_alignment(point1, point2):
"""Get the horizontal and vertical text alignment keywords for text placed at the end of a line segment from point1 to point2
args:
point1 - x,y pair
point2 - x,y pair
returns:
ha - horizontal alignment string
va - vertical alignment s... | 317860030bf86750207bc891c236ad2618c686b1 | 66,036 |
def ldns_rr_list2buffer_str(*args):
"""LDNS buffer."""
return _ldns.ldns_rr_list2buffer_str(*args) | 658912718ede1b21d2238929cfd7e782bf8bf72a | 66,037 |
def param(key, **kwargs):
"""Decorator for Agent operation functions to assist with checking
params prior to actually trying to execute the code. Example::
class MyAgent:
...
@param('voltage', type=float)
@param('delay', default=0., type=float)
@inlineCallbacks
de... | 910dd83169b86b6f432c24a6c0ad320644aee9f2 | 66,038 |
def weights_none(mol):
"""
Calculates the QED descriptor using unit weights.
"""
return qed(mol,w=[1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00]) | da2cf2f634c13e52a44c804f70d2700f252066eb | 66,039 |
from typing import Set
from typing import Tuple
def unrecognized_footprints_check(bom_rows: Rows, footprint_index: int) -> str:
"""Return an error string if unrecognized footprints are detected."""
# Sweep through looking for acceptable vs unacceptable footprints:
unrecognized_footprints: Set[str] = set()... | 0bd6ae4ba675007f75efefadf75216a52cd94aee | 66,040 |
def sample_on_ellipsoid(numpts, radius=(1.,1.,1.), rot=(0.,0.,0.), trans=(0.,0.,0.)):
"""Sample points uniformly randomly on the surface of an ellipsoid.
Args:
- numpts (int): Number of points to sample
- radius (tuple, float): radius of each axis (X, Y, Z) of the ellipsoid
- rot (np.array): rotation parameter... | 58671be659ea646ff3b02859d2a09879de6a27f6 | 66,041 |
from typing import Any
def avro_mocked_request(data: Any, schema: Any, **kwargs) -> web.Request:
"""For testng purposes."""
return mocked_request(MinosAvroProtocol.encode(data, schema), content_type="avro/binary", **kwargs) | 4cf99dc403c1559968d596804523d0b7fc49b04d | 66,042 |
def MOLT_query(collection):
"""
Returns a list of the possible MOLT (objects) that contain the collection. Accepts
either a list of midi tones, a list of strings, a list of pitch objecs,
or a list of note objects.
"""
# Convert everything to pitch classes.
query_collection = set()
if all(isinstance(x, int) or i... | ce4040e6701b61f1d468f4274de74986388b3feb | 66,043 |
import json
def admin_team_insert():
""" API for inserting a team """
prv_id = None
team_id = None
prjid = None
bgt_id = None
teamname = request.form['Name']
div_id = clean_jsgrid_int(request.form['DivisionID'])
myids = admindb.AdmIDs(prv_id, team_id, prjid, bgt_id, div_id)
retu... | 63122cabf8bc6f7d423f70e722ad2ff91aea0ac2 | 66,044 |
def wavenumber(f, er=1, ur=1):
"""Calculate freespace wavenumber of dielectric material (or vacuum).
Typically represented by: k
Args:
f: frequency, in units [Hz]
er: relative permittivity
ur: relative permeability
Returns:
np.ndarray: freespace wavenumber, in units [1... | d4fb4d3cf861d6d13308e9d487100465f104c2a1 | 66,045 |
import re
def getPolyPhen2input(data, filesize=150000):
"""
Reads data and creates files needed for PolyPhen2 input. Saves and returns
file names to be used as input. File size is restricted to 150000.
Arguments:
data = dataframe containing COSMIC data
filesize = int restricting lines ... | 811f0290f15e73d28d8a0685a7a360194090a40f | 66,046 |
def load_cell_expression_5platform(ncols=None, scaling='std', add_prefix=True):
"""Load 5-platform averaged cell line expression data, sub-select
columns of gene expression randomly if specificed, scale the
selected data and return a pandas dataframe.
Parameters
----------
ncols : int o... | fffca39904c1f790de7854631e023e29de667cb3 | 66,047 |
def normalize_rectangle(rect):
"""Normalizes a rectangle so that it is at the origin and 1.0 units long on its longest axis.
Input should be of the format (x0, y0, x1, y1).
(x0, y0) and (x1, y1) define the lower left and upper right corners
of the rectangle, respectively."""
assert len(rect) == 4, '... | b1a011948adb52bb6dea068116ab3a564ab2a1f8 | 66,048 |
def flip_joints_3d(joints_3d, width, joint_pairs):
"""Flip 3d joints.
Parameters
----------
joints_3d : numpy.ndarray
Joints in shape (num_joints, 3, 2)
width : int
Image width.
joint_pairs : list
List of joint pairs.
Returns
-------
numpy.ndarray
Flip... | 776057afbd195f1d17375a72cc0225e2e169c1de | 66,049 |
def forward(internal_func, f_x0, params_value, i, h):
"""Calculate the forward difference.
Args:
internal_func (func): A function with a 1d numpy array as it's only argument.
f_x0 (numpy array): The function value at params_value.
params_value (numpy array): The value column of param_df... | 6c2270e51904e11553ea3e335225b3308158c29a | 66,050 |
import inspect
import warnings
def valid_func_args(func, *args):
"""
Helper function to test that a function's parameters match the desired
signature, if not then issue a deprecation warning.
"""
keys = inspect.signature(func).parameters.keys()
if set(args) == set(keys):
return True
... | 4872817033ea55881442e69711b620b2853407f1 | 66,052 |
import pdb
def emlines_from_alis_output(alis_file):
""" Generate a list of emission lines from a standard ALIS output file
Currently loads
Parameters
----------
alis_file : str
Returns
-------
emlines : list
List of EmLine objects
"""
linelist = LineList('Galaxy')
... | 971a8267efd7f2acf8f78cde9f119e179be09ecb | 66,053 |
import re
def load_off(filename, verbose=True):
"""Load 3D model in .off format."""
with open(filename, 'r') as f:
obj_file = f.read().splitlines()
v = [] # list of vertices
f = [] # list of faces
e = [] # list of edges
num_vertices = None
num_faces = None
num_edges = None... | df03642b2270e149dc14587dbfa1df0505cad1b5 | 66,055 |
def share_get(context, share_id):
"""Get share by id."""
return IMPL.share_get(context, share_id) | c255a964fbee69c2c2ef402d4e05f4b1e43c9672 | 66,056 |
def put_ldap_group_schema_settings(
api_client,
group_required=None,
group_base=None,
group_id_attribute=None,
group_list_filter=None,
group_member_attribute=None,
group_member_attr_format=None,
group_search_scope=None,
**kwargs
):
"""Put update LDAP group schema settings # noqa... | 03b065fe95fa191d35c5904363381fdc3258bb55 | 66,057 |
def pp(obj, maxwidth=79):
"""
Pretty-print the given object.
"""
ctx = PrettyPrinter(maxwidth=maxwidth)
ctx.pp(obj)
return str(ctx) | a957f8093be00a04a81c727ee00eb697638b08ac | 66,058 |
def connect(addr, name=None, group=None, blocking=True, header_len=16, cache_size=-1):
"""
Creates a `HiSockClient` instance. See HiSockClient for more details
:param addr: A two-element tuple containing the IP address and
the port number of the server.
:type addr: tuple
:param name: A stri... | 8f98cd067a4d70d2ef2c1f292c27f7f4349fbd9c | 66,061 |
def bodypart(actions: Actions) -> Features:
"""Get the body part used to perform each action.
Parameters
----------
actions : Actions
The actions of a game.
Returns
-------
Features
The 'bodypart_id' of each action.
"""
return actions[['bodypart_id']] | bb9e325f608d4ca325d92f7e70973f561657c109 | 66,062 |
import shutil
def binary_available() -> bool:
"""Returns True if the GitHub CLI binary (gh) is
availabile in $PATH, otherwise returns False.
"""
return shutil.which("gh") is not None | e959757ccce6d162b225fd6ef986a7e248c606fa | 66,063 |
import copy
import six
def _config_list(conf_tuples=None, only_net=False, **kwargs):
"""
Return a list of dicts from the salt level configurations
conf_tuples
_LXCConfig compatible list of entries which can contain
- string line
- tuple (lxc config param,value)
... | 03a3e472784a132d6d65e480b17ffab77357607a | 66,064 |
def rectify_analysis(notice_xml, dry=False):
"""
Parses through the analysis section and fixes common problems:
- analysisSection with only a title: adds an empty analysisParagraph
"""
new_xml = deepcopy(notice_xml)
notice_analysis = new_xml.find('.//{eregs}analysis')
# If there is no noti... | cf9b0f2ce864445126c21e6c6ce1a9785e92c736 | 66,065 |
import torch
def add_k(c, active_k, max_k, gamma):
"""
replace the cluster indictors of 0 to active_K+1
:param c: a sparse matrix to indicate the cluster membership.
:return: a new sparse matrix to indicate the cluster membership.
"""
indices = c._indices()
values = c._values()
values... | 056acd7fcc7fd050e351a55d98003963bc22d5b5 | 66,067 |
def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False):
"""Parse the historical data in file handle fh from yahoo finance.
Parameters
----------
adjusted : bool
If True (default) replace open, high, low, close prices with
their adjusted values. The adjustment is by a scale fact... | 1899038f05d486f5af198ae411da11facd94ea8e | 66,068 |
def clean_colnames(
df: pd.DataFrame,
keep_names=True,
attr_name="column_map",
) -> pd.DataFrame:
"""Dataframe method, that applies :func:`clean_names` dataframe columns."""
return clean_names(df, keep_names=keep_names, attr_name=attr_name) | 1a4529239b46d243338762eb675767ab64b3e240 | 66,069 |
def getAllValidSequences(rule):
"""
Loops over all possible lists of three cards and returns the list of three
cards that are accepted by the given rule.
Parameters
----------
rule: Tree
The rule that we want to find valid cards for
Returns
-------
goodList: list
Li... | 0778295231226a44fb802d99ece815b6ffe9fcf7 | 66,071 |
def reverse_complement(sequence):
"""
Return reverse complement of DNA sequence.
"""
return ''.join(COMPLEMENT[b] for b in sequence[::-1]) | 4d416804b152c7d538771a8239842cc6acb920cd | 66,072 |
async def async_api_turn_on(hass, config, request, context, entity):
"""Process a turn on request."""
domain = entity.domain
if entity.domain == group.DOMAIN:
domain = ha.DOMAIN
service = SERVICE_TURN_ON
if entity.domain == cover.DOMAIN:
service = cover.SERVICE_OPEN_COVER
await... | 0e33791fde12d7582beed05be2d4adfd0eb004f2 | 66,073 |
def ring_float_to_class_int(rings:float, step=0.1):
"""Ring value rounded to classifier value; rounded to nearest step size"""
return round(rings/step) | 563f155481592c9924ed61535e07a4d1ff7a1e8e | 66,074 |
def capture(cohesin, occupied, args):
"""
We are describing CTCF capture here.
This function is specific to this particular project, and
users are encouraged to write functions like this
Note the for-loop over left/right sites below, and using cohesin[side]
to get left/right leg.
... | f5d93c05bd0597c4344c4fd6ebc108f5f897d65d | 66,075 |
def vh_u(Xcp,Ycp,Zcp,Gamma,R,h,psih=0,nB=3,bWT=True,method='wrench',bSemi=True,polar_out=True):
"""
Induced velocity by nB azimuthally dstributed helices
INPUTS:
- psih : reference azimuthal position of the first helix
- bSemi: Semi-infinite helices may be obtained using bSemi=True, but then ... | 62a51ed9ef4ac3bc0792b84bac3a974427b13be8 | 66,076 |
def action_github(commands, args, repos, data, options=cfg.OPTIONS):
"""Вывод данных, полученных из функции get_data_for_actions, в файл вашего репозитария на github.com
Необходимо заранее сгенерить personal access token (https://github.com/settings/tokens) и прописать его
в конфигурационный файл:
gith... | 1bd781292a664538f58d3c7026d6068440230474 | 66,077 |
def submitData():
""" Controller to manage the AJAX import of vulnerability data """
# Get the action to be performed
action = request.post_vars.action
if action == "vulnerability":
return import_vul_ui()
elif action == "vulnerability_part1":
return import_vul_csv_part1()
elif a... | 1c8ff6e516d3f2971580bfa188727cb74492cf9d | 66,078 |
async def get_product(product: ProductGinoModel = Depends(get_product)): # noqa: B008
"""API for getting a product."""
return product | 60ccf32fcb97eb7e0fe0c0b86a6d4204a0584925 | 66,079 |
import torch
def prep_image(img, img_size=(1088, 608)):
"""
Prepare image for inputting to the neural network.
Returns a Variable
"""
orig_im = cv2.imread(img)
dim = orig_im.shape[1], orig_im.shape[0]
img = letterbox_image(orig_im, img_size)
img_ = img[:, :, ::-1].transpose((2, 0, 1)... | e65d7f558ac0610133b6f996a118cd40429478fa | 66,080 |
def ifft_flat(ft, tod, nthread=1, axes=[-1], flags=None):
"""Same workaround as fft_flat but now for the inverse transform."""
shape_tod = tod.shape
naxes = np.atleast_1d(axes).size
axes_new = list(range(-1, -1 - naxes, -1))
tod = utils.partial_flatten(tod, axes=axes, pos=0)
ft = utils.partial_flatten(ft, axes=ax... | b1cc55db92fb818659d816f26b9acf6525c45fee | 66,081 |
def weekday_list_to_hexweek(weekday_list):
"""
Helper to convert list of integers represending weekdays into speaker's hex representation of weekdays.
:param hexweek: List of weekday integers e.g. [0, 1, 2, 3, 4]
:returns: Hex string .e.g. 0x3E
"""
# Mon, Tue, Wed, Thu, Fri, Sat, Sun
weekda... | c729dbc134c67c4c71911cbb5c817276583e1503 | 66,082 |
def set_markers(board):
"""
Function creates the lists of the markers to the side of the game board which indicates
the number of ship pieces in each row and column.
board: list of board tiles
returns the 2 lists of markers with number of ship pieces in each row (xmarkers)
and column (y... | 0302b250a43907db0969d693ac7adbe13c73ca7c | 66,083 |
def makeBdc(bus, branch):
"""Builds the B matrices and phase shift injections for DC power flow.
Returns the B matrices and phase shift injection vectors needed for a
DC power flow.
The bus real power injections are related to bus voltage angles by::
P = Bbus * Va + PBusinj
The real power f... | 753daefabe56694b80024648ed7266efcc51c9a0 | 66,084 |
def Cx2(c1, c2, q1, q2, kind='std'):
"""
Helper function to create pulse block for a pair of single-qubit Cliffords
"""
clifford_fun = clifford_map[kind.upper()]
seq1 = clifford_fun(q1, c1)
seq2 = clifford_fun(q2, c2)
#Create the pulse block
return seq1 * seq2 | ba39af4789e49e8f545de4c05fe4d952c4a16711 | 66,085 |
def can_create_teams(user, organization):
"""
Returns a boolean describing whether a user has the ability to
create new teams.
"""
if user.is_superuser:
return True
if not is_organization_admin(user, organization):
return False
result = plugins.first('has_perm', user, 'add_... | e4413302714edfeaab3d140790ef6def9680c838 | 66,087 |
def article_seen(article_title:str) -> list:
"""
Description:
Function to turn a certain article to seen if the user has clicked the 'x' on a news article.
Arguments:
article_title {str} : string containing the title of an article the user has pressed 'x' on
Returns:
article... | 822e90707bbe822dc0ad51338c944f9c30c9e6ac | 66,088 |
import hashlib
def get_hash(*args) -> str:
"""
Convert to String all given args
Adding SECRET_KEY and hashing it with sha3_256
@param args: Any argument convertible to String
@return: String with HEX digest
"""
hashing_list = []
for arg in args:
hashing_list.append(str(arg))
... | 7c9d7f5cff8c3a5e5584653ba31af88b807d5e8d | 66,089 |
from typing import Callable
from typing import Iterable
from typing import Iterator
def map_n(func: Callable[..., _T],
/,
*iterables: Iterable,
max_workers: int | None = None,
prefetch: int | None = 2,
mp: bool = False,
chunksize: int | None = None,
... | a52a3ac0f757fd5c51282586f80e354a53c75c43 | 66,090 |
from typing import Set
from typing import Type
from typing import List
def create_approach(name: str, initial_predicates: Set[Predicate],
initial_options: Set[ParameterizedOption],
types: Set[Type], action_space: Box,
train_tasks: List[Task]) -> BaseApproach... | 07492255fd5331c0e80dd06793c4644f6c68d1ce | 66,091 |
import torch
def validate_adv(val_loader, model, criterion):
"""
Run evaluation
"""
losses = AverageMeter()
top1 = AverageMeter()
# switch to evaluate mode
model.eval()
for i, (input, target) in enumerate(val_loader):
input = input.cuda()
target = target.cuda()
... | 846a0c7eda2c27d8a22cd0d54f48fadb85fb1fc1 | 66,092 |
import torchvision
def interpolate(
input, size=None, scale_factor=None, mode="nearest", align_corners=None
):
"""
Equivalent to nn.functional.interpolate, but with support for empty batch sizes.
This will eventually be supported natively by PyTorch, and this
class can go away.
"""
return ... | f3b4ed48be73aa4438c2c48ea6e1ffcd9757c3cb | 66,093 |
from typing import Any
from typing import Optional
def def_sensitivity(
*,
default: Any = NOTHING,
dtype: Optional[Any] = None,
description: Optional[str] = None,
converter: Optional[callable] = None,
validator: Optional[callable] = None,
**kwargs,
):
"""Define a sensitivity attribute ... | 4cb92c257913e08022ab6a6b67c2abfa84a958dd | 66,094 |
def is_matched_html(raw):
"""Return True if all HTML tags are properly match; False otherwise."""
S = ArrayStack()
j = raw.find('<') # find first '<' character (if any)
while j != -1:
k = raw.find('>', j + 1) # find next '>' character
if k == -1:
... | ecfe27be92d046097980e36748f26a463a8e1a50 | 66,095 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.