content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import inspect
def deprecated(removal_version, hint_message=None, subject=None, ensure_stderr=False):
"""Marks a function or method as deprecated.
A removal version must be supplied and it must be greater than the current 'pantsbuild.pants'
version.
When choosing a removal version there is a natural tension... | 84b2ef33a40d8f28eba27e29679338093875eb25 | 11,199 |
def prepare_comparator(comparator_path):
""" Processes the comparator path from the benchmark specification. Imports the object
dynamically.
Parameters
----------
comparator_path : str
Path to the python script file containing the comparator definition.
Returns
-------
ccobra.C... | 63b9f863a3d68a6fc7bb36c9da909004859e469b | 11,200 |
import csv
def get_genes(path):
"""Returns a list of genes from a DE results table"""
with open(path) as gene_list:
gene_list = csv.reader(gene_list)
gene_list = [row[0] for row in gene_list if row[0].startswith('P')]
return gene_list | 9deed781edc0514348b7f6c2f6ac2d302f30295d | 11,201 |
import types
def getNoncaptureMovesForRegularPiece(theGame, pieceLocation):
""" This returns a GameNode for every legal move of a regular piece """
moveList = []
xBoard = pieceLocation.get_x_board()
yBoard = pieceLocation.get_y_board()
pieceDestinationLeft = None
pieceDestinationRight = None
... | 13ad1e5cc4fcbd17b55b66703b41a49e5283efb8 | 11,203 |
import pathlib
def _top_level_package_filenames(tarball_paths):
"""Transform the iterable of npm tarball paths to the top-level files contained within the package."""
paths = []
for path in tarball_paths:
parts = pathlib.PurePath(path).parts
if parts[0] == "package" and len(parts) == 2:
... | 6b9b825eff14fe2e40f33c2caac104cf9869b277 | 11,204 |
def scale(X_train, X_test, type='MinMaxScaler', tuning_mode= True):
"""
This function apply Min Max or Standard scaling to a divided set of features divided as train and test data
Args:
The two dataframes:
X_train: a pandas dataframe with features of the training window
X_test: a pandas da... | 58d283856d789158847138c002e9f1f19d4beb9f | 11,205 |
def calc_positions(pl, pr, region1, region3, w, xi, t, gamma, dustFrac=0.):
"""
:return: tuple of positions in the following order ->
Head of Rarefaction: xhd, Foot of Rarefaction: xft,
Contact Discontinuity: xcd, Shock: xsh
"""
p1, rho1 = region1[:2] # don't need velocity
... | 8034d327c4d9c9c771137e3eff49f8627315b10a | 11,206 |
def accuracy(targets, predictions, weights=None):
"""Computes the categorical accuracy.
Given a set of ground truth values and a set of predicted labels as tensors of
the same shape, it returns a tensor of the same shape with 1.0 in those position
where the ground truth value and the predicted one are ... | 08dba6fab0f09c8d1507d00a8501192b2f008499 | 11,208 |
import re
def jp_author_name_normalized(name):
"""Construct the author name as P. Szekely."""
clean = name.replace('.',' ').replace(',',' ').replace(';', ' ')
clean = asciiChars(clean, '')
names = re.sub(r'\s+', ' ', clean.strip()).split(' ');
last_word = names[-1]
if len(last_word) == 1:
# The last word i... | 61e5aa4290611266d4c96c67a870ce4c375a291c | 11,209 |
import math
def palette(tensor, shape, name=None, time=0.0, speed=1.0):
"""
Another approach to image coloration
https://iquilezles.org/www/articles/palettes/palettes.htm
"""
if not name:
return tensor
channel_shape = [shape[0], shape[1], 3]
p = palettes[name]
offset = p["o... | 5717a405a68f54257082f15ce54ccb1fe3d52bd1 | 11,210 |
def binarize_categorical_columns(
input_train_df, input_test_df, categorical_columns):
"""Function to converting categorical features to one-hot encodings."""
# Binarize categorical columns.
binarized_train_df = pd.get_dummies(
input_train_df, columns=categorical_columns)
binarized_test_df = pd.get_d... | 537b5271298ee00b60fd16039ba63d02c61189b9 | 11,211 |
def smallest_sval(X, solver='lobpcg', **kws):
"""
Computes the smallest singular value of a matrix using
scipy.sparse.linalg.svds
Parameters
----------
X: array-like
solver: str
Which solver to use. Must be one of ['lobpcg', 'arpack']
**kws
Kws for svds
Output
... | ba5436fbc347eb050cc69c3b7dec7df414d31403 | 11,212 |
def mean_ndcg_score(u_scores, u_labels, wtype="max"):
"""Mean Normalize Discounted cumulative gain (NDCG) for all users.
Parameters
----------
u_score : array of arrays, shape = [num_users]
Each array is the predicted scores, shape = [n_samples[u]]
u_label : array of arrays, shape = [num_us... | 6a6e60182ec8bf2e3677779a5397d76fe492740c | 11,213 |
from typing import List
import torch
def average_precision(predictions: List, targets: List,
iou_threshold: float = 0.5) -> torch.Tensor:
"""Calculates average precision for given inputs
Args:
predictions (List): [Ni,5 dimensional as xmin,ymin,xmax,ymax,conf]
targets (List): [Mi,4 dim... | e32efe5501fee9140f9b10d2a29fa779af4be18b | 11,215 |
def new_post(update: Update, context: CallbackContext) -> int:
"""Start the conversation, display any stored data and ask user for input."""
# init empty list to store dicts w/ info about each uploaded photo
context.user_data['photos'] = []
reply_text = "Initiate conversation: new post "
# if conte... | 1b49d20628aaafdf6d61f1cb92cc2f123e742fac | 11,216 |
from typing import List
from typing import Union
from typing import Tuple
from typing import Sequence
def _get_geometry_type_from_list(
features: List, allowed_features: List[Union[Tuple, Sequence]]
) -> Tuple[str]:
"""
Gets the Geometry type from a List, otherwise it raises an exception.
:param feat... | c6ec2e68e3f5667a9fa31ab72b76b0257e4a7221 | 11,217 |
def save_network_to_path(interactions, path):
"""Save dataframe to a tab-separated file at path."""
return interactions.to_csv(path, sep='\t', index=False, na_rep=str(None)) | f189c6e8f7791f1f97c32847f03e0cc2e167ae90 | 11,218 |
from typing import Optional
from typing import Dict
from typing import Tuple
from typing import Union
def apply_sql(
query: str,
output_name: Optional[str],
found: Dict[str, beam.PCollection],
run: bool = True) -> Tuple[str, Union[PValue, SqlNode], SqlChain]:
"""Applies a SqlTransform with the given... | 26541c4e946a3d7b8dd1783d8b429bceb0b7b6bf | 11,219 |
from typing import Tuple
from datetime import datetime
def check_course_time_conflict(current_course: Course,
user: NaturalPerson) -> Tuple[bool, str]:
"""
检查当前选择课程的时间和已选课程是否冲突
"""
selected_courses = Course.objects.activated().filter(
participant_set__person=user... | 2b5a6d621463018b64d0d2d44ac8827b687cee67 | 11,220 |
def or_func(a, b):
"""Creates a new list out of the two supplied by applying the function to each
equally-positioned pair in the lists. The returned list is truncated to the
length of the shorter of the two input lists"""
return a or b | 0f90173e05910ebc7e81079d99bfdbbb1c0ee66b | 11,221 |
import typing
def json_loads(
value: typing.Union[bytes, bytearray, str]
) -> typing.Union[
typing.List[typing.Dict[str, typing.Any]], typing.Dict[str, typing.Any]
]:
"""Practical json dumps helper function, bytes, bytearray, and
str input are accepted. supports for ``orjson``, ``simplejson`.
In ... | 9fe8664df512b52b565d68f3433abc346112c974 | 11,222 |
import json
def execute_create_payment(client, create_payment_request):
"""
Create a payment. Automatically creates an NR for use.
:param client:
:param create_payment_request:
:return:
"""
headers = get_test_headers()
draft_nr = setup_draft_nr(client)
nr_id = draft_nr.get('id')
... | 56ff5e99f577d64cd71c451f9502220585b1d920 | 11,223 |
from typing import List
def collect_contrib_features(
project: 'ballet.project.Project'
) -> List[Feature]:
"""Collect contributed features for a project at project_root
For a project ``foo``, walks modules within the ``foo.features.contrib``
subpackage. A single object that is an instance of ``balle... | 8c76f968d7fc75bba2eb6fee9447e49de2d53694 | 11,224 |
def verify_token(token):
""" Basic auth method """
curr_user = User.check_token(token) if token else None
return curr_user is not None | 95027a9d0235521819b5ca262082b29fe252dc1b | 11,227 |
from typing import Sequence
import random
def generate_test_cases(n_tests: int, min_len: int, max_len: int, min_dim: int, max_dim: int) \
-> Sequence[Sequence[int]]:
"""
:param n_tests: number of test to generate
:param min_len: minimum number of matrices for each test case
:param max_len: ma... | 63a20aa5d94456597c29523019e2699aedf4ab5f | 11,228 |
from typing import List
def calc_neighbours(
adata: AnnData,
distance: float = None,
index: bool = True,
verbose: bool = True,
) -> List:
"""Calculate the proportion of known ligand-receptor co-expression among the neighbouring spots or within spots
Parameters
----------
adata: AnnData... | 1fdbc372f2249115b0ace55bf5d89c54a1143523 | 11,229 |
from typing import Optional
from typing import Tuple
from typing import List
def _build_tree_string(
root: Optional[Node],
curr_index: int,
include_index: bool = False,
delimiter: str = "-",
) -> Tuple[List[str], int, int, int]:
"""Recursively walk down the binary tree and build a pretty-print str... | 988a5816647ca31b19c25a3017061ec71cdabc85 | 11,230 |
def growth(xs, ys , x):
"""
growth function
pre:
xs,ys are arrays of known x and y values. x is a scaler or np.array
of values to calculate new y values for
post:
return new y values
"""
xs = np.array(xs)
ys = np.log(np.array(ys))
xy_bar = np.average(xs*ys)
x_b... | 5a47077ebfcca5284e29a02c467ba059d6350182 | 11,231 |
def remove_short_transition(transition_sites,thresh=11):
"""
removes transitions that are too close from others.
"""
if len(transition_sites) < 4:
return transition_sites
for i in range(len(transition_sites) - 1):
forward_difference = transition_sites[i+1] - transition_sites[i]
... | 5ae188ef1314f4416b3baba07f45cceb41dc4c7a | 11,232 |
def load_image(file_path):
"""
Load data from an image.
Parameters
----------
file_path : str
Path to the file.
Returns
-------
float
2D array.
"""
if "\\" in file_path:
raise ValueError(
"Please use a file path following the Unix convention"... | 1399e3299e8697097a0c92f39c122735ab63c633 | 11,233 |
import numpy as np
from glad.util import argmin_datetime,haversine
def absolute_dispersion(drifters,starttime,time):
"""
Calculates absolute dispersion A^2, given desired current and
initial time.
Parameters
----------
drifters : GladDrifter instance, list, ndarray
A list or numpy ar... | 1cf22d344994c913f294d005558afd73eb21cd2a | 11,234 |
import logging
def add_xgis_url(df: gpd.geodataframe.GeoDataFrame) -> gpd.geodataframe.GeoDataFrame:
""" Adding x-gis URL which will let the user check the result
:param df: gdf to use
"""
# Generaring url from string
df.reset_index(inplace=True) # resetting index
xy_tog = df[c.X].astype(str... | a220169ba79b452b8cbb0d0b2aee11229c09fdae | 11,235 |
from typing import Optional
from typing import Sequence
def get_compute_capacity_reservation_instance_shapes(availability_domain: Optional[str] = None,
compartment_id: Optional[str] = None,
display_name: Optional... | d294586d5aac79bb452d93bf3424daa403923188 | 11,236 |
import re
def is_branch_or_version(string):
"""Tries to figure out if passed argument is branch or version.
Returns 'branch', 'version', or False if deduction failed.
Branch is either 'master' or something like 3.12.x;
version is something like 3.12.5,
optionally followed by letter (3.12.5b) for a... | 6a5ad7cb7af29b6ce0e39ff86171f0f230929fb3 | 11,237 |
def eval_regressors(regressor_factories, gen_one_data, batch_size=1, names=None):
"""Evaluates an iterable of regressors on some test data of size
:batch_size: generated from :gen_one_data:.
"""
X, y = dg.BatchData.batch(gen_one_data, batch_size)
return _eval_regressors(regressor_factories, X, y, na... | 89c63d5c8c4697370ff2e63baf96ec456565fe42 | 11,238 |
def beautify():
"""Set reasonable defaults matplotlib.
This method replaces matplotlib's default rgb/cmyk colors with the
colarized colors. It also does:
* re-orders the default color cycle
* sets the default linewidth
* replaces the defaault 'RdBu' cmap
* sets the default cmap to 'RdBu'
... | da08523ed69b2bb97af06cc1e51f5bdf2e412faa | 11,239 |
import yaml
from typing import OrderedDict
def ordered_load(stream, loader=yaml.SafeLoader, object_pairs_hook=OrderedDict):
"""Load YAML, preserving the ordering of all data."""
class OrderedLoader(loader):
pass
def construct_mapping(loader, node):
loader.flatten_mapping(node)
ret... | d3b6a9c84e895a63a85de39dbb5a849d6c224ecd | 11,241 |
def user_unions_clear(*args):
"""
user_unions_clear(map)
Clear user_unions_t.
@param map (C++: user_unions_t *)
"""
return _ida_hexrays.user_unions_clear(*args) | f1e7b1a8cf966f3d28966919cf2e4c5e82cfb45c | 11,242 |
def heur_best_from_now(state):
"""
This heuristics computes the cost based in put all weight in the launch with the lowest variable cost.
@param state: state to compute the cost.
@return: cost
"""
try:
return min([launch.compute_variable_cost(state.left_weight()) for launch in state.laun... | 050c7c718ad849e8e7fc6892de7097c3bd0f83dd | 11,243 |
def get_ngram(text, ns=[1]):
"""
获取文本的ngram等特征
:param text: str
:return: list
"""
if type(ns) != list:
raise RuntimeError("ns of function get_ngram() must be list!")
for n in ns:
if n < 1:
raise RuntimeError("enum of ns must '>1'!")
len_text = len(text)
... | 3826fcdce46b455762417528ac9f31a0552b5a04 | 11,244 |
from scipy.stats import entropy
def entropy(df):
"""Return Shannon Entropy for purchases of each user."""
mask = df.credit_debit.eq('debit')
df = df[mask]
num_cats = df.auto_tag.nunique()
def calc_entropy(user, num_cats):
total_purchases = len(user)
cat_purchases = user.groupby('a... | dd3f0e1d3865de151ce4a451c2def148d58da9da | 11,245 |
def splitter(h):
""" Splits dictionary numbers by the decimal point."""
if type(h) is dict:
for k, i in h.items():
h[k] = str(i).split('.');
if type(h) is list:
for n in range(0, len(h)):
h[n] = splitter(h[n])
return h | 1eb5e38a02ce310a068d8c1c9df2790658722662 | 11,246 |
def listall_comments():
"""Lists rule-based labels
Returns:
list: A list of FileTypeComments
"""
return listall('comment') | 5f26a0632497309e13d624437767467811d8faa3 | 11,247 |
import random
import hashlib
import time
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-... | 9a8df9402b8ccde30ae289eb759708f506ef6087 | 11,248 |
import html
def make_html_doc(body, root, resource_dir=None, title=None, meta=None):
"""Generate HTML document
Parameters
----------
body : fmtxt-object
FMTXT object which should be formatted into an HTML document.
root : str
Path to the directory in which the HTML file is going t... | 6794050593440cafafa080e46b435675fbdad648 | 11,249 |
def blur(img):
"""
:param img:
:return:
"""
blank_img = SimpleImage.blank(img.width, img.height)
for x in range(1, img.width-1):
for y in range(1, img.height-1):
left1_pixel = img.get_pixel(x-1, y-1)
left2_pixel = img.get_pixel(x-1, y)
left3_pixel = im... | b2e04d8134b1d295e497b28a43f93223bcaf881f | 11,250 |
def generalized_euler_solver(descr, coefs, rho0, v0, t, x, bc="periodic", num_integrator_steps=1, fix_vvx_term=True):
"""Solver for Euler hydro system.
Builds RHS of the Euler equation Dv_t = f(...) from symbolic description.
"""
t_pde = np.linspace(t[0], t[-1], len(t)*num_integrator_steps) # Create... | 5bc1fefbb3c1e13da37d2e37fdefa1be44812a36 | 11,251 |
def pick_unassigned_variable(board, strategy, unassigned_heap):
"""
:returns: (row_index, col_index)
"""
if strategy == Strategies.FIRST_FOUND:
return __pick_unassigned_variable_first_found(board)
elif strategy == Strategies.MIN_ROW:
return __pick_unassigned_variable_min_row(board)
... | a96bb4d5e047f44fb79dd2eae68532c8e54296d4 | 11,254 |
def CONTAINS_INTS_FILTER(arg_value):
"""Only keeps int sequences or int tensors."""
return arg_value.elem_type is int or arg_value.has_int_dtypes() | c4452c5e6bbd9ead32359d8638a6bf1e49b600ba | 11,255 |
def pad_renderable(renderable, offset):
"""
Pad a renderable, subject to a particular truncation offset.
"""
if offset < 0:
raise Exception("invalid offset!")
if offset == 0:
return RenderGroup(_RULE, Padding(renderable, 1))
if offset == 1:
return Padding(renderable, 1)
... | eed05f632e00f8cb8a2539f59402c4c200159f4c | 11,256 |
import frappe.modules
def reload_doc(module, dt=None, dn=None, force=False, reset_permissions=False):
"""Reload Document from model (`[module]/[doctype]/[name]/[name].json`) files.
:param module: Module name.
:param dt: DocType name.
:param dn: Document name.
:param force: Reload even if `modified` timestamp ma... | c6f68a63433010f2a0270fdc0f373e96e63001c5 | 11,257 |
def create_api_app(global_conf, **local_conf):
"""Creates MainAPI application"""
controllers = {}
api_version = global_conf.get('api_version')
if api_version == 'v2.0':
controllers.update({
'/log/single': v2_logs.Logs()
})
elif api_version == 'v3.0':
controllers... | 1ec0f155dfdc482fa6b1b41afb18d037636fc9ba | 11,259 |
def gauss_4deg(x,b, ampl,cent,sigm):
""" Simple 3 parameter Gaussian
Args:
x
b (float): Floor
ampl (float): Amplitude
cent (float): Centroid
sigm (float): sigma
Returns:
float or ndarray: Evaluated Gausssian
"""
return b + ampl*np.exp(-1.*(cent-x)**... | 42f58844c91423220176b0f93ead4a4fd6dbd608 | 11,260 |
import requests
def get_spreads(pair, since):
"""Returns last recent spreads"""
api_command = API_LINK + f'Spreads?pair={pair}&since={since}'
resp = requests.get(api_command).json()
if not resp['error']: # empty
return resp
return resp['error'] | 7e32b1abf2988bd5eeb439d9308a1a6320ba8b87 | 11,261 |
def quat2expmap(q):
"""
Converts a quaternion to an exponential map
Matlab port to python for evaluation purposes
https://github.com/asheshjain399/RNNexp/blob/srnn/structural_rnn/CRFProblems/H3.6m/mhmublv/Motion/quat2expmap.m#L1
Args
q: 1x4 quaternion, w, x, y, z
Returns
... | 1b68e2ad62f46402f06c9ba2c459c33d464d84e4 | 11,263 |
def candidate_results_for_race_type(result_form, race_type, num_results=None):
"""Return the candidates and results for a result form and race type.
:param result_form: The result form to return data for.
:param race_type: The race type to get results for, get component results
if this is None.
... | 22bff04bd0b59b6c566f792794119929913efd42 | 11,265 |
def sort_2metals(metals):
"""
Handles iterable or string of 2 metals and returns them
in alphabetical order
Args:
metals (str || iterable): two metal element names
Returns:
(tuple): element names in alphabetical order
"""
# return None's if metals is None
if metals is None:... | dab922797a6c7b94d6489d8fc4d9c1d99f3ee35c | 11,266 |
def parse_join(tables, operation, left, right):
"""
Parses a join from the where clause
"""
# Verify Left
table_name = left['column']['table']
column_name = left['column']['name']
# If table and column, check that table for presense
if table_name is not None and not tables[table_name].h... | 1d5f912dfe634c21dea7640ad12271e4ac34b277 | 11,267 |
def address_id_handler(id):
"""
GET - called as /addresses/25
PUT - called to update as /addresses/25?address='abc'&lat=25&lon=89
DELETE - called as /addresses/25
:param id:
:return:
"""
if request.method == 'GET':
return jsonify(read_address(session, address_id=id))
elif re... | 9bb3fd813842aac0262417dcb59e4b0cffadc1f0 | 11,268 |
from neptune_mlflow.sync import sync as run_sync
def sync(path, project):
"""Upload mlflow runs data to Neptune.
PATH is a directory where Neptune will look for `mlruns` directory with mlflow data.
Examples:
neptune mlflow .
neptune mlflow /path
neptune mlflow /path --project u... | 5fb258969ea02a93774b2fb350c3d3fc3d436752 | 11,269 |
def prefix_search_heuristic_split(mat: np.ndarray, chars: str) -> str:
"""Prefix search decoding with heuristic to speed up the algorithm.
Speed up prefix computation by splitting sequence into subsequences as described by Graves (p66).
Args:
mat: Output of neural network of shape TxC.
cha... | c7894012ff1fe4d2ef0baab6bb0375dc2167ea58 | 11,270 |
def _make_set_permissions_url(calendar_id, userid, level):
"""
:return: the URL string for GET request call
to Trumba SetPermissions method
"""
return "{0}?CalendarID={1}&Email={2}@uw.edu&Level={3}".format(
set_permission_url_prefix, calendar_id, userid, level) | 669a64f8a17d87777dea3d007d690b132d8cb266 | 11,271 |
def pack_inputs(inputs):
"""Pack a list of `inputs` tensors to a tuple.
Args:
inputs: a list of tensors.
Returns:
a tuple of tensors. if any input is None, replace it with a special constant
tensor.
"""
inputs = tf.nest.flatten(inputs)
outputs = []
for x in inputs:
if x is No... | dcb26dd286a88288cf9afb824a69d468188436be | 11,272 |
from datetime import datetime
def datetime_without_seconds(date: datetime) -> datetime:
"""
Returns given datetime with seconds and microseconds set to 0
"""
return date.replace(second=0, microsecond=0) | de30c7770d84751b555c78e045f37783030d8970 | 11,273 |
import copy
def update_br(request):
"""
更新会议室
:param request:
:return:
"""
if request.method == 'POST':
dbs = request.dbsession
app_path = request.registry.settings['app_path']
br = dbs.query(HasBoardroom).filter(HasBoardroom.id == request.POST.get('br_id', 0)).first()... | 46fa2c9cb20f7335b539f2a4e77f566e93e6bf7c | 11,274 |
def find_north_pole(valid_rooms):
"""
Decode the room names and find the north pole.
Args:
valid_rooms (list): A list of valid rooms to decode/search.
Returns:
tuple
"""
global NORTH_POLE_NAME
for room in valid_rooms:
room_name, sector_id, checksum = room
... | b3da9a66838c024bb6ae68be8104b3e80f79d0d7 | 11,275 |
def cli(gene1, gene2, gene3, frameness, keep_exon, fusion_fraction,
add_insertion, total_coverage, output, common_filename):
"""[Simulator] Fusion generator."""
normal_coverage = total_coverage * (1. - fusion_fraction)
fusion_coverage = total_coverage * fusion_fraction
normal_ref = generate_norm... | ed52c518bf3c88623510fa07996fdec205936f4a | 11,276 |
def build_upsample_layer(cfg, *args, **kwargs):
"""Build upsample layer.
Args:
cfg (dict): The upsample layer config, which should contain:
- type (str): Layer type.
- scale_factor (int): Upsample ratio, which is not applicable to
deconv.
- layer args... | 30121657746d3b5ec1f374d339a9d33b48a24724 | 11,277 |
def ctime_ticks(t):
"""This is for backwards compatibility and should not be used."""
return tsc_time.TSC_from_ticks(t).ctime() | 841f879db7e8fa7aa436ceddeb69c76c5d707f17 | 11,278 |
def vitruvian_loss(input, mask, dataset):
"""Vitruvian loss implementation"""
if dataset == "itop":
# 1 - 2 e 1 - 3 -> collo spalle
# 2 - 4 e 3 - 5 -> spalle gomito
# 4 - 6 e 5 - 7 -> gomito mano
# 9 - 11 e 10 - 12 -> anca ginocchio
# 11 - 13 e 12 - 14 -> ginocchio piede
... | b609b28e15a1b53bccfd69d3ac0938be1f6ccee6 | 11,279 |
def LoadElement(href, only_etag=False):
"""
Return an instance of a element as a ElementCache dict
used as a cache.
:rtype ElementCache
"""
request = SMCRequest(href=href)
request.exception = FetchElementFailed
result = request.read()
if only_etag:
return result.etag
... | 8e47fbc2aa745c97c9b93401302ff13435e8e9e7 | 11,280 |
from typing import Iterable
def xreplace_indices(exprs, mapper, candidates=None, only_rhs=False):
"""
Create new expressions from ``exprs``, by replacing all index variables
specified in mapper appearing as a tensor index. Only tensors whose symbolic
name appears in ``candidates`` are considered if ``... | 808918b8852ff23e40f34aa26cbc6433a9bdf102 | 11,282 |
import six
def format_ratio(in_str, separator='/'):
""" Convert a string representing a rational value to a decimal value.
Args:
in_str (str): Input string.
separator (str): Separator character used to extract numerator and
denominator, if not found in ``in_str`` w... | 308ec972df6e57e87e24c26e769311d652118aee | 11,283 |
def fill_tidal_data(da,fill_time=True):
"""
Extract tidal harmonics from an incomplete xarray DataArray, use
those to fill in the gaps and return a complete DataArray.
Uses all 37 of the standard NOAA harmonics, may not be stable
with short time series.
A 5-day lowpass is removed from the ... | fbb881ca3a47778c8c6ee8b3804953fb5b806b4e | 11,284 |
def wrapper_unit_scaling(x, T, s_ref, n_gt, *args, **kwargs):
"""Normalize segments to unit-length and use center-duration format
"""
xc = segment_format(x, 'b2c')
init_ref = np.repeat(s_ref[:, 0], n_gt)
return segment_unit_scaling(xc, T, init_ref) | 28f29fd81143c1bb12d4e062e680de2643662bd1 | 11,285 |
import copy
import time
import tqdm
import torch
def fairseq_generate(data_lines, args, models, task, batch_size, beam_size, device):
"""beam search | greedy decoding implemented by fairseq"""
src_dict = task.source_dictionary
tgt_dict = task.target_dictionary
gen_args = copy.copy(args)
with open... | a412f619f79f39f77d6df83cefbbe38170d77109 | 11,286 |
def retrieve_features(dataframe):
"""
Retrieves features (X) from dataframe
:param dataframe:
:return:
"""
return list(dataframe["tweet"]) | 69118d6d0b9503500f6fa4b24fb844af4ff25644 | 11,287 |
def atarzia_short_MD_settings():
"""My default settings for short, crude cage optimizations in stk.
Modified on 26/04/19.
"""
Settings = {
'output_dir': None,
'timeout': None,
'force_field': 16,
'temperature': 700, # K
'conformers': 50,
'time_step': 1, ... | 490a59e9551a324b571d4f67c4e7885144f2fe77 | 11,288 |
def result_by_score_from_csv(f, score, ascending=True):
"""Return result with the best defined score"""
df = pd.read_csv(f)
df.sort_values(score, ascending=ascending, inplace=True)
return df.loc[0, ["pdb_code", score]].tolist() | ba41c6cfc26d830685c43265eaa21c496173311e | 11,289 |
from typing import Mapping
from typing import Tuple
def get_default_hand_connection_style(
) -> Mapping[Tuple[int, int], DrawingSpec]:
"""Returns the default hand connection drawing style.
Returns:
A mapping from each hand connection to the default drawing spec.
"""
hand_connection_style = {}
for k, ... | 7cbc020f746e2dacd31664f9ddbe71fb98fc1942 | 11,291 |
def lists_to_html_table(a_list):
"""
Converts a list of lists to a HTML table. First list becomes the header of the table.
Useful while sending email from the code
:param list(list) a_list: values in the form of list of lists
:return: HTML table representation corresponding to the values in the li... | cc244ec7f0bccedba2bb3bd66e29b3f43160f8c1 | 11,292 |
def from_matrix_vector(matrix, vector):
"""Combine a matrix and vector into a homogeneous transform.
Combine a rotation matrix and translation vector into a transform
in homogeneous coordinates.
Parameters
----------
matrix : ndarray
An NxM array representing the the linear part of... | d4d49a4217d82c93b77aa1b50fc7a8d70875d11a | 11,293 |
def take_closest(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
"""
pos = bisect_left(myList, myNumber)
if pos == 0:
return myList[0]
if pos == len(myList):
return myList[-1]
... | 6dea2edfb83bb8d78e7140d9bcc9b8f30441a3bf | 11,294 |
def check_host(host):
""" Helper function to get the hostname in desired format """
if not ('http' in host and '//' in host) and host[len(host) - 1] == '/':
return ''.join(['http://', host[:len(host) - 1]])
elif not ('http' in host and '//' in host):
return ''.join(['http://', host])
elif host[len(host) - 1] ==... | 0d035f616ce539f0a822aa1426cf3cd0eb766d04 | 11,295 |
from datetime import datetime
def task_time_slot_add(request, task_id, response_format='html'):
"""Time slot add to preselected task"""
task = get_object_or_404(Task, pk=task_id)
if not request.user.profile.has_permission(task, mode='x'):
return user_denied(request, message="You don't have access... | 250fbb87a80f2c2431b5e95b7c437f0b9562a1bc | 11,296 |
from typing import Any
def get_artist_names(res: dict[str, Any]) -> str:
"""
Retrieves all artist names for a given input to the "album" key of a response.
"""
artists = []
for artist in res["artists"]:
artists.append(artist["name"])
artists_str = ", ".join(artists)
return artist... | 2913c813e7e6097cb2cb3d3dfb84f831bbc0a6e7 | 11,297 |
def json_response(func):
"""
View decorator function that converts the dictionary response
returned by a view function to django JsonResponse.
"""
@wraps(func)
def func_wrapper(request, *args, **kwargs):
func_response = func(request, *args, **kwargs)
status_code = func_response.g... | ad4a304b9e1434d7d0832fc9b535e2fd37228ad8 | 11,298 |
def clean_df(df):
"""return : pandas.core.frame.DataFrame"""
df.index = pd.DatetimeIndex(df.comm_time)
df = df.sort_index()
df = df[~(np.abs(df.com_per-df.com_per.mean())>(3*df.com_per.std()))]#清洗出三个标准差之外的数据,人均有关的计算用df2
df = df.drop('_id',1)
df = df.drop_duplicates()
return df | 055f0efcc79e0e551620a602cb8d9e8244d58a7e | 11,299 |
from typing import Iterator
from typing import Tuple
from typing import Any
import itertools
def _nonnull_powerset(iterable) -> Iterator[Tuple[Any]]:
"""Returns powerset of iterable, minus the empty set."""
s = list(iterable)
return itertools.chain.from_iterable(
itertools.combinations(s, r) for r... | ad02ab8ac02004adb54310bc639c6e2d84f19b02 | 11,300 |
import yaml
def _parse_obs_status_file(filename):
"""
Parse a yaml file and return a dictionary.
The dictionary will be of the form: {'obs': [], 'bad': [], 'mags: []}
:param filename:
:return:
"""
with open(filename) as fh:
status = yaml.load(fh, Loader=yaml.SafeLoader)
if 'o... | 389fc921867367964001e5fc2f56a7fa7defd7c8 | 11,301 |
def extract_optional_suffix(r):
"""
a | a b -> a b?
"""
modified = False
def match_replace_fn(o):
if isinstance(o, Antlr4Selection):
potential_prefix = None
potential_prefix_i = None
to_remove = []
for i, c in enumerate(o):
if... | a1d4e6702ed1b23e0f94a44e5bea6fae16b47e17 | 11,302 |
def _heading_index(config, info, token, stack, level, blockquote_depth):
"""Get the next heading level, adjusting `stack` as a side effect."""
# Treat chapter titles specially.
if level == 1:
return tuple(str(i) for i in stack)
# Moving up
if level > len(stack):
if (level > len(stac... | f42dd5c6aae942da687310d7bef81f70bfadad83 | 11,303 |
from typing import List
def sin_salida_naive(vuelos: Data) -> List[str]:
"""Retorna una lista de aeropuertos a los cuales hayan llegado
vuelos pero no hayan salido vuelos de este.
:param vuelos: Información de los vuelos.
:vuelos type: Dict[str, Dict[str, Union[str, float]]]
:return: Lista de aer... | 136b7c1e3428cecee5d3bc7046fac815276288e5 | 11,304 |
def converter(doc):
"""
This is a function for converting various kinds of objects we see
inside a graffle document.
"""
if doc.nodeName == "#text":
return str(doc.data)
elif doc.nodeName == "string":
return str(doc.firstChild.data)
elif doc.nodeName == 'integer':
return int(doc.firstChi... | 8820aa739f4b96251033c191ea405157cfe1e9fb | 11,305 |
def printable_cmd(c):
"""Converts a `list` of `str`s representing a shell command to a printable
`str`."""
return " ".join(map(lambda e: '"' + str(e) + '"', c)) | b5e8a68fc535c186fdbadc8a669ed3dec0da3aee | 11,306 |
def details_from_params(
params: QueryParams,
items_per_page: int,
items_per_page_async: int = -1,
) -> common.Details:
"""Create details from request params."""
try:
page = int(params.get('page', 1))
except (ValueError, TypeError):
page = 1
try:
anchor =... | 50e20619bc4f32af6811a3416b2d2f93820ba44a | 11,307 |
from typing import Tuple
from typing import Mapping
def _signature_pre_process_predict(
signature: _SignatureDef) -> Tuple[Text, Mapping[Text, Text]]:
"""Returns input tensor name and output alias tensor names from signature.
Args:
signature: SignatureDef
Returns:
A tuple of input tensor name and ... | a53af746f7cebc7c3baaa316458dd3e7b88c2c38 | 11,309 |
def style_95_read_mode(line, patterns):
"""Style the EAC 95 read mode line."""
# Burst mode doesn't have multiple settings in one line
if ',' not in line:
return style_setting(line, 'bad')
split_line = line.split(':', 1)
read_mode = split_line[0].rstrip()
line = line.replace(read_mode,... | 25c347acb87702f19ebcea85a3b4f0257df101ae | 11,310 |
def trange(
client, symbol, timeframe="6m", highcol="high", lowcol="low", closecol="close"
):
"""This will return a dataframe of true range for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (string): Ticker
timeframe (string): timeframe to... | 94cf95eb86575a66e015e46fd81a5a8085277255 | 11,311 |
def ConvolveUsingAlm(map_in, psf_alm):
"""Convolve a map using a set of pre-computed ALM
Parameters
----------
map_in : array_like
HEALPix map to be convolved
psf_alm : array_like
The ALM represenation of the PSF
Returns
-------
map_out : array_like
The smeared ... | 0ebfa49c605f57ea2cc59b2686da8995dc01881f | 11,312 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.