content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _passwd_tar_impl(ctx):
"""Core implementation of passwd_tar."""
f = "".join(["%s:x:%s:%s:%s:%s:%s\n" % (
entry[PasswdFileContentProviderInfo].username,
entry[PasswdFileContentProviderInfo].uid,
entry[PasswdFileContentProviderInfo].gid,
entry[PasswdFileContentProviderInfo].inf... | fb6adba6be2567a03f4f89ad98747c5d702349c1 | 46,176 |
def multi_replace(search, replace, path):
"""Replace search with replace in all filenames
and file contents in directory path.
@type search: string
@param search: The old string.
@type replace: string
@param replace: The new string.
@type path: string
@param path: The path in ... | 759591256bf233e58f823f5ccec574683adbadca | 46,178 |
def extract_JK(pos_seq):
"""The 'JK' method in Handler et al. 2016.
Returns token positions of valid ngrams."""
def find_ngrams(input_list, num_):
'''get ngrams of len n from input list'''
return zip(*[input_list[i:] for i in range(num_)])
# copied from M and S chp 5'''
patterns = set(['AN', 'NN', 'AAN', 'AN... | 0452e26abfbac94571fefcb5e455df5802617eff | 46,179 |
import logging
def get_child_logger(*names: str):
"""Returns a child logger of the project-level logger with the name toolshed.<name>."""
return logging.getLogger("toolshed." + '.'.join(names)) | a1760d34a620ffa3caf8abaca6cfb911209cf074 | 46,180 |
import types
def validate_pcrPlate_position_samplesetitems(
samplesetitems, pcrPlateRow, samplesetitem_id, sampleset=None
):
"""
1) validate pcrPlateRow position selected for sampleSetItem is unique
2) for Ampliseq on Chef pcrPlateRow value is required
If validating with a dict of sam... | fa8839ad8fb347d39b037845295ddcf328dd507c | 46,181 |
from rstoolbox.components import SequenceFrame
from rstoolbox.components import DesignFrame
import copy
import collections
def sequential_frequencies( df, seqID, query="sequence", seqType="protein",
cleanExtra=True, cleanUnused=-1 ):
"""Generates a :class:`.SequenceFrame` for the frequ... | 2969867ecedbf4e201da225cbd17f829b89d01b2 | 46,182 |
def get_csv_config(model):
"""Returns a configuration object based on the given model."""
if model == Accession:
return AccessionCSVConfig
elif model == Donor:
return DonorCSVConfig
elif model == Object:
return ObjectCSVConfig
else:
return GenericCSVConfig | d34579a94a0c661ee8c08dad97d13e7bfb033365 | 46,183 |
def import_vae(env: str, cams: list, mvae_mode: str, img_width: int, img_height: int) -> MultiCamVae:
"""
Loads an existing vae set with the specified properties, or returns an already cached goal set
:param env: the name of the environment, e.g. FetchReach-v1
:param cams: the list of camera names, e.g... | 16907adf63c9883e5b55239c1147b818a6522b04 | 46,184 |
import fastapi
import profile
async def api_portal_restrictions(req: fastapi.Request):
"""
Returns all restrictions for the current user.
"""
keyword_restrictions, query_s = profile(restrictions, portal, req)
return {
'profile': {
'query': query_s,
},
'data': k... | 456ed71c0197b8dc7cbca6b36dacbecbabda0870 | 46,186 |
def cartesian_pose(args):
"""
Move the robot arm to the specified configuration.
Call using:
$ rosrun intera_examples go_to_cartesian_pose.py [arguments: see below]
-p 0.4 -0.3 0.18 -o 0.0 1.0 0.0 0.0 -t right_hand
--> Go to position: x=0.4, y=-0.3, z=0.18 meters
--> with quaternion orient... | 55d2ecf81c64f2f248da7bbdc3c7907d5838661d | 46,189 |
def test_basic_call_async():
""" The most basic Happy-Path test for Hug APIs using async """
@hug_core.local()
async def hello_world():
return "Hello World!"
assert hello_world() == "Hello World!" | ae96de3fe9ee440d55944434b862ef61b58b5a09 | 46,190 |
def Anomalies(Serie):
"""
Make anomalies compared with the annual cycle
INPUTS
Serie : Pandas DataFrame with data
"""
Ciclo = Cycles(Serie, type='annual')
Devtd = Cycles(Serie, type='annual',percentiles='std')
Anom = Serie.copy()
for i in range(len(Serie)):
med = Ciclo[Serie.... | e6d6a9ed11bd6a2d8985b99d3b8a065fab50c273 | 46,191 |
def close_con(session):
"""
Nothing to say
:param session: A section object
:return:
"""
session.close()
return 'Session closed' | 9e33de814328ac855d4c478de836dde543350a32 | 46,192 |
from typing import Tuple
from typing import Dict
def get_message_maps(
force_refresh: bool = False,
) -> Tuple[Dict[str, Node], Dict[str, Client]]:
"""Gets Node and Client protobufs, computes their internal statuses, and return their maps.
If the cache doesn't contain the message maps, this function read... | 082e1196f9c2117b350134bcab948cfece07c380 | 46,193 |
def safe_str_convert(s, strict=False):
"""Convert a string to ASCII without throwing a unicode decode error.
@param s (any) The thing to convert to a str.
@param strict (boolean) If True make sure that there are no
unprintable characters in the given string (if s is a str). If
False do no modifica... | 1937a9750a86c8fa2dadeb75595d2975c1c32b27 | 46,196 |
def _vectorize_voxels(voxels_linear, size_x, size_y):
"""
Convert linear array of voxel indices to 3D array of voxel indices.
Inputs:
voxels_linear (np vector of ints) - linear array of indicies
size_x (int) - size of voxel space in x direction (in voxels)
size_y (int) - size of voxel space in ... | 9d43d2d547e9bb59169bb118f4269bdde0f051ca | 46,197 |
import pkg_resources
def _get_user_dir():
"""Get the users data directory location."""
app_name = pkg_resources.require('zegami-cli')[0].project_name
return user_data_dir(app_name, 'zegami') | 7a7691be4cc91afcbec05aa14830df1af4369cde | 46,198 |
import inspect
def collect_derivatives(expressions):
"""
Exploit linearity of finite-differences to collect `Derivative`'s of
same type. This may help CIRE creating fewer temporaries while catching
larger redundant sub-expressions.
"""
processed = []
for e in expressions:
# Track t... | 097863fc0d71d1ec97be98ac46da5234b7331362 | 46,199 |
def pdf(X, m, S):
"""
Calculates the probability density function of a Gaussian distribution:
X is a numpy.ndarray of shape (n, d) containing the data points whose PDF
should be evaluated
m is a numpy.ndarray of shape (d,) containing the mean of the distribution
S is a numpy.ndarray of shape (d... | 56d53f34c3d58e359f0f19279f8db125aebe2e3f | 46,201 |
def find_correct_weight(program_weights, program, correction):
"""Return new weight for node."""
return program_weights[program] + correction | 994c25efef10fa37971372f444a879e816708830 | 46,202 |
from typing import Optional
def segment_mask(segment_ids: JTensor,
source_segment_ids: Optional[JTensor] = None,
dtype: jnp.dtype = jnp.float32) -> JTensor:
"""Computes (non-causal) segment mask.
Args:
segment_ids: a JTensor of shape [B, T], the segment that each token belon... | 3ea357746326b6a88c5017e1fe6d4b0141b69519 | 46,203 |
def handle_keys():
"""
This version use keypad (hence KP?). Not tested.
"""
global fov_recompute
global mouse_coord
keypress = False
for event in tdl.event.get():
if event.type == 'KEYDOWN':
user_input = event
keypress = True
if event.type == 'MOU... | 04be0066018da8d5ac52ceeeb83c357734bccbf1 | 46,204 |
import ctypes
def errcheck_object(result, func, args):
"""Checks the return value of NormFileEnqueue and NormDataEnqueue"""
if result == ctypes.c_void_p.in_dll(libnorm, "NORM_OBJECT_INVALID"):
raise NormError(
"Error creating object from function '%s'" % func.__name__)
return resul... | 5d654f34937ae0784470ba6264afc9a5bfc8774b | 46,206 |
def encode(delta_str, n_vertices, base, m=False):
"""Encodes delta string as a big integer.
Args:
delta_str: A string with delta coordinates in reference to min_x and min_y, min_x and min_y also included
n_vertices: Number of vertices in the polygon
base
Returns:
A dict map... | 35353910c61610add5df138934caa2ad94c63daf | 46,208 |
def get_most_common_elements(iterator):
"""Returns a generator containing a descending list of most common elements."""
if not isinstance(iterator, list):
raise TypeError("iterator must be a list.")
grouped = [(key, len(list(group))) for key, group in groupby(sorted(iterator))]
return sorted(gr... | c259560a3ca8e8c2e8b0666a67f866a2a8c736c0 | 46,209 |
import starlette
def build_starlette_request(scope, serialized_body: bytes):
"""Build and return a Starlette Request from ASGI payload.
This function is intended to be used immediately before task invocation
happens.
"""
# Simulates receiving HTTP body from TCP socket. In reality, the body has
... | 76e7ed35ab1ecb8375696bcb474deeaec75a03dc | 46,210 |
import yaml
def create_namespace_with_name_from_yaml(v1: CoreV1Api, name, yaml_manifest) -> str:
"""
Create a namespace with a specific name based on a yaml manifest.
:param v1: CoreV1Api
:param name: name
:param yaml_manifest: an absolute path to file
:return: str
"""
print(f"Create ... | 11f06eabefdf3b8ba9c4354345896fed076b98a8 | 46,212 |
def sd_generate_state(model, n_steps, n_targets, init_state, birth, death,
noise=True):
"""Generate synthetic data on target states
Provide with a model, number of steps to generate, number of targets,
initial state of each of the targets and the time of the birth and death
of eac... | 4b26ad19a565f5a105ca827f71aec22235a167b6 | 46,213 |
def value_of_ace(card_one, card_two):
"""Calculate the most advantageous value for the ace card.
:param card_one, card_two: str - card dealt. See below for values.
:return: int - either 1 or 11 value of the upcoming ace card.
1. 'J', 'Q', or 'K' (otherwise known as "face cards") = 10
2. 'A' (ace... | 90ff26e76c116fd1cb803b56362d28aec1d642e4 | 46,214 |
from typing import Dict
def autoapi_skip_member(app: Sphinx, what: str, name: str, obj: PythonPythonMapper, would_skip: bool, options: Dict):
"""Project specific skip function for AutoAPI."""
if '__init__' in name:
return False
return would_skip | 9ec70eeec97c3713ac10f2beb27a63b96ecadb3f | 46,215 |
async def post_settings(update: AdvancedSettingRequest) -> AdvancedSettingsResponse:
"""Update advanced setting (feature flag)"""
try:
await advanced_settings.set_adv_setting(update.id, update.value)
except ValueError as e:
raise LegacyErrorResponse(message=str(e)).as_error(status.HTTP_400_B... | ff558558089ccbdd9e5c94d0a2be5558fbcfe672 | 46,216 |
def safe_log10(data):
""" A safe function for LOG10 in cases of too small values (close or equal to 0 ) """
prob_tmp = np.where(data > 1.0e-10, data, 1.0e-10)
result = np.where(data > 1.0e-10, np.log10(prob_tmp), -10)
return result | 861030069dad485188d3b23750e6395b11ff4ff2 | 46,217 |
def offset(point, direction, distance=1):
"""Offsets a point in a given direction some distance,
E.g. (0, 0) offset 'R' by 2 => (2, 0)
Args:
point (Point): the point to use for the offset point
direction (str): a valid direction ('U', 'R', 'D' or 'L')
distance (Optional[int]): the d... | 3998cbb0bf2f4af3930677fd991967404a1c173d | 46,218 |
def property_entropy(col, sim_matrix, bg_distr, seq_weights, gap_penalty=1):
"""Calculate the entropy of a column col relative to a partition of the
amino acids. Similar to Mirny '99. sim_matrix and bg_distr are ignored, but
could be used to define the sets. """
# Mirny and Shakn. '99
property_pa... | af8e4ded39ec68f7d9c282b327d8ed3245d70bb8 | 46,219 |
from re import T
def set_p_to_zero(pvect, i):
""" Provided utility function: given a symbolic vector of
probabilities and an index 'i', set the probability of the
i-th element to 0 and renormalize the probabilities so they
sum to 1.
"""
new_pvect = T.set_subtensor(pvect[i], 0.)
new_pvect =... | da7287606ed7e62c1c30adc165b74c6794da7c2b | 46,220 |
import requests
def get_cards(session: requests.sessions.Session, dni: str) -> list:
"""Returns cards list and details using the session provided."""
endpoint = GET_CARDS_ENDPOINT
data = {
"dni": dni,
}
json_response = session_post(session, endpoint, data)
card_list = json_response["re... | f96d24149c481228e4edb39c6dbf633828adea8c | 46,221 |
def configure_i18n(app):
""" 国际化支持. """
babel = Babel(app)
@babel.localeselector
def get_locale():
if has_request_context() and request:
# Request a locale and save to session
rl = request.args.get('_locale', None)
if rl:
accept_languages = ap... | a3fadcb4ef107e56bfd630ef0182115b7f9348b1 | 46,223 |
from datetime import datetime
def process_articles_results(articles_results_list):
"""
Function that process the list of article from the request.
"""
articles_results = []
for individual_article in articles_results_list:
title = individual_article.get('title')
description = indivi... | 0af29222fd77e742a1f59049877f2892fb57c6c0 | 46,224 |
import networkx
import itertools
import random
def _compute_diagram_component(Primes, Update, Subspaces, EdgeData, Silent):
"""
Also computes the commitment diagram but without removing out-DAGs or considering connected components separately.
Not meant for general use. Use compute_diagram(..) instead.
... | 1d6a5c979bc40bfc8363e8dfc3d69df575fbd1a8 | 46,225 |
def translate_english_to_chinese(target_str):
""" translate English to Chinese
Args:
target_str (str): target string
"""
translator = Translator(to_lang="chinese")
result = translator.translate(target_str)
return result | c6d78feff9d6c18b8966160775bb8ff4f2900ad2 | 46,226 |
def div(a,b):
"""Elementwise division with another vector, or with a scalar."""
if hasattr(b,'__iter__'):
if len(a)!=len(b):
raise RuntimeError('Vector dimensions not equal')
return [ai/bi for ai,bi in zip(a,b)]
else:
return [ai/b for ai in a] | c12511e47a4366efc8d248b7abfac2eea02644c5 | 46,227 |
def part2(grid):
"""
A basin is all locations that eventually flow downward to a single low point.
Therefore, every low point has a basin
Locations of height 9 do not count as being in any basin
All other locations will always be part of exactly one basin.
The size of a basin is the number of lo... | 7876ab48d5290654919f396b04b5146310d53b37 | 46,228 |
import re
def normalize_twitter_hashtag(text):
"""hashtagを共通の文字列に置き換える(含んでいることを表したい)"""
return re.sub(r"#\w+", "#hashtag", text) | bccff4f413732b5d401e5dd362b299998f707f1c | 46,229 |
def get_market_price_change_by_ticker(fromdate: str, todate: str, market: str="KOSPI", adjusted: bool=True) -> DataFrame:
"""입력된 기간동안의 전 종목 수익률 반환
Args:
fromdate (str ): 조회 시작 일자 (YYYYMMDD)
todate (str ): 조회 종료 일자 (YYYYMMDD)
market (str , optional): 조회 시장 (KOSPI/... | 0bb2775baef9436c19a8edbbd6f72aea212ca7a1 | 46,230 |
import scipy.signal as sig
def filter(data, low=300, high=6000, rate=30000):
""" Filter the data with a 3-pole Butterworth bandpass filter.
This is used to remove LFP from the signal. Also reduces noise due
to the decreased bandwidth. You will typically filter the raw data,
then extract... | 59801cbd04878a6a5049262c283e4d18b042a53d | 46,232 |
def load_config(filepath: str) -> ConfigFile:
"""Load configuration
Arguments:
filepath {str}
Returns:
{ConfigFile} -- query parameters
"""
config = ConfigFile.from_filename(filepath)
validate(config.content, config.version)
return config | 328907c370308369436e7ff55cd0a11ee5c55572 | 46,233 |
def szudzik_pair(pairs: np.ndarray) -> np.ndarray:
"""
Numpy implementation of a pairing function by Matthew Szudzik
Args:
pairs (np.ndarray): n x 2 integer array of pairs.
Returns:
hash_list (np.ndarray): n x 1 integer array of hashes.
"""
xy = np.array(pairs)
x = xy[..., ... | 5eaa4f9c8fd62f0409bf7e01e2609220c6f336cf | 46,234 |
def relu(x):
"""
Compute the relu of x
Arguments:
x -- A scalar or numpy array of any size.
Return:
s -- relu(x)
"""
s = np.maximum(0,x)
return s | 9531d5cc64e4721d25482e0f5f3257d2255e2a5b | 46,235 |
def get_instance_id(finding):
"""
Given a finding, go find and return the corresponding AWS Instance ID
:param finding:
:return:
"""
for kv in finding['attributes']:
if kv['key'] == 'INSTANCE_ID':
return kv['value']
return None | f4f6826dc02664b95ca8fdc91d89a6429192b871 | 46,238 |
from typing import Optional
def get_winning(process_id: int) -> Optional[list[Version]]:
"""Get a dict of the winning process versions per customer category.
Format of dict:
[{
'customer_category': str,
'winning_version': Version.A or Version.B
}]
:param process_id: specify proces... | 322299b7e28ca5429695d5b310b269853279f09e | 46,239 |
def BackwardFoldScaleAxis():
"""Backward fold axis scaling into weights of conv2d/dense.
Returns
-------
ret : tvm.relay.Pass
The registered pass to backward fold expressions.
Note
----
It is recommended to call backward_fold_scale_axis
before using forward_fold_scale_axis as b... | dc9bb99fa02920a643c8fa59d4e08c29e4a3826f | 46,240 |
def refresh(request):
"""Endpoint that'll use the database information to update running
process"""
ips_from_database = [x.ip for x in Machine.objects.all()]
database_machines_found = LocalNetworkScanner().refresh(ips_from_database, PORTS)
# if machine in database found on netowkr
ips_from_fou... | ed0c28a1c02525c7396ee04cb9d92e7a10f1a349 | 46,241 |
def triple(subject, relation, obj):
"""Builds a simple triple in PyParsing that has a ``subject relation object`` format"""
return And([Group(subject)(SUBJECT), relation(RELATION), Group(obj)(OBJECT)]) | b4c3a1bf4192fbf7a5c0c155551633cd7eb34678 | 46,242 |
def get_article_sentiment(article):
"""
Extracts sentiment analysis for article.
@param article: article dictionary (retrieved from the Data Lake)
@returns: (article_level_polarity, article_level_subjectivity)
"""
if language_dict[article['media']] == 'DE':
blob = TextBlobDE(article['tex... | d07fba0a706571d6e3f22793e99f3ae5890c995c | 46,243 |
def frame_to_yaml_safe(frame):
"""
Convert a pandas DataFrame to a dictionary that will survive
YAML serialization and re-conversion back to a DataFrame.
Parameters
----------
frame : pandas.DataFrame
Returns
-------
safe : dict
"""
return {col: series_to_yaml_safe(series)... | f33f0ca3b0c4fe689639a99b2f4bf44fc06e9973 | 46,244 |
def coach_or_competitor(username):
"""converts a string to bytes
Args:
username: the user whose should be checked
Returns:
renders the competiotr template if user is comeptitor or the coach one if coach
"""
if is_coach(username):
print "This user is a coach"
return... | 98750b1cb80ee59c2481672350867b429e660746 | 46,246 |
def taint_name(rawtxt):
"""check the interface arguments"""
tainted_input = str(rawtxt).lower()
for test_username in get_user_list():
if tainted_input in test_username:
return test_username
return None | 4407508960ddfcdd267ab427227db0d009183221 | 46,247 |
def cdlsticksandwich(opn, high, low, close):
"""Stick Sandwich:
A stick sandwich is a technical trading pattern in which three candlesticks form what appears
to resemble a sandwich on a trader's screen. Stick sandwiches will have the middle candlestick
oppositely colored of the candlesticks on either s... | 192f85c1de98f4095fad9a5d3a1cbc2d7df53e49 | 46,248 |
def sample_bounded_multicoal_tree(stree, n, T, leaf_counts=None, namefunc=None,
sroot=None, sleaves=None, stimes=None,
gene_counts=None):
"""
Returns a gene tree from a bounded multi-species coalescence process
stree -- species tree
... | b5cc1bd53d86ef588ab36ebe0ffc54ed7e7e5e2b | 46,249 |
def collect_inventory_license_expression(location, scancode=False):
"""
Read the inventory file at location and return a list of ABOUT objects without
validation. The purpose of this is to speed up the process for `gen_license` command.
"""
abouts = []
if scancode:
inventory = gen.load_... | cb2020b2e89aa2294d46fe890d846548e1f88b32 | 46,250 |
def node_hist_fig(
node_color_distribution,
title="Graph Node Distribution",
width=400,
height=300,
top=60,
left=25,
bottom=60,
right=25,
bgcolor="rgb(240,240,240)",
y_gridcolor="white",
):
"""Define the plotly plot representing the node histogram
Parameters
--------... | 35ad64446612a98db6df49d364679d0a890eca1e | 46,251 |
def analytic_solution_modes(dx, p, nx, ny, x, y, c, t, n):
"""
Analytic solution for acoustic modes in 2D rectangular domains.
:param dx spatial step after discretization, scalar (m).
:param p numerical acoustic pressure used for the sizes, 2D-array (Pa).
:param nx mode number (... | b2b69cb4bb8b4a827cbb8818750a9f86e0c33773 | 46,252 |
from typing import Dict
def encode_images(format_dict: Dict) -> Dict[str, str]:
"""b64-encodes images in a displaypub format dict
Perhaps this should be handled in json_clean itself?
Parameters
----------
format_dict : dict
A dictionary of display data keyed by mime-type
Returns
... | c1dd645767d272a257cdd257d9854c2abad82353 | 46,253 |
def read_catl(path_to_file):
"""
Reads survey catalog from file
Parameters
----------
path_to_file: `string`
Path to survey catalog file
survey: `string`
Name of survey
Returns
---------
catl: `pandas.DataFrame`
Survey catalog with grpcz, abs rmag and stell... | 6013689b4d6f8558dba11cac5ece8d41bd38da8c | 46,255 |
def deconv(in_planes, out_planes, upscale_factor=2):
"""2d deconv"""
kernel_size, stride, opad = get_deconv_params(upscale_factor)
# print("DECONV", kernel_size, stride, opad)
return nn.ConvTranspose2d(in_planes, out_planes,
kernel_size=kernel_size,
... | 7b1f32915aee14b64564c92e20cb372935b3c759 | 46,256 |
from cntk.cntk_py import bernoulli_random_like
def bernoulli_like(x, mean=0.5, seed=auto_select, name=''):
"""bernoulli_like(x, mean=0.5, seed=auto_select, name='')
Generates samples from the Bernoulli distribution with success probability `mean`.
Args:
x: cntk variable (input, output, parameter,... | 943804bcb7725533242fa674c7357b9b56cc0655 | 46,258 |
def dVdc_calc(Vdc,Ppv,S,C):
"""Calculate derivative of Vdc"""
dVdc = (Ppv - S.real)/(Vdc*C)
return dVdc | 59d2708726e078efb74efce0bac2e397ba846d89 | 46,259 |
def percentile_spectrogram(spg, f_axis, rank_freqs=(8., 12.), pct=(0, 25, 50, 75), sum_log_power=True, show=True):
""" Compute percentile power spectra using the spectrogram, ranked by power within
a specific band. Essentially a different way of visualizing correlation between freqs.
Parameters
-------... | 44154d001479b82b14d4b9e794b56f49500ec4bf | 46,260 |
import math
def _get_cold_progression(age, rng, carefulness, preexisting_conditions, really_sick, extremely_sick):
"""
[summary]
Args:
age ([type]): [description]
rng ([type]): [description]
carefulness ([type]): [description]
preexisting_conditions ([type]): [description]... | 6fad1e52bddba28ca4045ed79e8838441ec32483 | 46,261 |
def project_to_image_space(anchors, stereo_calib_p2, image_shape):
"""
Projects 3D anchors into image space
Args:
anchors: list of anchors in anchor format N x [x, y, z,
dim_x, dim_y, dim_z]
stereo_calib_p2: stereo camera calibration p2 matrix
image_shape: dimensions of ... | 927267f0c4a75a5fdf5f0f52456c7e7ac48931f7 | 46,262 |
def define_model(quant_features, qual_features):
"""Define model
Args:
quant_features (list of str): corresponding to column names of training data
qual_features (list of str): corresponding to column names of training data
Returns:
model (sklearn obj)
"""
# transf... | 6cb132f0c7d58655afd8f3779712e62e8842bdef | 46,263 |
def check_order(df, topcol, basecol, raise_error=True):
"""
Check that all rows are either depth ordered or elevation_ordered.
Returns 'elevation' or 'depth'.
"""
assert basecol in df.columns, f'`basecol` {basecol} not present in {df.columns}'
if (df[topcol] > df[basecol]).all():
return... | 9b4e7b9938bb2fe14ab99d5c111883a0f6d73337 | 46,264 |
async def list_keys(hub, ctx, name, resource_group, **kwargs):
"""
.. versionadded:: 2.0.0
Retrieve a Redis cache's access keys. This operation requires write permission to the cache resource.
:param name: The name of the Redis cache.
:param resource_group: The name of the resource group.
CL... | 410ee854ae90de02f1b41dc32eaccd74d202462e | 46,267 |
from typing import Tuple
def new_simple_controller_config(
config: dict = None,
options: dict = None,
config_from_file=False,
serial_number="1111",
devices: Tuple[pv.VeraDevice, ...] = (),
scenes: Tuple[pv.VeraScene, ...] = (),
setup_callback: SetupCallback = None,
) -> ControllerConfig:
... | 8353cc001d7527afeb475e7b293812df7adf26e9 | 46,268 |
import torch
def online_mean_and_std(loader):
"""Compute the mean and sd in an online fashion
Var[x] = E[X^2] - E^2[X]
"""
cnt = 0
fst_moment = torch.empty(3)
snd_moment = torch.empty(3)
for x, y in loader:
b, c, h, w = x.shape
nb_pixels = b * h * w
sum_ = to... | 25479de7b88385d0714e3bf26ce6cbb151bf04f1 | 46,269 |
def GetDevice(serial=None):
"""Returns and ADBDevice given its serial.
The first connected device is returned if serial is None.
"""
devices = [d for d in ListDevices() if not serial or serial == d.serial]
return devices[0] if devices else None | ccf6451aa48b98efba03be4fa4438920b0fc5374 | 46,270 |
def api_demo_data_project(): # noqa: F401
"""Get info on the article"""
subset = request.args.get('subset', None)
if subset == "plugin":
result_datasets = get_dataset_metadata(exclude="builtin")
elif subset == "test":
result_datasets = get_dataset_metadata(include="builtin")
else:... | ca63c2803d9e0720cde7142eef8074bbef3eec40 | 46,271 |
def nonmax_supression(x):
"""Nonmaximum suppression finds crests of a signal.
All other non-maxima found from thresholding are suppressed.
Args:
x (1D numpy array): a signal which has been thresholded to only
contain maximum peaks.
Returns:
1D numpy array: an array indexes ... | cee150df2fb53dc8ad2fd1a0949dcf2e81608588 | 46,273 |
def ipv4_subnet_details(addr, mask):
"""
Function that prints the subnet related details- Network, Broadcast, Host IP range and number of host addresses
:param addr: IP address
:param mask: subnet mask
:return: result dictionary containing the details
"""
network_address = []
broadcast_a... | 7d872a63b9a0968eabbe9af7ccfbfda311346bc8 | 46,275 |
def _get_sdk_name(platform):
"""Returns the SDK name for the provided platform.
Args:
platform: The `apple_platform` value describing the target platform.
Returns:
A `string` value representing the SDK name.
"""
return platform.name_in_plist.lower() | 0bc7f446472f44e52ea0b11cda7397e48848f0ef | 46,276 |
def myplus(a, b=0):
"""
Parameters
----------
a : float
the first number
b : float
the second number
defaults to zero
Returns
-------
a + b
"""
return a + b | c9efbff1babaae75c51401f56d830e8b7a543286 | 46,277 |
def read_data_from_fp_numpy(fp):
"""
Read the data from a single Silixa xml file. Using a simple approach
Parameters
----------
fp : file, str, or pathlib.Path
File path
Returns
-------
data : ndarray
The data of the file as numpy array of shape (nx, ncols)
Notes
... | 5b06e049df52abd262add9e1f449a1317df2d67e | 46,278 |
import tqdm
def schedule_jobs(
fns, concurrency=DEFAULT_THREADS,
progress=None, total=None, green=False
):
"""
Given a list of functions, execute them concurrently until
all complete.
fns: iterable of functions
concurrency: number of threads
progress: Falsey (no progress), String: Progress + ... | b4ae40ba37709f7f323b9dcf6bfa7ffce174fa9e | 46,279 |
def Hamming_bit_decoder(N,kind='bit',read=True,name='decoder'):
"""Hamming Gate resistant to bit-fips"""
circ=HammingCircuit(N, ancillas=N)
if kind=='phase':
circ.h([*range(2**N)])
circ.append(syndrome(N),[*range(2**N+N)])
circ.append(apply_syndrome(N),[*range(2**N+N)])
if read==True: ci... | 9b9e44d1708c57b7c218fe4b5f1e66928942ab30 | 46,280 |
def KeycodeToDIK(keycode):
"""
Convert a (Tkinter) keycode to a DirectInput Key code
If not in table, return keycode as hex
"""
_res = f'0x{keycode:02x}'
for dik, entry in DirectInputKeyCodeTable.items():
if entry[1] == keycode:
_res = dik
break
return _res | 608931cae3f47b80b9048aa5532d0b6fb95a8719 | 46,282 |
import logging
def tts_request(announcement="Text to speech example announcement!") ->str:
"""Test function to check that the text to speech is working appropriately"""
engine = pyttsx3.init()
engine.say(announcement)
engine.runAndWait()
logging.info('tts test run')
return "Hello text-to-speec... | 24e6b9680dc8e6d3160995d690b9b16defbe52a0 | 46,283 |
from typing import List
import random
def roll_relationships(relationship_points: int, min_icons: int) -> List[IconRelationship]:
"""
:param relationship_points:
How many points are spent to relationship.
:param min_icons:
Minimum number of different icons to have a relationship to.
:... | d951fa6676c8db9bbf3213379aa824d83fd96a12 | 46,284 |
import re
def ALMAUVFITSTab(inUV, filename, outDisk, err, \
exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL"], \
include=[], logfile=""):
"""
Write Tables on UV data as FITS file
Write Tables from a UV data set (but no data) as a FITAB format file
His... | 54ffa1a38b8ae37949b2e2ae9b92eea7ba9f7316 | 46,285 |
def create_children(input_node, node_holder, max_frag=0, smiles=None, log_file=None, recurse=True):
"""
Create a series of edges from an input molecule. Iteratively
:param input_node:
:param max_frag: Max initial fragments (or no limit if 0)
:param smiles: A SMILES string, for log/diagnostics only.
... | fe36b1b81fc7668498f8da318a9864b31a272a70 | 46,286 |
import re
def typify(node):
"""Convert the input into the appropriate
type of ExpressionBase-derived Node. Will
apply pattern matching to determine if a
passed string looks like a numerical constant
or if the input is a numerical constant, return
the appropriate node type.
Parameters
... | 4024effbe9176acc10cdf25ce398b6cb2826b8ba | 46,287 |
import pathlib
def file_exists(file_path):
""" Returns true if file exists, false if it doesnt """
file = pathlib.Path(file_path)
return file.is_file() | d8219f71cf891d2d4e9c95670bd90b957becfdc5 | 46,288 |
import hashlib
import json
def hasher(obj):
"""Returns non-cryptographic hash of a JSON-serializable object."""
h = hashlib.md5(json.dumps(obj).encode())
return h.hexdigest() | 967ba4a1513bbe4a191900458dfce7a1001a8125 | 46,289 |
def long_word_pct(df):
"""
Get percentage of long words.
Long words are defined as having more than 8 chars.
Needs features:
Words
Adds features:
Long_word_percent: percentage of long words
:param: the dataframe with the dataset
:returns: the dataframe with the added f... | 2d80ea6e93f70ac2d5d68d472a75c0a1b13d6dee | 46,290 |
def check_answer(question_id, answers_list):
"""
Check answers for question.
Convert answers to boolean values for comparing with correct answers.
Answer wil get point if correct, not empty and all correct choices was chosen.
@param question_id: Question object id --> int
@param answers_list: ... | a092646d38e608f88b3191368dcf23c5770323e6 | 46,291 |
def _to_float(expr):
"""Converts a sympy expression to a Python float
The given expression must be a sympy ``Number`` isinstance, or ValueError
will be raised.
"""
res = expr.evalf()
if isinstance(res, Number):
return float(res)
else:
raise ValueError(
'Expressi... | cb0a0fbca7410d4d32c003e29f86b946a84d69e6 | 46,292 |
def atom_count(gra, dummy=False, with_implicit=True):
""" count the number of atoms in this molecule
by default, this includes implicit hydrogens and excludes dummy atoms
"""
if not dummy:
gra = without_dummy_atoms(gra)
natms = len(atoms(gra))
if with_implicit:
atm_imp_hyd_vlc_d... | 66ff22f6ff7785200ecca8f20bc1247120bb565a | 46,293 |
import numpy
def isstarboard(ctx, scene, node1, node2):
""" Returns True if node1 is on the right of node2 based on a view matrix
calculated from the 'face' of node 2.
For node1 to be on the right of node2:
- node2 to must be considered to have a front face.
- the view transformed... | f4d545ce98ae032d3116b814e3470b5fc514659e | 46,294 |
import glob
def get_tls_path(opts, id_type, namespace, release):
"""Get path to the directory containing TLS materials for a node
Args:
opts (dict): Nephos options dict.
id_type (str): Type of ID we use.
namespace (str): Name of namespace.
release (str): Nam... | cf4c35163e5852109deed7aa7aa611b41b7a9e54 | 46,295 |
def _length_hint(obj):
"""Returns the length hint of an object."""
try:
return len(obj)
except TypeError:
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
except TypeError:
... | 267f6242b5e0c901c30ebaa01b2c39472d3ae07e | 46,296 |
def _root_sort_key(root):
"""
Allow root comparison when sorting.
Args:
root (str or re.Pattern): Root.
Returns:
str: Comparable root string.
"""
try:
return root.pattern
except AttributeError:
return root | 51a7e51b58cbdf8c3277844903950282a5368815 | 46,297 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.