content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from sklearn import neighbors
def knn_threshold(data, column, threshold=15, k=3):
"""
Cluster rare samples in data[column] with frequency less than
threshold with one of k-nearest clusters
Args:
data - pandas.DataFrame containing colums: latitude, longitude, column
column - the ... | 37de2c0b4c14cdbb6a0dd10ee7ea1e270fe6ef56 | 22,495 |
def format_formula(formula):
"""Converts str of chemical formula into latex format for labelling purposes
Parameters
----------
formula: str
Chemical formula
"""
formatted_formula = ""
number_format = ""
for i, s in enumerate(formula):
if s.isdigit():
if ... | c3c87ffcdc5695b584892c643f02a7959b649935 | 22,497 |
def ParseQuery(query):
"""Parses the entire query.
Arguments:
query: The command the user sent that needs to be parsed.
Returns:
Dictionary mapping clause names to their arguments.
Raises:
bigquery_client.BigqueryInvalidQueryError: When invalid query is given.
"""
clause_arguments = {
'... | b3348b10ec7aeb57916366b96409666b71c9a9ce | 22,498 |
def primary_astigmatism_00(rho, phi):
"""Zernike primary astigmatism 0°."""
return rho**2 * e.cos(2 * phi) | 031bb068b4384dc2cd15bebf3450faa25e0177bc | 22,499 |
def lpt_prototype(mesh,
nc=FLAGS.nc,
bs=FLAGS.box_size,
batch_size=FLAGS.batch_size,
a0=FLAGS.a0,
a=FLAGS.af,
nsteps=FLAGS.nsteps):
"""
Prototype of function computing LPT deplacement.
Returns output t... | ab9dfc52ddc26a62f9c9bc0b62dec044d0262d79 | 22,500 |
def in_collision(box1: OrientedBox, box2: OrientedBox) -> bool:
"""
Check for collision between two boxes. First do a quick check by approximating each box with a circle,
if there is an overlap, check for the exact intersection using geometry Polygon
:param box1: Oriented box (e.g., of ego)
:param b... | 290c7de8b73ff31349ec020eb745209a28cdb460 | 22,501 |
def process_embedded_query_expr(input_string):
"""
This function scans through the given script and identify any path/metadata
expressions. For each expression found, an unique python variable name will
be generated. The expression is then substituted by the variable name.
:param str input_string: ... | 013c37c9fb63a447ac844d94c2a08f8b53fd759b | 22,502 |
def format_elemwise(vars_):
"""Formats all the elementwise cones for the solver.
Parameters
----------
vars_ : list
A list of the LinOp expressions in the elementwise cones.
Returns
-------
list
A list of LinLeqConstr that represent all the elementwise cones.
"""
# ... | 36cf91dc01549c4a2a01b4d301d387f002f8eee1 | 22,503 |
def extract_stars(image, noise_threshold):
"""
Extract all star from the given image
Returns a list of rectangular images
"""
roi_list = []
image_list = []
# Threshold to remove background noise
image = image.copy()
image[image < noise_threshold] = 0.0
# Create binary image by... | 3b252525d14a875ba96e66edead179096e62b1af | 22,504 |
import torch
def lovasz_hinge(logits, labels):
"""
Binary Lovasz hinge loss
logits: [P] Variable, logits at each prediction (between -\infty and +\infty)
labels: [P] Tensor, binary ground truth labels (0 or 1)
"""
if len(labels) == 0:
# only void pixels, the gradients should be... | 07eae3d43fda67cb2c195c6f8f72774d99f3195d | 22,505 |
from bs4 import BeautifulSoup
def extract_metadata(url: str, body: BeautifulSoup) -> Website:
"""
Extract metadata from a site and put it into a `Website object`.
"""
try:
name = body.title.get_text().strip()
except AttributeError:
name = url
try:
description = (
... | 534ee50ee2a8daa39730f795cd4bfb16c1dacc1e | 22,506 |
def markContinuing(key, idea, oldest_idea_id, oldest_idea_detect_time, accum):
"""
Mark IDEA as continuing event.
:return: marked key, IDEA
"""
# If idea is present
if idea:
# Equality of ID's in tuple and idea, if true mark will be added
if oldest_idea_id != idea.id:
... | 3f83283f284693b0d0fdee7129fe0fa51b2a9174 | 22,507 |
import torch
def box1_in_box2(corners1:torch.Tensor, corners2:torch.Tensor):
"""check if corners of box1 lie in box2
Convention: if a corner is exactly on the edge of the other box, it's also a valid point
Args:
corners1 (torch.Tensor): (B, N, 4, 2)
corners2 (torch.Tensor): (B, N, 4, 2)
... | f7c5e442aadfadd15dcfdd32c3358f784ac418bc | 22,508 |
def in_line_rate(line, container_line):
"""一个线段和另一个线段的重合部分,占该线段总长的占比"""
inter = intersection_line(line, container_line)
return inter / (line[1] - line[0]) | 3f56b05c0bbe42030c1fd6f684724c2afc922135 | 22,509 |
def test_cli_requires():
"""Test to ensure your can add requirements to a CLI"""
def requires_fail(**kwargs):
return {'requirements': 'not met'}
@hug.cli(output=str, requires=requires_fail)
def cli_command(name: str, value: int):
return (name, value)
assert cli_command('Testing', 1... | 2febbfa4ed51a22e057494dfaeb45c99400b72d4 | 22,510 |
def comm_for_pid(pid):
"""Retrieve the process name for a given process id."""
try:
return slurp('/proc/%d/comm' % pid)
except IOError:
return None | 49aa200986f3fcafd053e5708a08a4ff5873b40e | 22,511 |
def get_machine_type_from_run_num(run_num):
"""these are the values to be used in config for machine dependent settings"""
id_to_machine = {
'MS001': 'miseq',
'NS001': 'nextseq',
'HS001': 'hiseq 2500 rapid',
'HS002': 'hiseq 2500',
'HS003': 'hiseq 2500',
'HS004': '... | 117b5cb1646a0295be28f5875c3cd9d9c09c67ea | 22,512 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username"... | 4ef618ea5028fca74664ef7cfdd8de9dae6de007 | 22,514 |
def twisted_sleep(time):
"""
Return a deferred that will be triggered after the specified amount of
time passes
"""
return task.deferLater(reactor, time, lambda: None) | f26cdbc7c8af8f19658241ae01465c418253f040 | 22,515 |
import pickle
async def async_load_cache(
filename: str,
) -> dict[str, str | dict[str, dict[str, dict[str, dict[str, str]]]]]:
"""Load cache from file."""
async with aiofiles.open(filename, "rb") as file:
pickled_foo = await file.read()
return pickle.loads(pickled_foo) | 4b64e9f70d1dfd0627625edb69e80a166ebdeeb1 | 22,517 |
import six
def make_function(function, name, arity):
"""Make a function node, a representation of a mathematical relationship.
This factory function creates a function node, one of the core nodes in any
program. The resulting object is able to be called with NumPy vectorized
arguments and return a re... | 460d453888e025832983e7a822d3dfd498f0d176 | 22,518 |
def data_type_validator(type_name='data type'):
"""
Makes sure that the field refers to a valid data type, whether complex or primitive.
Used with the :func:`field_validator` decorator for the ``type`` fields in
:class:`PropertyDefinition`, :class:`AttributeDefinition`, :class:`ParameterDefinition`,
... | d949eddfcfbe941e6ee74127761336fbc1e006db | 22,519 |
def list_challenge_topics(account_name, challenge_name): # noqa: E501
"""List stargazers
Lists the challenge topics. # noqa: E501
:param account_name: The name of the account that owns the challenge
:type account_name: str
:param challenge_name: The name of the challenge
:type challenge_name:... | 24daefe48f62c649ee31f362c418eb62f0dd6c33 | 22,520 |
import copy
def ee_reg2(x_des, quat_des, sim, ee_index, kp=None, kv=None, ndof=12):
"""
same as ee_regulation, but now also accepting quat_des.
"""
kp = np.eye(len(sim.data.body_xpos[ee_index]))*10 if kp is None else kp
kv = np.eye(len(sim.data.body_xpos[ee_index]))*1 if kv is None else kv
jacp,jacr=jac(sim, e... | 23a0f818c57cf0760eff4f74ec7b94bd337e14ab | 22,521 |
def _default_clipping(
inner_factory: factory.AggregationFactory) -> factory.AggregationFactory:
"""The default adaptive clipping wrapper."""
# Adapts relatively quickly to a moderately high norm.
clipping_norm = quantile_estimation.PrivateQuantileEstimationProcess.no_noise(
initial_estimate=1.0, targe... | c39c143bebe78bec0bcd7b8d9f3457a04ac7b5a4 | 22,522 |
import torch
def make_pred_multilabel(data_transforms, model, PATH_TO_IMAGES, epoch_loss, CHROMOSOME):
"""
Gives predictions for test fold and calculates AUCs using previously trained model
Args:
data_transforms: torchvision transforms to preprocess raw images; same as validation transforms
... | 42fb9446df2e0a8cc5d408957db21622bd5bb96e | 22,523 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up a config entry for solarlog."""
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, "sensor")
)
return True | 2cb14b9a71b16409aa9030acafd8c677efe1e22a | 22,524 |
def SqueezeNet_v1(include_top=True,
input_tensor=None, input_shape=None,
classes=10):
"""Instantiates the SqueezeNet architecture.
"""
input_shape = _obtain_input_shape(input_shape,
default_size=32,
... | b31f613a63836e88bf04c0b38240ce256cf9b2ae | 22,525 |
def xcafdoc_ColorRefGUID(*args):
"""
* Return GUIDs for TreeNode representing specified types of colors
:param type:
:type type: XCAFDoc_ColorType
:rtype: Standard_GUID
"""
return _XCAFDoc.xcafdoc_ColorRefGUID(*args) | b5d300d656977402d95c0227462e8da6224a3eff | 22,526 |
import code
def green_on_yellow(string, *funcs, **additional):
"""Text color - green on background color - yellow. (see _combine())."""
return _combine(string, code.GREEN, *funcs, attributes=(code.BG_YELLOW,)) | 90b2ae25b1e58da8b3a7a1d3b76468cfade3887a | 22,527 |
def _register_models(format_str, cls, forward=True):
"""Registers reward models of type cls under key formatted by format_str."""
forwards = {"Forward": {"forward": forward}, "Backward": {"forward": not forward}}
control = {"WithCtrl": {}, "NoCtrl": {"ctrl_coef": 0.0}}
res = {}
for k1, cfg1 in forw... | 96c95d83841b381777ce817e401cc6c7e8a5dc1d | 22,528 |
def configure_pseudolabeler(pseudolabel: bool, pseudolabeler_builder, pseudolabeler_builder_args):
"""Pass in a class that can build a pseudolabeler (implementing __call__) or a builder function
that returns a pseudolabeling function.
"""
if pseudolabel:
return globals()[pseudolabeler_builder](*... | 3e31869542a977cc4b72267b348f7e087ccb2aee | 22,529 |
def flip_dict(dict, unique_items=False, force_list_values=False):
"""Swap keys and values in a dictionary
Parameters
----------
dict: dictionary
dictionary object to flip
unique_items: bool
whether to assume that all items in dict are unique, potential speedup but repeated items wil... | c8344852bc76321f80b4228671707ef7b48e4f71 | 22,531 |
def randn(N, R, var = 1.0, dtype = tn.float64, device = None):
"""
A torchtt.TT tensor of shape N = [N1 x ... x Nd] and rank R is returned.
The entries of the fuill tensor are alomst normal distributed with the variance var.
Args:
N (list[int]): the shape.
R (list[int]): the rank.
... | a88dc6a6602adf16617086d35ae43ed6f1eff796 | 22,532 |
def flatten_all_dimensions_but_first(a):
"""
Flattens all dimensions but the first of a multidimensional array.
Parameters
----------
a : ndarray
Array to be flattened.
Returns
-------
b : ndarray
Result of flattening, two-dimensional.
"""
s = a.shape
s_fla... | 80c150e81cd03f6195234da2419ee78c6bee1e54 | 22,533 |
def getHRLanguages(fname, hrthreshold=0):
"""
:param fname: the name of the file containing filesizes. Created using wc -l in the wikidata folder
:param hrthreshold: how big a set of transliteration pairs needs to be considered high resource
:return: a list of language names (in ISO 639-3 format?)
"... | 184f91f40aba76c6ebdcd553c0054b4b1a73da5d | 22,534 |
def _wrap(func, *args, **kwargs):
"""To do."""
def _convert(func_, obj):
try:
return func_(obj)
except BaseException:
return obj
# First, decode each arguments
args_ = [_convert(decode, x) for x in args]
kwargs_ = {k: _convert(decode, v) for k, v in kwargs.i... | d3b951c664a098f6ce3d0c024cb2ae92b2fa9314 | 22,535 |
import itertools
def make_id_graph(xml):
"""
Make an undirected graph with CPHD identifiers as nodes and edges from correspondence and hierarchy.
Nodes are named as {xml_path}<{id}, e.g. /Data/Channel/Identifier<Ch1
There is a single "Data" node formed from the Data branch root that signifies data th... | d83bf22f76393d1213b469ebd53d93dca30e9d90 | 22,536 |
import base64
def aes_base64_encrypt(data, key):
"""
@summary:
1. pkcs7padding
2. aes encrypt
3. base64 encrypt
@return:
string
"""
cipher = AES.new(key)
return base64.b64encode(cipher.encrypt(_pkcs7padding(data))) | 7f32b4a3848a4084ebd90c5a941c35e19d57d0ec | 22,537 |
def mast_query_darks(instrument, aperture, start_date, end_date):
"""Use ``astroquery`` to search MAST for dark current data
Parameters
----------
instrument : str
Instrument name (e.g. ``nircam``)
aperture : str
Detector aperture to search for (e.g. ``NRCA1_FULL``)
start_date... | f612068ff220cf02cf6582478d257ff842f72eef | 22,540 |
import random
def randomNumGen(choice):
"""Get a random number to simulate a d6, d10, or d100 roll."""
if choice == 1: #d6 roll
die = random.randint(1, 6)
elif choice == 2: #d10 roll
die = random.randint(1, 10)
elif choice == 3: #d100 roll
die = random.randint(1, 100)
el... | 307194d60a79ee2b101f7743002a380848e68628 | 22,541 |
def is_distinct(coll, key=EMPTY):
"""Checks if all elements in the collection are different."""
if key is EMPTY:
return len(coll) == len(set(coll))
else:
return len(coll) == len(set(xmap(key, coll))) | 94469c2915e5164238999f1d98c850856034652e | 22,543 |
def split_data(df_data, config, test_frac=0.2):
"""
split df_data to train and test.
"""
df_train, df_test = train_test_split(df_data, test_size=test_frac)
df_train.reset_index(inplace=True, drop=True)
df_test.reset_index(inplace=True, drop=True)
df_train.to_csv(config.path_train_data, index... | 6b9b9301d15e29562933164343d894880641aed8 | 22,544 |
import requests
def query(params, lang='en'):
"""
Simple Mediawiki API wrapper
"""
url = 'https://%s.wikipedia.org/w/api.php' % lang
finalparams = {
'action': 'query',
'format': 'json',
}
finalparams.update(params)
resp = requests.get(url, params=finalparams)
if ... | 990ca6aae015e3106920ce67eb4e29f39e8a8f4c | 22,545 |
from datetime import datetime
import time
def reporting_window(year, month):
"""
Returns the range of time when people are supposed to report
"""
last_of_last_month = datetime(year, month, 1) - timedelta(days=1)
last_bd_of_last_month = datetime.combine(
get_business_day_of_month(last_of_la... | 89f1c6f42257068c9483cc9870e0774fab262b13 | 22,546 |
def fit_cluster_13():
"""Fit a GMM to resolve objects in cluster 13 into C, Q, O.
Returns
-------
sklearn.mixture.GaussianMixture
The mixture model trained on the latent scores.
list
The classes represented in order by the model components.
"""
data = classy.data.load()
... | 5e242716633a759b2dcdbcbd68cbd441c7c0281e | 22,548 |
def sidebar_left(request):
"""
Return the left sidebar values in context
"""
if request.user.is_authenticated():
moderation_obj = {
'is_visible': False,
'count_notifs': 0,
}
if request.user.is_staff:
moderation_obj['is_visible'] = True
... | 161a0bdc872f8dfff9e57156e58685cb600d2be4 | 22,549 |
import torch
def get_edge_lengths(vertices, edge_points):
"""
get edge squared length using edge_points from get_edge_points(mesh) or edge_vertex_indices(faces)
:params
vertices (N,3)
edge_points (E,4)
"""
N, D = vertices.shape
E = edge_points.shape[0]
# E,2,D (O... | 396d7d669d96611fb65c20b99347ab8041ff3f5a | 22,550 |
def compute_pca(nparray):
"""
:param nparray: nxd array, d is the dimension
:return: evs eigenvalues, axmat dxn array, each column is an eigenvector
author: weiwei
date: 20200701osaka
"""
ca = np.cov(nparray, y=None, rowvar=False, bias=True) # rowvar row=point, bias biased covariance
pc... | 0aa1d731c0d296cc66a9275e466e4ce3d57a8621 | 22,551 |
def fac(num):
"""求阶乘"""
assert num >= 0
if num in (0, 1):
return 1
return num * fac(num - 1) | e043e03e1d528dd9ec5685c4483e70217c948a0b | 22,552 |
def entropy(logp, p):
"""Compute the entropy of `p` - probability density function approximation.
We need this in order to compute the entropy-bonus.
"""
H = -(logp * p).sum(dim=1).mean()
return H | dff7c89979e5a9cef65088fd9f8858bb66bf218f | 22,553 |
def find(query):
"""Retrieve *exactly* matching tracks."""
args = _parse_query(query)
return mpctracks('find', args) | 656b2f7dfc4642cbe5294a888f5c4873e905140a | 22,554 |
import random
def permuteregulations(graph):
"""Randomly change which regulations are repressions, maintaining activation and repression counts and directions."""
edges = list(graph.edges)
copy = graph.copy()
repressions = 0
for edge in edges:
edge_data = copy.edges[edge]
if edge_d... | 76a12e573a6d053442c86bc81bebf10683d55dfb | 22,555 |
def editor_command(command):
"""
Is this an external editor command?
:param command: string
"""
# It is possible to have `\e filename` or `SELECT * FROM \e`. So we check
# for both conditions.
return command.strip().endswith('\\e') or command.strip().startswith('\\e ') | 0e80547b3c118bf01bd7a69e2d93fe8f65851ecf | 22,556 |
def blrObjFunction(initialWeights, *args):
"""
blrObjFunction computes 2-class Logistic Regression error function and
its gradient.
Input:
initialWeights: the weight vector (w_k) of size (D + 1) x 1
train_data: the data matrix of size N x D
labeli: the label vector (y_k) of siz... | 3192982a54163868deffa9dfcce2a6f828b67abd | 22,557 |
from datetime import datetime
def edit_battle(battle_id):
"""
Edit battle form.
:param battle_id:
:return:
"""
battle = Battle.query.get(battle_id) or abort(404)
if battle.clan != g.player.clan and g.player.name not in config.ADMINS:
abort(403)
all_players = Player.query.f... | 839a134441af0429ce141218931faef1d53f9938 | 22,558 |
def construct_epsilon_heli(epsilon_diag,
pitch,
divisions,
thickness,
handness="left"):
"""
construct the dielectric matrices of all layers
return a N*3*3 array where N is the number of layers
We ... | 3be04a06524c6011180584f39dea7651d43b5b46 | 22,559 |
def image_overlay(im_1, im_2, color=True, normalize=True):
"""Overlay two images with the same size.
Args:
im_1 (np.ndarray): image arrary
im_2 (np.ndarray): image arrary
color (bool): Whether convert intensity image to color image.
normalize (bool): If both color and normalize ... | 501a1465147e8b63c1a36c0cd7f2a1850f7a14b9 | 22,561 |
def get_next_seg(ea):
"""
Get next segment
@param ea: linear address
@return: start of the next segment
BADADDR - no next segment
"""
nextseg = ida_segment.get_next_seg(ea)
if not nextseg:
return BADADDR
else:
return nextseg.start_ea | 5ea0bf1ef889bad4013a86df237cca39a4934c4c | 22,563 |
from invenio_app_ils.items.api import ITEM_PID_TYPE
def validate_item_pid(item_pid):
"""Validate item or raise and return an obj to easily distinguish them."""
if item_pid["type"] not in [BORROWING_REQUEST_PID_TYPE, ITEM_PID_TYPE]:
raise UnknownItemPidTypeError(pid_type=item_pid["type"])
# inlin... | f1e5c59e43787a736cb99c51a74e562f6a1c636f | 22,564 |
import _ctypes
def save_as_png(prs: pptx.presentation.Presentation, save_folder: str, overwrite: bool = False) -> bool:
"""
Save presentation as PDF.
Requires to save a temporary *.pptx first.
Needs module comtypes (windows only).
Needs installed PowerPoint.
Note: you have to give full path fo... | bf982eb1b5395e4602f00859c73a1924fca638b9 | 22,566 |
import json
def http_post(request):
"""HTTP Cloud Function.
Args:
request (flask.Request): The request object.
<https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>
Returns:
The response text, or any set of values that can be turned into a
Response object ... | dd82b624a3d2cf37c1cb2538cdc8d26447f3e029 | 22,567 |
def create_incident_field_context(incident):
"""Parses the 'incident_fields' entry of the incident and returns it
Args:
incident (dict): The incident to parse
Returns:
list. The parsed incident fields list
"""
incident_field_values = dict()
for incident_field in incident.get('i... | 1a56c5b76c4c82827f8b7febde30e2881e6f0561 | 22,569 |
def create_profile(body, user_id): # noqa: E501
"""Create a user profile
# noqa: E501
:param body:
:type body: dict | bytes
:param user_id: The id of the user to update
:type user_id: int
:rtype: None
"""
if connexion.request.is_json:
json = connexion.request.get_json()
... | ff00d3a65f0e10ec3f90d0b1139033cf004d560a | 22,570 |
def load_global_recovered() -> pd.DataFrame:
"""Loads time series data for global COVID-19 recovered cases
Returns:
pd.DataFrame: A pandas dataframe with time series data for global COVID-19 recovered cases
"""
return load_csv(global_recovered_cases_location) | bb7702d3cd597dbc12314804d0d0a09f4c28d72c | 22,571 |
import urllib
def build_url(self, endpoint):
"""
Builds a URL given an endpoint
Args:
endpoint (Endpoint: str): The endpoint to build the URL for
Returns:
str: The URL to access the given API endpoint
"""
return urllib.parse.urljoin(self.base_url, endpoint) | e31bead2e87cea82c237df06bf00085dc8a3c04d | 22,572 |
def neighbors(i, diag = True,inc_self=False):
"""
determine the neighbors, returns a set with neighboring tuples {(0,1)}
if inc_self: returns self in results
if diag: return diagonal moves as well
"""
r = [1,0,-1]
c = [1,-1,0]
if diag:
if inc_self:
return {(i[0]+d... | 3d4ca12795fa1d3d7e7f8f231cdf0f12257da7e0 | 22,573 |
import torch
def gumbel_softmax(logits, tau=1, hard=False, eps=1e-10):
"""
NOTE: Stolen from https://github.com/pytorch/pytorch/pull/3341/commits/327fcfed4c44c62b208f750058d14d4dc1b9a9d3
Sample from the Gumbel-Softmax distribution and optionally discretize.
Args:
logits: [batch_size, n_class] un... | 3d512e47771ecac396e757e4b7b8db9030b89f46 | 22,575 |
from typing import List
import re
def decompose_f_string(f_string: str) -> (List[str], List[str]):
"""
Decompose an f-string into the list of variable names and the separators between them.
An f-string is any string that contains enclosed curly brackets around text.
A variable is defined as the text ... | c463c8189539fd0c2c14e2c5620cafc9820c0f41 | 22,576 |
def process(register, instructions):
"""Process instructions on copy of register."""
cur_register = register.copy()
cur_index = 0
while cur_index < len(instructions):
cur_instruction = instructions[cur_index]
cur_index += process_instruction(cur_register, cur_instruction)
return cur_... | 5a204828261d8408467d9b17976728780db76d1d | 22,577 |
def bearing_radians(lat1, lon1, lat2, lon2):
"""Initial bearing"""
dlon = lon2 - lon1
y = sin(dlon) * cos(lat2)
x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon)
return atan2(y, x) | 613a5496b58e09a1b79c0576e90ff2b6f49df31d | 22,578 |
import logging
import json
def RunSimulatedStreaming(vm):
"""Spawn fio to simulate streaming and gather the results.
Args:
vm: The vm that synthetic_storage_workloads_benchmark will be run upon.
Returns:
A list of sample.Sample objects
"""
test_size = min(vm.total_memory_kb / 10, 1000000)
iodepth... | 417898b96223eb28d1d999adaad137c2e9d9e30c | 22,579 |
def get_all_tutorial_info():
"""
Tutorial route to get tutorials with steps
Parameters
----------
None
Returns
-------
Tutorials with steps
"""
sql_query = "SELECT * FROM diyup.tutorials"
cur = mysql.connection.cursor()
cur.execute(sql_query)
tutorials = cur.fetcha... | 2565427a617ce042af9165963f7676877c97dd16 | 22,581 |
from datetime import datetime
def parse_date(datestring, default_timezone=UTC):
"""Parses ISO 8601 dates into datetime objects
The timezone is parsed from the date string. However it is quite common to
have dates without a timezone (not strictly correct). In this case the
default timezone specified i... | 41058b1a825a9c0ee133327001ada1834c3c1732 | 22,582 |
def BigSpectrum_to_H2COdict(sp, vrange=None):
"""
A rather complicated way to make the spdicts above given a spectrum...
"""
spdict = {}
for linename,freq in pyspeckit.spectrum.models.formaldehyde.central_freq_dict.iteritems():
if vrange is not None:
freq_test_low = freq - freq... | 961e4dd676332efea084fd87d9108337ce56fbe2 | 22,583 |
def get_thickness_model(model):
"""
Return a function calculating an adsorbate thickness.
The ``model`` parameter is a string which names the thickness equation which
should be used. Alternatively, a user can implement their own thickness model, either
as an experimental isotherm or a function whic... | 1573206c331cbb4f770ed21cea88f73d13fea385 | 22,584 |
import aiohttp
def http(session: aiohttp.ClientSession) -> Handler:
"""`aiohttp` based request handler.
:param session:
"""
async def handler(request: Request) -> Response:
async with session.request(
request.method,
request.url,
params=request.params or No... | 2628774af37c44a42c74ab8844b2f5d37200eaa9 | 22,585 |
def remove_package_repo_and_wait(repo_name, wait_for_package):
""" Remove a repository from the list of package sources, then wait for the removal to complete
:param repo_name: name of the repository to remove
:type repo_name: str
:param wait_for_package: the package whose version should ch... | 14b8d261c58ba07d12fd9737392858a541b8deb1 | 22,586 |
from typing import Callable
from typing import List
def lyndon_of_word(word : str, comp: Callable[[List[str]],str] = min ) -> str:
"""
Returns the Lyndon representative among set of circular shifts,
that is the minimum for th lexicographic order 'L'<'R'
:code:`lyndon_of_word('RLR')`.
Args:
... | c4195244488de555871e02260c733a28a882481a | 22,587 |
def num_of_visited_nodes(driver_matrix):
""" Calculate the total number of visited nodes for multiple paths.
Args:
driver_matrix (list of lists): A list whose members are lists that
contain paths that are represented by consecutively visited nodes.
Returns:
int: Number of visited no... | 2a1244cd033029cec4e4f7322b9a27d01ba4abd5 | 22,588 |
def gen_custom_item_windows_file(description, info, value_type, value_data,
regex, expect):
"""Generates a custom item stanza for windows file contents audit
Args:
description: string, a description of the audit
info: string, info about the audit
value_type: string, "POLICY_TEXT" -- included for p... | 3d0335d91eb700d30d5ae314fce13fc4a687d766 | 22,589 |
import inspect
def create_signature(args=None, kwargs=None):
"""Create a inspect.Signature object based on args and kwargs.
Args:
args (list or None): The names of positional or keyword arguments.
kwargs (list or None): The keyword only arguments.
Returns:
inspect.Signature
... | 011acccada7896e11e2d9bb73dcf03d7dc6e751e | 22,590 |
import json
def select(type, name, optional):
"""Select data from data.json file"""
with open('data.json', 'r') as f:
data = json.load(f)
for i in data[type]:
if i == data[name]:
return data[optional] | f784137127cd77af2db6e4ac653dc360515ec056 | 22,591 |
def perform_step(polymer: str, rules: dict) -> str:
"""
Performs a single step of polymerization by performing all applicable insertions; returns new polymer template string
"""
new = [polymer[i] + rules[polymer[i:i+2]] for i in range(len(polymer)-1)]
new.append(polymer[-1])
return "".join(... | c60f760ef6638ff3a221aff4a56dccbeae394709 | 22,592 |
import json
def load_datasets(json_file):
"""load dataset described in JSON file"""
datasets = {}
with open(json_file, 'r') as fd:
config = json.load(fd)
all_set_path = config["Path"]
for name, value in config["Dataset"].items():
assert isinstance(value, dict)
... | d34d3e79582db9f0682909a88d697edbf0ef75e3 | 22,593 |
def instantiate_descriptor(**field_data):
"""
Instantiate descriptor with most properties.
"""
system = get_test_descriptor_system()
course_key = CourseLocator('org', 'course', 'run')
usage_key = course_key.make_usage_key('html', 'SampleHtml')
return system.construct_xblock_from_class(
... | 6a640d1d66818898951298750a819d12e24c74e9 | 22,594 |
import time
def simple_switch(M_in, P_in, slack=1, animate=True, cont=False, gen_pos=None, verbose=True):
"""
A simple switch algorithm. When encountering a change in sequence, compare the value
of the switch to the value of the current state, switch if it's more. The default value
function sum(exp(length(ad... | 709f3eeab1fe498cb0a5b9a765c44d427a03b4c4 | 22,595 |
def drop_duplicates_by_type_or_node(n_df, n1, n2, typ):
"""
Drop the duplicates in the network, by type or by node.
For each set of "duplicate" edges, only the edge with the maximum weight
will be kept.
By type, the duplicates are where nd1, nd2, and typ are identical; by node,
the duplicates ... | 015679f5a2625792ef57b49994408746440ce15c | 22,596 |
def voting(labels):
""" Majority voting. """
return sitk.LabelVoting(labels, 0) | 52fa5c2cfbe3551a676904ea1c2f3c6514833ba7 | 22,597 |
def user_city_country(obj):
"""Get the location (city, country) of the user
Args:
obj (object): The user profile
Returns:
str: The city and country of user (if exist)
"""
location = list()
if obj.city:
location.append(obj.city)
if obj.country:
location.appe... | be4238246042371215debb608934b89b63a07dab | 22,598 |
def test_encrypted_parquet_write_kms_error(tempdir, data_table,
basic_encryption_config):
"""Write an encrypted parquet, but raise KeyError in KmsClient."""
path = tempdir / 'encrypted_table_kms_error.in_mem.parquet'
encryption_config = basic_encryption_config
... | aeeffecf5ca38907506ce79b96c823652cd3ef99 | 22,599 |
import codecs
async def putStorBytes(app, key, data, filter_ops=None, bucket=None):
""" Store byte string as S3 object with given key
"""
client = _getStorageClient(app)
if not bucket:
bucket = app['bucket_name']
if key[0] == '/':
key = key[1:] # no leading slash
shuffle = -1... | f58ff0c9073e2ce7dce19b2c586abc14af792590 | 22,600 |
def unique_boxes(boxes, scale=1.0):
"""Return indices of unique boxes."""
assert boxes.shape[1] == 4, 'Func doesnot support tubes yet'
v = np.array([1, 1e3, 1e6, 1e9])
hashes = np.round(boxes * scale).dot(v)
_, index = np.unique(hashes, return_index=True)
return np.sort(index) | 951f0b6f0d51212ad63e787a32c78d14f7e11bd1 | 22,602 |
def dataloader(loader, mode):
"""Sets batchsize and repeat for the train, valid, and test iterators.
Args:
loader: tfds.load instance, a train, valid, or test iterator.
mode: string, set to 'train' for use during training;
set to anything else for use during validation/test
Returns:
An itera... | b15b736919c21df142e2d4815f33b24dc0f01e5f | 22,603 |
def sub_inplace(X, varX, Y, varY):
"""In-place subtraction with error propagation"""
# Z = X - Y
# varZ = varX + varY
X -= Y
varX += varY
return X, varX | 646578886c37003eb860134b93db95e6b4d73ed7 | 22,604 |
def inv_logtransform(plog):
""" Transform the power spectrum for the log field to the power spectrum of delta.
Inputs
------
plog - power spectrum of log field computed at points on a Fourier grid
Outputs
-------
p - power spectrum of the delta field
"""
xi_log = np.fft.ifftn(plo... | aaf414796e5dfd5ede71dd8e18017f46b7761a39 | 22,605 |
import builtins
def ipv6_b85decode(encoded,
_base85_ords=RFC1924_ORDS):
"""Decodes an RFC1924 Base-85 encoded string to its 128-bit unsigned integral
representation. Used to base85-decode IPv6 addresses or 128-bit chunks.
Whitespace is ignored. Raises an ``OverflowError`` if stray characters... | 324ec9835c7228bf406a8b33450c530b7191c4a0 | 22,606 |
def relabel_sig(sig:BaseSignature, arg_map:TDict[str, str]=None,
new_vararg:str=None, kwarg_map:TDict[str, str]=None,
new_varkwarg:str=None,
output_map:TDict[str, str]=None) -> BaseSigMap:
"""
Given maps along which to rename signature elements, generate a new
... | a6b7ab1f8e8d3104938a6b1cecc609fb8a3aa1a0 | 22,607 |
import functools
def inferred_batch_shape_tensor(batch_object,
bijector_x_event_ndims=None,
**parameter_kwargs):
"""Infers an object's batch shape from its parameters.
Each parameter contributes a batch shape of
`base_shape(parameter)[:-event_ndi... | d3c3a40f36c66ef28f6aeaddbdaa7dff5729f1ed | 22,608 |
from datetime import datetime
def fsevent_log(self, event_id_status_message):
"""Amend filesystem event history with a logging message
"""
event_id = event_id_status_message[0]
status = event_id_status_message[1]
message = event_id_status_message[2]
dbc = db_collection()
history_entry = {
... | 64cd88762e2775172bcf4c894c5187c373db3ee8 | 22,609 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.