content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import functools
def firmware_command(fn):
"""Check if we are in the firmware before running commands that require it."""
@functools.wraps(fn)
def _decorated(self, *args, **kwargs):
# if self.status != 'firmware':
# # Note: we could instead reset_to_firmware here.
# raise Bli... | 6941c0a755a208c8fbd7860c716bd2dc6848546f | 68,288 |
def have_encoder_for_format(format_id: HeifCompressionFormat) -> bool:
"""Wrapper around `libheif.heif_have_encoder_for_format`"""
return lib.heif_have_encoder_for_format(format_id) | 813bf400bde9d5760357ffcfb34de21bc6dfb6fd | 68,290 |
def process_path_for_cand(path, docsents):
"""
processing the paths for a candidate
:param path:
:param docsents:
:return:
"""
he_docidx = path['head_ent_docidx']
he_doc_len = get_doc_len(docsents, he_docidx)
he_ent_loc_dict = path['head_ent']
he_locs = []
he_words = list(he_... | 5998432f69b34f24a85fae25b9fb41d7871e0008 | 68,291 |
def ijkl2MN(ijkl):
"""
Convert (i, j, k, l) indices of a symmetric
4nd-order tensor to its matrix index
"""
ij = ijkl[:2]
kl = ijkl[2:]
M = ij2M(ij)
N = ij2M(kl)
return M, N | 6a9630fb386e1b40bb02e7337150bd1c3154b788 | 68,292 |
def extract_references(fileName):
"""Runs the extraction engine over a single file, specified by its name (full or relative path).
1. Convert the PDF to a plain text document
2. Extract references from the text
Returns the references
"""
print "Converting PDF to plain text..."
docu... | ecf3518d438259a03551d14d8177a42fa9263c5e | 68,293 |
import hashlib
import io
def calculate_file_checksum(path):
"""
Calculate the MD5 sum for a file:
Read chunks of a file and update the hasher.
Returns the hex digest of the md5 hash.
"""
hasher = hashlib.md5()
with io.FileIO(path, 'r') as fp:
while True:
buf = fp.read(6... | 6bddfd83a8bc326fcfea8fb69affde45f3cb1dd8 | 68,294 |
import torch
def get_position(lens, maxlen, left_pad=False):
""" transform sequence length to a series of positions. e.g., 3 -> 1,2,3"""
batch_size = lens.size(0)
pos = torch.zeros((batch_size, maxlen), dtype=torch.long, device=lens.device)
for i, input_len in enumerate(lens):
if not left_pad:... | 48c2ac5c0bde1f554b3b44c82177945ab2c667ab | 68,295 |
def memoize(fn):
"""
args and kwargs to fn must be hashable.
"""
cache = {}
@wraps(fn)
def wrap(*args, **kwargs):
if args:
key_args = frozenset(args)
else:
key_args = None
if kwargs:
key_kwargs = frozenset(kwargs.items())
else:... | 8f82a92b5edd1e7197395887e4519830f4b04d4b | 68,298 |
import json
def allPickupBySite():
"""
Récupère la liste de tous les pickup associé au site d'idSite
Args:
request.form doit contenir :
- idSite
Returns:
code 1, data : data contient la liste des pickup
code -1, message : erreur lors de la récupéra... | b04bdc6d04493bc8e57c861193225da1f1569e65 | 68,299 |
def get_test_image():
"""Test image representing coordinate grid
--------------------
| | | | | | |
--------------------
| | | | | | |
--------------------
| | | | | | |
--------------------
| | | | | | |
--------------... | 54fcf5167aecbd131171d0dab8dac0bb4303f7d4 | 68,300 |
def next_missing_index(prefix, i):
""" Determine netxt index that has not yet been downloaded
"""
while(index_exists(prefix, i)):
i = i+1
return i | f0105c0d37bdf69e93af6d2fd41dd90f2d6b19f6 | 68,301 |
import re
def filename_from_name(name):
"""Shorten the name of a whatever to something suitable as a filename.
e.g. Water's Edge -> waters-edge
"""
name = unicode(name)
name = name.lower()
name = re.sub(u'[ _]+', u'-', name)
name = re.sub(u'[\'.()]', u'', name)
return name | 546239b3a0b8e0399d3d444bf528c55bcc3cea54 | 68,303 |
def get_total_balance():
""" Get total balance
Returns:
---------
Returns total balance of all accounts
"""
return sum(record['values']['balance'] for record in get_accounts()) | d03a09ab27fc646ce3a68364fccfc0784d09ce26 | 68,304 |
def generate_mu_z(size=1000, z0=0.3, dmu_0=0.1, dmu_1=0.02,
random_state=None, cosmo=None):
"""Generate a dataset of distance modulus vs redshift.
Parameters
----------
size : int or tuple
size of generated data
z0 : float
parameter in redshift distribution:
... | bda9f00784f1a16724a4482d504090446cd5061e | 68,305 |
def compute_test_rates():
"""Compute the exact rates to test
HAL takes in integer rates values
This function handles the floating point to integer issues
"""
test_rates = np.sort(list(BASE_RATES) + list(INTERMEDIATE_RATES))
print("Base rates:\n{}".format(BASE_RATES))
print("Intermediate... | 25326962772b155c46a697c756ea6838fe4cbc39 | 68,306 |
def rsqrt(x):
"""Take reciprocal of square root of input x.
Parameters
----------
x : PrimExpr
Input argument.
Returns
-------
y : PrimExpr
The result.
"""
return call_intrin(x.dtype, "tir.rsqrt", x) | de6b0756a232c8513832ec36d76531c076fb2805 | 68,307 |
def convert_bxd_name(name: str) -> str:
"""
the names of BXDs are not consistent across all metadata
and VCF files, so we sometimes have to convert their names
>>> convert_bxd_name("4512-JFI-0469_BXD100_RwwJ_phased_possorted_bam")
"BXD100_RwwJ_0469"
>>> convert_bxd_name("4512-JFI-0410_BXD013_T... | 577f936d81fdd7a87bd02fec069ff5f09e3b1412 | 68,309 |
from typing import Optional
from typing import Any
import functools
import asyncio
async def create_pool(
settings_: RedisSettings = None,
*,
retry: int = 0,
job_serializer: Optional[Serializer] = None,
job_deserializer: Optional[Deserializer] = None,
default_queue_name... | 1248a0053bb9ccbe9961120d52a745add885f622 | 68,310 |
def ExactCover(grid, x, y):
"""
Calculates the Exact Cover for an element in the grid and returns all possible numbers.
"""
x_axis = get_x_axis_elements(grid[x])
y_axis = get_y_axis_elements(grid, y)
BlockOfCoordinates = ReturnBlockOfCoordinates(x, y)
block = set()
steps = in... | ae8ef61ae32b976ff369641644538ab34b4c10e4 | 68,311 |
import torch
def makeInp(inputs):
"""Move tensors onto GPU if available.
Args:
inputs: A dict with a batch of word-indexed data from DataLoader. Contains
['brk_sentence', 'bs_inp_lengths', 'style', 'sentence', 'st_inp_lengths', 'marker', 'mk_inp_lengths']
Returns:
inputs: The dict with same structure but s... | af00b78f33627f45e505a6b8c75fb07ef29b94e6 | 68,312 |
import html
def parse_cbr_key_indicators(content: str):
"""
The function to parse USD, EUR and precious metals
rates from CBR site
"""
root = html.fromstring(content)
tables = root.xpath('//table')[:2]
result = {}
for table in tables:
for row in table[0][1:]:
key =... | 34b3820706be413fcb9cf9b1f735bf5870d8cad9 | 68,315 |
def kl_divergence(p, q, regularizer=None):
"""
Returns a notion of "distance"
between two probability distributions
p and q.
"""
if regularizer is None:
regularizer = lambda: 0
return -tl.sum(p * tl.log(q / p)) + regularizer() | 85d2aae875a39321752e476d0cfb00d8571ea0a3 | 68,317 |
import warnings
def rename_internal_nodes(tree, names=None, inplace=False):
""" Names the internal according to level ordering.
The tree will be traversed in level order (i.e. top-down, left to right).
If `names` is not specified, the node with the smallest label (y0)
will be located at the root of t... | d5df42023afe184af41d7553b2e1491b09d5edc1 | 68,318 |
def compare_score_file(df_res, df_res_ref):
"""
Compare df_res
"""
col_list = ["raw_score", "norm_score", "mc_pval", "pval"]
for col in col_list:
v_ = df_res[col].values
v_ref = df_res_ref[col].values
err_msg = "Inconsistent values: {}\n".format(col)
err_msg += "|{:^... | e8fddbe5a019525ab86696d0be9e77c89e32e77f | 68,319 |
def get_base64(cred=None, filename=CFG_FILENAME, api=None):
"""Return base64 encoded string."""
assert api
credentials = _read_cfg(
default_value=cred, filename=filename, key_to_read=api
)
output = b64encode("{}".format(credentials).encode(encoding="ascii"))
return output.decode("ascii") | 8dd23a0c762348f116dc171ad8c1e0d884c90b6b | 68,320 |
import requests
import json
def api(q, user):
"""
http://docs.ruyi.ai/344886
"""
url = 'http://api.ruyi.ai/v1/message'
params = {
'q': q.strip(),
'app_key': config.RUYI_API_KEY,
'user_id': user.id
}
try:
r = sess.get(url, params=params)
except requests.R... | fa2dc307d2d1df99e6ab236965bc663a3f017e32 | 68,321 |
def calc_iou(box_a, box_b):
"""Computes IoU of two axis aligned bboxes.
Args:
box_a, box_b: 6D of center and lengths
Returns:
iou
"""
max_a = box_a[3:6]
max_b = box_b[3:6]
min_max = np.array([max_a, max_b]).min(0)
min_a = box_a[0:3]
m... | 541c0f681dfb1f62495ed78d06c588de2eedd0e0 | 68,322 |
def sub_cupydense(left, right):
"""
Perform the operation ``out := left - right``
Parameters
----------
left : CuPyDense
Matrix to be added.
right : CuPyDense
Returns
-------
out : CUPyDense
"""
_check_same_shape(left, right)
return left - right | 2dad4a44b0610ce0f89ee562a10606603224a5f5 | 68,323 |
def polyphase_filter_decimate(x, m, f):
"""Decimate x by m with filter taps f."""
return np.sum(polyphase_core(x, m, f), axis=0) | 575da79126da7fadd90d0a4604ff2460793dc6d2 | 68,324 |
def headers(mime, length):
"""Returns a list of HTTP headers given the MIME type and the length of the
content, in bytes (in integer or sting format)."""
return [('Content-Type', mime),
('Content-Length', str(length))] | da5f73591bf9d4bbc8b1d01f4d6babf0de54ce00 | 68,325 |
def search_parser(lineno, line, syntax):
"""Finds a proper parser function for a given line or raises an error
:param lineno:
:param line:
:type syntax: :class:`plim.syntax.BaseSyntax`
"""
for template, parser in syntax.parsers:
matched = template.match(line)
if matched:
... | 5040a687e9fc7053dbba1b9d756040378ce5e704 | 68,326 |
def triangulate(A, order):
"""Convert linear array to 2-D array with triangular coefficient layout"""
AT = sp.zeros((order + 1, order + 1))
k = 0
for i in range(order + 1):
for j in range(i + 1):
AT[i, j] = A[k]
k += 1
return AT | d30bd30a4c9a39a07e722d586676d15b68b767cc | 68,327 |
def generate_changes(dns_zone, action, data):
"""
Produces a change request (additions, deletions) with the specified data
"""
return dns_zone.discovery.changes().create(
project=utils.get_gcp_config()['project'],
managedZone=dns_zone.name,
body={action: data}) | d198b559db07a6b2f507ab898477effe432e79c0 | 68,328 |
def read_file_binary(filename: str) -> bytes:
"""Get the contents of a binary file contained with qutebrowser.
Args:
filename: The filename to open as string.
Return:
The file contents as a bytes object.
"""
path = _path(filename)
with _keyerror_workaround():
return pat... | 26bb04963a2e27e3abd3784860602a21cb42365c | 68,329 |
def wordle_score(data_connection):
"""Create a wordle score."""
WordleScore.client = data_connection
return WordleScore | 6cdefa5f46e6bfbc26ac9c05f0ed15ac296b6a4a | 68,331 |
def get_dir(dir: str, permissions=0o0775, exist_ok : bool=True):
"""Makes a directory at the given location
Args:
dir (str): Path of the directory
permissions ([type], optional): Permissions of directory. Defaults to 0o0775.
exist_ok (bool, optional): If True, program will continue if d... | 44dba12399e5ff781c96607693658ec2e3ad6917 | 68,332 |
def selection_rate(y_true, y_pred, *, pos_label=1, sample_weight=None):
"""Calculate the fraction of predicted labels matching the 'good' outcome.
The argument `pos_label` specifies the 'good' outcome.
"""
if len(y_pred) == 0:
raise ValueError(_EMPTY_INPUT_PREDICTIONS_ERROR_MESSAGE)
select... | 8682334c7095a8bfa451aa757fd38a0ea01898f1 | 68,333 |
import statistics
def run_stats(this_set):
""" Find standard deviation and mean (average) for the data set. """
# Simply calculate Mean & StdDev for this set.
# Return TUPLE of FLOATS
return statistics.mean(this_set), statistics.stdev(this_set) | 35ce499654bf7e8fe43d862b5456b0578a093fc7 | 68,334 |
def highest_match_action(ic, dc, sc, im, dm, sm, cost):
"""Given the following values, choose the action (insertion, deletion, or
substitution), that results in the highest match score (ties are broken
using the distance values). This is used within the dynamic programming
algorithm.
* ic - inserti... | d1d5b47e02ec9df8b65d3856b8ebba70511ca4d4 | 68,335 |
def routes_messages():
"""Returns currently active messages and notifications for routes specified by parameter 'r'.
If you want to specify multiple routes, use the 'r[]' key in the query string. If no routes are
specified, all active messages will be returned."""
params = utils.qs_params( command='m... | 58a77d5ca7776727f448cd5170898c2edae206a0 | 68,336 |
def generate_csv_url(sheet_url):
"""
Utility function for generating csv URL from a google sheets link
This function generates a link to a csv file from a link used to edit a google sheets file.
The gid must be present in the URL.
Parameters
----------
sheet_url : str
The URL for the... | d941ef98f3400175b9db4f7ef5da858fc6426caf | 68,337 |
import time
def register(request):
"""
List all snippets, or create a new snippet.
"""
if request.method == 'GET':
return Response('get')
elif request.method == 'POST':
''' Sample input
{
"client_id" :12,
"client_secret" : "123sdf",
"em... | 17ac306df386ad5ae4ee36c77d953c04d7843302 | 68,338 |
def get_buffer_variable(a_variable_name):
"""Return the Vim buffer variable named `a_variable_name'."""
return get_prefixed_variable("b", a_variable_name) | a43371a80793a6d73d388db3a2e01635d570b53c | 68,339 |
from course.views import may_set_pretend_facility as mspf
def may_set_pretend_facility(user):
"""
Check if a user may set pretend_facility
:param user: a :class:`accounts.User:` instance
:return: a :class:`bool`
"""
return mspf(user) | 933dddca3c5caa028bd667c0b4f4d311f71e62cc | 68,341 |
def dataAPIFactory(makeInstances=True):
"""
This is a convenience factory for creating a DataAPI instance.
"""
kwds = {}
api = DataAPI
apiArgs = []
return apiFactory(instanceKwds=kwds, makeInstances=makeInstances,
api=api, apiArgs=apiArgs) | 21ebbc0d98a8b16e088e69e884c18d17e8610d68 | 68,342 |
from evennia.web.webclient.views import webclient
def webclient(request):
"""
Webclient page template loading.
"""
# disable autologin until it's fixed in devel
session = request.session
session.flush()
session.save()
return webclient(request) | 16930fb9737ea8d9f7ad108499dc1adb80638627 | 68,343 |
import types
def register(struct_type):
"""Register a `numba.core.types.StructRef` for use in jit-code.
This defines the data-model for lowering an instance of `struct_type`.
This defines attributes accessor and mutator for an instance of
`struct_type`.
Parameters
----------
struct_type ... | dfdbe76aa21368994524e8118aa5ba649c567502 | 68,344 |
from typing import Iterable
import torch
from typing import Optional
def sentences_to_tensor(sentences: Iterable[str],
tokenizer: object,
device: torch.device,
max_sequence_length: Optional[int] = None,
regularize: bool = ... | 01e53abaf34ab437590e1234c3b4721aec2844dd | 68,345 |
def hashed_kgrams(string, k):
"""Return hashes of all k-grams in a string"""
hashes = [hash(string[offset:offset+k])
for offset in range(len(string) - k + 1)]
return np.array(hashes) | 8258aad6a9e13757672c9843a15934862b412c6f | 68,346 |
def enum(**enums):
"""
http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python
"""
return type('Enum', (), enums) | 38e7eeaa682709a624ffbaa861023c18cf7c421d | 68,348 |
import scipy
def robust_std(l, alpha=1/scipy.stats.norm.ppf(0.75)):
"""
Compute a robust estimate of the standard deviation for the list
of values *l* (by default, for normally distributed samples ---
see https://en.wikipedia.org/wiki/Median_absolute_deviation).
"""
return alpha * mad(l)[0] | 17fa4bb89552231ccd7e829a793d5b4c18d4ef8d | 68,349 |
def add_nprocessors_option(parser,default_nprocessors,default_display=None):
"""Add a '--nprocessors' option to a parser
Given a parser instance 'parser' (either OptionParser or
ArgumentParser), add a '--nprocessors' option.
The value of this option can be accessed via the 'nprocessors'
attribute ... | cbc1fb90f258271f9cc09fb87b5c7be566776f9b | 68,351 |
def not_found(error):
"""Handler for 'not found' error."""
return make_response(jsonify({'error': 'Not found'}), 404) | 2d71367f72bed2ff80eddaa09ce43e46c5924cc6 | 68,353 |
def CheckProg(context, prog_name):
"""Simple check if a program exists in the path. Returns the path
for the application, or None if not found.
"""
res = SCons.Conftest.CheckProg(context, prog_name)
context.did_show_result = 1
return res | 2b03f98e3cde1ac97c7557f8c1d42ecb1e46b04b | 68,354 |
def encode_apb(dest):
""" https://gpsd.gitlab.io/gpsd/NMEA.html#_apb_autopilot_sentence_b """
nmea = '$OPAPB,'
nmea += 'A,A,' # 1,2 Set to valid
if dest.xte is None:
nmea += ',,,' # 3,4,5 XTE is not valid
else:
dir_to_steer = 'R' if dest.xte > 0 else 'L'
nmea += '{:.3f},{}... | 947cfdc299c2f7214d7953559f8296669e1eac8f | 68,355 |
from typing import Set
def write_itemscheme(obj: model.ItemScheme, locale=DEFAULT_LOCALE):
"""Convert :class:`.ItemScheme`.
Parameters
----------
locale : str, optional
Locale for names to return.
Returns
-------
pandas.Series
"""
items = {}
seen: Set[Item] = set()
... | db0fe86a62218d14ffbe9470cf855175328b6a0d | 68,357 |
def read_nifti(name):
"""Read nifti1 data"""
return nb.nifti1.load(name) | 71bba97760eb5389ad41d7f9bccf9554f17eca73 | 68,358 |
def plot_confusion_matrix(actual: np.ndarray, predictions: np.ndarray, save: str = None, normalize: bool = False,
title: str = "Confusion matrix"):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
Source: http://... | ebfec9aa49681fc2476f322b32bd0467b176e8e9 | 68,359 |
def nurbs_curve2():
""" Creates a 5th order 2D NURBS Curve instance """
# Create a curve instance
curve = NURBS.Curve()
# Set curve degree
curve.degree = 4
# Set weighted control points
curve.ctrlptsw = [[5.0, 5.0, 0.5], [10.0, 10.0, 1.0], [20.0, 15.0, 0.1],
[35.0, 15... | 12494acdc51251042fa0ad29cef98feb764e5e0f | 68,360 |
def get_user_input_environment(env, reparam=False):
"""Validate action input for adversarial environment role.
Args:
env: Multigrid environment object.
reparam: True if this is a reparameterized version of the environment.
Returns:
Integer action.
"""
max_action = env.adversary_action_dim - 1
... | cb8da1704722b3c466f05bcbc82ca31a6472418a | 68,362 |
import struct
def cusparseCreate():
"""
Initialize CUSPARSE.
Initializes CUSPARSE and creates a handle to a structure holding
the CUSPARSE library context.
Returns
-------
handle : int
CUSPARSE library context.
"""
handle = _ffi.new('cusparseHandle_t *')
status = _ff... | 258c6784d326d7bfd654df8f87f000afe83ddf5d | 68,363 |
from bs4 import BeautifulSoup
import re
def clean_review(raw_review):
"""Function to convert raw review from df to words"""
text_nothtml = BeautifulSoup(raw_review).get_text()
text_letters = re.sub("[^a-zA-Z]", " ", text_nothtml)
text_lower = text_letters.lower()
text_tokens = text_lower.split()
... | 02c2902c9f20bab4c861a93842fdddd4c6ce76cc | 68,365 |
def get_capillary_rotation(capillaryImage,zTranslate):
"""
Finds the rotation angle of the capillary with respect to the camera position
**return slope in degrees (rotational angle)
capillaryCoords = 2D array (from get_string_interface_coordinates)
"""
#binarize image of capillary
... | 2efbd72684da6e0277f5fffc2a1b888ac6e071b9 | 68,366 |
def combined_loss(new_params,
log_probab_actions_old,
value_predictions_old,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
gamma... | 5fb55af174a6a03ea18d0b5fcce6e97abc999b9a | 68,367 |
def get_nic_information(idrac_ip):
"""Get nic information"""
data = _make_request(REDFISH_URI.format(idrac_ip) + "/NetworkInterfaces")
network_uri_list = [item['@odata.id'] for item in data["Members"]]
all_nics = []
for item in network_uri_list:
item = item.replace("Interfaces", "Adapters... | 98088d870ca1730b5eace7801bd879d541c6532f | 68,368 |
def shortcdstime2jd(days, milliseconds):
"""
Convert cds time to julian date
"""
offset = days + (milliseconds / 1000.) / (24. * 60. * 60.)
return julian_epoch + offset | 823395c7986b568581cb00b8095056eaa01fdd37 | 68,369 |
from typing import Dict
def _get_claim(context: X12ParserContext) -> Dict:
"""Returns the current claim record for the patient (either subscriber or dependent)"""
if _is_patient_a_dependent(context.patient_record):
claim = context.patient_record[TransactionLoops.CLAIM_INFORMATION][-1]
else:
... | 441b1cebd320ac5e84636fde42ecfd3b177d5309 | 68,370 |
def cloudinary_direct_upload(callback_url, **options):
"""Deprecated - please use cloudinary_direct_upload_field, or a proper form"""
params = utils.build_upload_params(callback=callback_url, **options)
params = utils.sign_request(params, options)
api_url = utils.cloudinary_api_url("upload", resource_t... | de51c4ee5acfcbb38412846d0583113b55b77fcf | 68,371 |
def parse(hdfs_path):
"""
Parse the given path and return its components.
:type hdfs_path: str
:param hdfs_path: an HDFS path, e.g., ``hdfs://localhost:9000/user/me``
:rtype: tuple
:return: scheme, netloc, path
"""
return _HdfsPathSplitter.parse(hdfs_path) | 9aa4e56de6eb2a701fc49025966eac884da234fd | 68,372 |
def Choi_LS_Pauli_mem(k, channel, cycles=1, optimize='optimal', full_output=1):
"""
WITHOUT CONTROL ON RANK
Version where we try to keep memory in check. Main impact from M_k:
needs $24^k$ complex128 entries.
Could be reduced to $16^k$ at the price of many extra calculations.
Yields the le... | f4675a8c4bfb59a845e255b7ab3fb3bf174ce9f7 | 68,373 |
from typing import Union
def digits_sum(n: Union[int, BigInt]) -> int:
"""Get sum of digits in number
Args:
n: Number
Returns:
Sum of digits in number
Examples:
>>> digits_sum(123)
6
>>> digits_sum(BigInt(123456))
21
"""
return sum(get_digits... | 3d422038e68c66602e842eda33c2f71ae396de3b | 68,374 |
def traverse_robustness(claim: dict, discussion: dict, assign_values=True) -> float:
"""Recursive robustness of a claim, based on its weight and the weights of its entire subtree.
Args:
claim (dict): The claim for which to calculate robustness.
discussion (list): The discussion `claim` belo... | 4ea356b268d7155bfb918765ae22957814a8dc39 | 68,375 |
import requests
async def get_or_create_pmid(handler, user, collection_name, pmid, github_token):
""" Get the contents of this PMID file, or create it if it doesn't
exist. """
p = int(pmid)
repo_name = get_repo_name_from_collection(collection_name)
try:
pmid_contents = await handler.github... | 53cf90ed639a3e9266e2c0db5d5a8d91924ac21b | 68,376 |
def plot_raceline(Track_type, class_params: dict, LASTIDX, Car_type, savestr, save_results=False, line_type="EI"):
"""
Args:
Track_type:
class_params:
LASTIDX:
Car_type:
savestr:
save_results:
line_type: the method used to get the raceline (EI, NEI, random)
"""
TRACK_NAME = Track_type.__name__
try... | d1cd1d86edeace388fa36bce0ee3f5df61c2363f | 68,378 |
def create_multiscale_sauvola(window_size_list=[3,5,7,11,15,19],
train_k=False,
train_R=False,
train_alpha=False,
norm_type='bnorm',
base_filters=4,
... | ec6c6d89fb5bcbbc72bc3920ab8e92b19181bed8 | 68,379 |
def manip( at='', path='.', recursive=False, ignore=True, modify=False, prefix='new_', posfix='', log=True ):
"""INSTRUCTIONS
Decorator that transforms an [str] = function( [str]:text, *args, **kwargs ) into an function that apllies itself into a folder.\n
The default values for the new function can be set ... | 1b4331963de371297a395a02724ea381cd8b9bd4 | 68,380 |
def search_results(intent, session):
"""
Search GitHub for the intent's query slot
"""
query = intent['slots']['query']['value']
results = search_repositories(query)
card_title = "Search Results for " + query
if results['items']:
top_repo = results['items'][0]
speech_outp... | 1b7560e5b79c7ab5cb7f1011e5609561a07d2e48 | 68,381 |
def get_linkresolver_url_by_ip(request, citation):
"""
Use the WorldCat registry API to get the appropriate OpenURL resolver for
the user, based on their IP address.
"""
worldcat_registry = "http://www.worldcat.org/registry/lookup?IP={ip}"
worldcat_tag = "{http://worldcatlibraries.org/registry/... | e04e11a2a47810d437591a9550e58d343e5647a9 | 68,383 |
def byte_array_declaration(data: bytes, name: str) -> str:
"""Generates a byte C array declaration for a byte array"""
type_name = '[[maybe_unused]] const std::byte'
byte_str = ''.join([f'std::byte{{0x{b:02x}}},' for b in data])
array_body = f'{{{byte_str}}}'
return f'{type_name} {name}[] = {array_b... | 015f0cb1a4dfd94b6f488b4eae0b58860da4d1dc | 68,385 |
import copy
def assemble_read_pairs(pairs: list, dist: int) -> str:
"""Assemble a string from substrings
:param pairs: a group of substrings pairs
:type pats: list (of tuples (of strs))
:param dist: the distance between the read-pairs
:type dist: int
:returns: the assembled string
:rtype:... | 89913d359a012877fa69d6ad632fdc1de4343fc7 | 68,386 |
import torch
def box_iou(box1, box2):
"""
Return intersection-over-union (Jaccard index) of boxes.
Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
Arguments:
box1 (Tensor[N, 4])
box2 (Tensor[M, 4])
Returns:
iou (Tensor[N, M]): the NxM matrix containing the... | 9913cb2a210802288e711f676cadd8c8d7e89f0a | 68,387 |
def fizzbuzz(node):
""" takes a value and returns fizz is divisible by 3,
buzz if divisible by 5, fizzbuzz if divisble by both,
or just the value if none of the conditions are met """
if node.val % 3 == 0 and node.val % 5 == 0:
node.val = 'fizzbuzz'
return node
elif node.val ... | 8d2125342f0f792d4f6b057c07fa8545f220f254 | 68,388 |
from typing import Tuple
from typing import Any
def loadProperty(xml: ET.Element) -> Tuple[Any, Any]:
"""Load a Qt Property from XML."""
for variant in xml:
return (xml.get("name"), _loadVariant(variant))
raise ValueError("No property in provided XML") | e532800424e17580bb95b221a439b7928439d783 | 68,389 |
import tokenize
def parse(css):
"""Parse a CSS *group of selectors*.
If you don't care about pseudo-elements or selector specificity,
you can skip this and use :meth:`~GenericTranslator.css_to_xpath`.
:param css:
A *group of selectors* as an Unicode string.
:raises:
:class:`Selec... | 8fe9112383ba62fbe3a0a1ba808a55f7d869adb6 | 68,390 |
def svm_train(X, Y, lambda_, lr=1e-3, steps=1000, init_w=None, init_b=0):
"""Train a binary SVM classifier.
Parameters
----------
X : ndarray, shape (m, n)
training features.
Y : ndarray, shape (m,)
binary training labels.
lambda_ : float
regularization coefficient.
... | b633b433e8d53c45d21d19c884e40de6ed1b9212 | 68,392 |
def get_version_string() -> str:
"""Returns version of GDM and of all registered extension packages."""
return " GDM Version: {}. Registered extension packages: {}.".format(
_version.version, extensions.get_registered_package_info()) | 862d0f2437ef6aab376f9d0165414de2414163a3 | 68,394 |
import features
def get_feature_extractors():
""" Return list of feature extractors given in `features.py`
"""
return [getattr(features, x) for x in dir(features)
if isinstance(getattr(features, x), type) and
x != 'BaseFeatureExtractor' and
getattr(features, x).__bases_... | 98a2eb81b98e02218ce83e669cbdf67b11c63227 | 68,395 |
def find_previous_tries_attempts(target_try_attempts):
"""
:param target_try_attempts: An AttemptLog queryset
:type target_try_attempts: django.db.models.QuerySet
:return: A queryset matching previous tries' attempts for each try in `target_try_attempts`
:rtype: django.db.models.QuerySet
"""
... | 7b7bb30632e2f4f54b7d52778efeeb9e760d283c | 68,396 |
import time
import torch
def find_all_boxes(output, conf_thresh, num_classes, anchors, num_anchors, only_objectness=1, validation=False):
""" find boxes from output """
num_classes, num_anchors = int(num_classes), int(num_anchors)
anchor_step = int(len(anchors) / num_anchors)
# output = (bacth, (... | 8791575379c58f01a44fc4ac8b275713154b75c5 | 68,397 |
from datetime import datetime
def encode_jwt(username, domain: str = None):
"""Get JWT encoded token."""
current_time = datetime.datetime.utcnow()
expires_on = current_time + datetime.timedelta(seconds=JWT_EXPIRATION_DELTA)
# Идея хранить в payload user_id признана несостоятельной.
access_token_pa... | 93692ed90318148cb638d4ba7b63cd8723fc1d1c | 68,399 |
def get_tm_team_links(url):
"""Get links for each team from the league page."""
soup = get_soup(url)
table = soup.find_all('table')[3]
links = table.find_all('a', class_='vereinprofil_tooltip')
links = [l['href'] for l in links]
links = list(set(links))
links = [f'https://www.transfermarkt.c... | 9bea824be99cb9a7c49deecb4638fecd5b156597 | 68,400 |
import pytz
from datetime import datetime
def get_now_utc(no_microseconds=True):
"""
This method returns now's datetime object UTC localized.
:param no_microseconds: sets whether microseconds should be cleared.
:return: the just created datetime object with today's date.
"""
if no_microseconds... | 86684073044ac42d60a40c0ec3aa6c944614aefb | 68,402 |
from bs4 import BeautifulSoup
import re
def preproces_text(sentence):
"""
Function that preprocess input sentence: tokenize, lowwer the words and removes speacial characters from each sentence
"""
soup = BeautifulSoup(sentence, "html.parser")
sentence = soup.get_text()
sentence = re.sub("\[[^]... | 2b72809ffe8639bd6b4dbf068e97d3c0fcb64fdb | 68,404 |
import numpy
def CsPadElement(data3d, qn, config):
"""Construct one image for each quadrant, each with 8 sections from
a data3d = 3 x 2*194 x 185 data array. This function was originally
written by Ingrid Ofte for pyana's XtcExplorer module. XXX
Documentation!
"""
# If any sections are missing, insert ... | 088304c77a37855d57a307827f3ed7ff78e73499 | 68,405 |
def to_hcl_map(key: str, config: DictConfig):
""" Helper to return a dictionary of config into a HCL map """
hcl_map = f"{key} = {{\n"
for key, value in config.items():
hcl_map = f'{hcl_map} {key} = "{get_env_var(value)}"\n'
return f"{hcl_map} }}" | 3d55c7cd27ff7be034c6f9e9919761285a309d01 | 68,406 |
def get_shows():
"""
Returns all shows on the minerva DB
"""
# connect to the database
db = connect_minerva_db()
# return all the shows as a list
shows = list(db.shows.find())
return shows | fba3c3db4a9a559169994f2b1aea224945b6bfaf | 68,407 |
def get_risksense_host_finding_context(resp_hostfinding):
"""
Prepare context data for "risksense-get-host-findings" and "risksense-get-host-finding-detail" command.
:param resp_hostfinding: host finding response
:return: list of host finding context
"""
return {
'HostID': resp_hostfind... | 9c454a17956bba5a3c5dfe1ab9f0dd09f841347f | 68,408 |
def comp_stft_average(values):
"""Computes the average of the Short-Time Fourier Transform
Parameters
----------
values: ndarray
ndarray of the field
Returns
-------
Average of the Short-Time Fourier Transform
"""
# To do
nperseg = 3200
noverlap = int(nperseg * 0.75)
... | 7c7bebd992999593b55481e8db0783366fc4a555 | 68,409 |
def register_encryption_handler(instance, **options):
"""
registers a new encryption handler or replaces the existing one
if `replace=True` is provided. otherwise, it raises an error
on adding an instance which it's name is already available
in registered handlers.
:param AbstractEncrypterBase ... | e9a851a0f2c249580a4bde24fb0d29c62d47987d | 68,410 |
def svn_fs_begin_txn(*args):
"""
svn_fs_begin_txn(svn_fs_txn_t txn_p, svn_fs_t fs, svn_revnum_t rev,
apr_pool_t pool) -> svn_error_t
"""
return apply(_fs.svn_fs_begin_txn, args) | 8631f732be827d8c4a481fcd59b14817c6fbd8d6 | 68,412 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.