content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_fully_qualified_class_name(cls):
"""Returns fully dot-qualified path of a class, e.g. `ludwig.models.trainer.TrainerConfig` given
`TrainerConfig`."""
return ".".join([cls.__module__, cls.__name__]) | dc3cbbb8be4503b562a381aa45842399a623971e | 44,555 |
from typing import Union
def convert_bytes(bytes: int, unit: str = "Mi") -> Union[str, int]:
"""Converts a number of bytes to a string representation.
By default, the output is in MiB('Mi') format.
If unit is 'b', the output would be an integer value.
(e.g., convert_bytes(1024, 'b') -> 1024)
Onl... | dc38268c668e1b49718f167b5fc2767613d055b1 | 44,558 |
def global_settings(request):
"""
Expose various settings
"""
return {
'global_settings': {
'google_analytics_tracking_id': settings.GOOGLE_ANALYTICS_TRACKING_ID,
'IMIS_SSO_LOGIN_URL': settings.IMIS_SSO_LOGIN_URL,
'HELIX_LOGOUT_URL': settings.HELIX_LOGOUT_URL
... | 0f83b5000a8946d46fba244bdc67b5f2141ee0dc | 44,559 |
def index():
"""
The landing page of the site
:return: Returns a rendering of the landing page.
"""
form = Transaction(request.form)
return render_template("transaction.html", form=form) | e85ff39e1525b303604c815eea6b33d69290ac35 | 44,560 |
def determine_flow_unit(stock_unit: str, time_unit: str = "h"):
"""For example:
>>> determine_flow_unit("m³") # m³/h
>>> determine_flow_unit("kWh") # kW
"""
flow = to_preferred(ur.Quantity(stock_unit) / ur.Quantity(time_unit))
return "{:~P}".format(flow.units) | b359cba095f94101ac5c9ef1d6815897db33cff9 | 44,561 |
from typing import List
def handle_hosts(
actapi: act.api.Act, content: Text, hosts: List[Text]
) -> List[act.api.fact.Fact]:
"""handle the hosts part of a hybrid-analysis report"""
feeds_facts: List[act.api.fact.Fact] = []
for host in hosts:
(ip_type, ip) = act.api.helpers.ip_obj(host)
... | 14aee6fbe5eb2d51c8ae2349648f6f32573030e7 | 44,562 |
def parsevROps(payload, alert):
"""
Parse vROps JSON from alert webhook.
Returns a dict.
"""
if (not 'alertId' in payload):
return alert
alert.update({
"hookName": "vRealize Operations Manager",
"AlertName": payload['alertName'] if ('alertName' in payload and payloa... | 8149dd87f26c0767692dcd79ab88a36e1f2e328b | 44,563 |
def as_chunks(l, num):
"""
:param list l:
:param int num: Size of split
:return: Split list
:rtype: list
"""
chunks = []
for i in range(0, len(l), num):
chunks.append(l[i:i + num])
return chunks | 6bf6a2efed8e4830447319dd1624e70463faaf41 | 44,564 |
def extract_average_values_roc(nb_random_realizations, fpr_list, tpr_list, auc_values):
"""This function extracts the average values for the ROC curve across the random realizations
Args:
nb_random_realizations (int): number of cross-validation runs that were performed
fpr_list (list... | 710a904ce50f6fd0f7c8b0cec1a44c72f4417041 | 44,565 |
def prepare_for_training(data, polynomial_degree=0, sinusoid_degree=0, normalize_data=True):
"""Prepare dataset for training on prediction."""
# Calculate the number of examples.
num_examples = data.shape[0]
# Prevent original data from being modified.
data_processed = np.copy(data)
# Normali... | c20ac524ed44bb9c1bff0943c85ec16251a6915a | 44,566 |
def z_curvature_stacks(z_fit_params, z_contour_stack):
"""
Calculates curvature, normal, and tangent vectors of contours on a given
image stack on z-slice
Iteratively steps through z_fit_params and z_contour_stack and calls
curvature_z_slice
Parameters
----------
z_fit_params : list
... | 8af26fb34a9a1d6b78adf6d2192c040504f0f355 | 44,567 |
import requests
def get_ec2_instance_ip():
"""Try to obtain the IP address of the current EC2 instance in AWS"""
try:
ip = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text
except requests.exceptions.ConnectionError:
return None
return ip | b9b403124daba52236218d75225c537b450f283b | 44,568 |
import random
def e_greedy(options, e=0., reverse=False):
""" Epsilon-greedy algorithm for selecting sampled bandits
Parameters
----------
options : list
list of the bandits samples
e : float, default = 0
epsilon value between 0 and 1 that determines how random the chosen bandit i... | 648ceccf20ac19078557f8185f83c29c985f8ae8 | 44,569 |
from typing import Tuple
from typing import List
def get_all_serialization_annotations(
annotation: Annotation
) -> Tuple[Annotation, List[SerializationAnnotation]]:
"""Gets the type T of Annotation[T, SerializationAnnotation]
Args:
annotation (Any): The annotation
Returns:
Tuple... | a88818a33ec311fb39ad7d42ecd6abc3b651b062 | 44,570 |
def _name_to_agent_class(name: str):
"""
Convert agent name to class.
This adds "Agent" to the end of the name and uppercases the first letter
and the first letter appearing after each underscore (underscores are
removed).
:param name:
name of agent, e.g. local_human
:return:
... | 6ac0dbf4fb8ab90e592b85216be6d9c109a1310c | 44,571 |
def bin_search_recursive(array, what_to_find, left=0, right=None):
"""
Finds element in a sorted array using recursion.
:param list array: A sorted list of values.
:param what_to_find: An item to find.
:returns: Index of the searchable item or -1 if not found.
"""
right = right if right is... | 83ff4dbcd9cab179c5e83f73d5fdc7c5a6bca4d4 | 44,572 |
from typing import List
def extensions_to_glob_patterns(extensions: List) -> List[str]:
"""Generate a list of glob patterns from a list of extensions.
"""
patterns: List[str] = []
for ext in extensions:
pattern = ext.replace(".", "*.")
patterns.append(pattern)
return patterns | a04ed356bfa5db7c0210b86dff832d32bfef6dbf | 44,573 |
def is_classvar(t):
"""
>>> is_classvar(typing.ClassVar[int])
True
>>> is_classvar(int)
False
"""
return is_from_typing_module(t) and str(t).startswith("typing.ClassVar[") | 611092fa7c2f430aa755bbd667d40abcd7ccf693 | 44,574 |
from typing import Tuple
def get_reduced_powers(values: Tuple, power: int) -> Tuple[Expr, Symbol]:
"""
For a variable v only taking finitely many values v**n can be written as linear
combinations of powers < |values|. This function computes this linear combination.
The values ought be passed as a sort... | edb4977ec5ee84129f35b1d8bafed59ad948b3f0 | 44,575 |
def detect_cross_pnt(arr, thr, way='up', gap=1):
"""
detect the data rise/down point, returns the index of the
point right above the threshold.
arguments:
- arr: data array (1d)
- thr: threshold (scale)
key arguments:
- way: either be "up" or "down", for data rise/ data down respective... | 0cf5db8f78cb0ee81174a7d662551c095480de97 | 44,576 |
def check_resource(drink_ingredients):
"""Checks whether the ingredients in the machine enough to make the drink"""
for items in resources:
if drink_ingredients[items] > resources[items]:
print(f"Sorry there's not enough {items}!")
return False
return True | ecd869d4f09032e57d151ec6816fc2b08dce41b8 | 44,577 |
def handler(event, context):
"""
https://docs.aws.amazon.com/lambda/latest/dg/with-scheduled-events.html
"""
print(event, context)
publisher.handle(event, context)
return {} | 049029afedc796f86fd2b82637464e724d722bf9 | 44,578 |
from typing import Union
from typing import Mapping
def extract_image(
inputs: Union[jnp.ndarray, Mapping[str, jnp.ndarray]]
) -> jnp.ndarray:
"""Extracts a tensor with key `image` or `x_image` if it is a dict, otherwise returns the inputs."""
if isinstance(inputs, dict):
if "image" in inputs:
retur... | 2a4ecc20c861532736a4725fbe5a19b53847a53e | 44,579 |
def drop_duplicate_cols(df: pd.DataFrame) -> pd.DataFrame:
"""Remove duplicated colulms from a df
# https://stackoverflow.com/questions/14984119/python-pandas-remove-duplicate-columns/40435354#40435354
Args:
df (pd.DataFrame): df with duplicated column names
Returns:
pd.DataFrame: df ... | 3b5ffa67b363e59271a5c6392fec0365c2034daf | 44,580 |
def find_sources(indegrees: dict) -> deque:
"""Find sources (nodes that have 0 inbound edges).
Args:
indegrees (dict): A dictionary where the key is a graph node \
and the value is the number of inbound edges.
Returns:
deque: A deque containing source nodes.
"""
sources = d... | f31c67eedebe9d15aa65fbbcc1b36cf52c4eccc7 | 44,581 |
def stretch_audio(x, rate, window_size=512):
"""Stretch the audio speech using spectrogram.
Args:
x (numpy.ndarray): Input waveform.
rate (float): Rate of stretching.
window_size (int, optional): Window size for stft. Defaults to 512.
Returns:
numpy.ndarray: The stretched a... | cd07aca4db84eb8934510afd6770b439289bc264 | 44,582 |
async def email_subscribe_confirm(token, hood=Depends(get_hood_unauthorized)):
"""Confirm a new subscriber and add them to the database.
:param token: encrypted JSON token, holds the email of the subscriber.
:param hood: Hood the Email bot belongs to.
:return: Returns status code 200 after adding the s... | 441ec97f6534749fb6a006a443326f56ebe75f8f | 44,583 |
def pairing_gen(email_addresses):
"""This function generates the final pairings and outputs an alphabetically sorted pandas dataframe with all
elements in both columns """
pairing_1 = []
pairing_2 = []
for first_member, second_member in grouper(email_addresses, 2, SUBSTITUTE):
pairing_1.appe... | 5efa2b3a7f6de73c2c117dd3e7a0407e8ce52e57 | 44,584 |
import torch
def get_joint_loss(data_dict, device, config, weights,
detection=True, caption=True, reference=True, use_lang_classifier=True, num_ground_epoch=50):
""" Loss functions
Args:
data_dict: dict
config: dataset config instance
reference: flag (False/True)
Returns:
... | 66d5358286b20dc2e4efa5ed71bea298c4a5eeca | 44,585 |
def specr_model(fn, a,b,c1,c2,d,e):
"""
Description:
------------
Theoretical model for spectral ratio. Preferred model is
determined by the values of d & e and they are user-defined.
Input:
-----------------
fn --> freqeuncy bins
a --> fc main event
b --> fc egf
... | 1355ba14569cb87ebe6d8f937db81db89fc8c952 | 44,586 |
import re
def get_operation_id_groups(expression):
"""Takes an operator expression from an .mmcif transformation dict, and
works out what transformation IDs it is referring to. For example, (1,2,3)
becomes [[1, 2, 3]], (1-3)(8-11,17) becomes [[1, 2, 3], [8, 9, 10, 11, 17]],
and so on.
:param str ... | 8ec6fdca5209de1d658a2ae938fc840e9d1b0c23 | 44,587 |
from typing import Optional
def is_plus(char: Optional[str]) -> bool:
"""Check if character is a plus symbol."""
return char == PLUS | 9a9a1141f87150ec621e283362a1831eb0bb8288 | 44,588 |
def mrt_alert_msg(mrt_line, direction, stations, public_bus, mrt_shuttle, mrt_shuttle_dir):
"""
Message that will be sent if there is an MRT alert/breakdown/delay
:param mrt_line: "DTL/NSL/EWL..."
:param direction: "Both"/specific MRT station name("Jurong East")
:param stations: "NS17, NS16, NS15, N... | df03473dab23748f42bfe9fc8bc0fe9a80fc7c74 | 44,589 |
def clusters_tournament(ptree, labels):
"""A cluster 'wins' if some node inside the cluster is the ascendant
of another node in the other cluster"""
L = np.max(labels) + 1
T = np.zeros((L, L), dtype=int)
for i, m in enumerate(ptree.match):
li = labels[i]
if li != -1:
for ... | 8ccf7ad28e58c44c7f12051bded48136fe7598c5 | 44,591 |
from datetime import datetime
import requests
from bs4 import BeautifulSoup
def _load_quebec(start_date=datetime(2020, 1, 1), end_date=datetime.today(), verbose=True):
"""
Parameters:
- `start_date`
datetime object, the date of the earliest news release to be retrieved. By default, only ... | 295b723a4e7ab6d36c540e1910e954b0efd439bd | 44,592 |
def batch_to_model_inputs(batch, aux, prog, diag, forcing, constants):
"""Prepare batch for input into model
This function reshapes the inputs from (batch, time, feat) to (time, z, x,
y) and includes the constants
"""
batch = merge(batch, constants)
def redim(val, num):
if num == 1:
... | b0268c72499823bad747fb30e4be8d091c3060d6 | 44,593 |
def is_envvar(buff, pos):
""":return: start, end, pos or None, None, None tuple."""
try:
while buff[pos] in ' \t':
pos += 1
start = pos
while True:
if buff[pos] in '\0"\'()- \t\n':
return None, None, None
if buff[pos] == '=':
... | ee424577dd91a7d7011996c5f185f15855e1d2f5 | 44,594 |
def application():
"""Create an application."""
return flaked.Application() | 067fc7e8763678b1ba3387f95f8b90fc3f1075bd | 44,595 |
from bs4 import BeautifulSoup
def urlscraper(url: str, pattern: str, regex:bool=False) -> list:
"""urlscraper is a simple method to scrape information from a url based on a given string pattern
:param url: the url to run pattern against
:param pattern: the string representation of the pattern
:param ... | a1788fb1e6d98d1fb65dd3bdb617bf9a22f0a053 | 44,596 |
def load_model(filename):
"""
Return a model stored within a file.
This routine is for specialized model descriptions not defined by script.
If the filename does not contain a model of the appropriate type (e.g.,
because the extension is incorrect), then return None.
No need to load pickles o... | 2be8d79119538c31606dfccffd8560aa82dc4e7a | 44,597 |
def climb_stairs(stairs):
#
"""You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can
you climb to the top?
Example:
Input: 2
Output: 2
3
1 1 1
1 2
2 1
"""
... | c32a05ab1013b769c2d040a00c622605d7893398 | 44,598 |
def measure_nearest_neighbor_performance(accuracy_label, encoder,
family_accessions, batch_size,
train_samples, shuffle_seed,
sample_random_state):
"""Measures nearest neighbor classification p... | defbc8a86978062997fb6bacb912c014ede6fbf0 | 44,599 |
def make_safe(s):
"""Replaces all spaces with '\\ '"""
return replaceAll(s, " ", "\\ ") | 2f7d09b50cd7d4b78789fd27c31639d1d981b404 | 44,600 |
def gradient_descent(w0, optimizer, regularizer=None, opts=dict()):
"""
Mini-Batch Stochastic Gradient descent algorithm.
w0: is the initial guess
loss_function: is the loss function you want to optimize. It should have the gradient and loss method.
opts: a dictionary with the algorithm parameters
... | 070b42508343b662128c60726f6c7ebdc312511c | 44,601 |
import io
def parse_xml_file(filename):
"""Returns a dictionary with the class_id, genus, species, bg_species."""
def strip_tag(s):
return s.split('>', 1)[1].split('<', 1)[0]
mapping = {"ClassId": "class_id",
"Genus": "genus",
"Species": "species",
"Ba... | 14bb447987d42465bfb6543935ba67285e72322c | 44,602 |
def compute_aggregation_axes(dims, axes=None, keepdims=False):
"""Computes parameters for an aggregation-over-axes operation.
Args:
dims ([int or Value]): The dimensions of the value being aggregated.
axes ([int], optional): Defaults to None. The indices of the axes to aggregate over.
k... | c4d6bec3c9bad18bd56829e05b36030c262a3649 | 44,604 |
def dataNormalize(data, maxAudio_total ,maxVisual_total ):
"""
:param data: the avData, size is (*,288,360)
:return: the normalized avData, size is (*,288,360)
normalize method: (x-min_local)/(max_total-min_local)
"""
data_nor = np.zeros(data.shape)
for i in range(6):
audiodata = dat... | 0078397ebbbd360c8ca4d0501cad87cf34582a48 | 44,605 |
def is_rfc1918(ip_str):
"""Returns True if the IP is private. If the IP isn't a valid IPv4 address
this function will raise a :class:`ValidationError`.
"""
private_networks = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"]
try:
ip_str_network = ipaddr.IPv4Network(ip_str)
except ipaddr.... | 40c103719203f469ccb00e0a27a9524275dbaeb5 | 44,606 |
def create_hparams(hparams_string=None, verbose=False):
"""Create model hyperparameters. Parse nondefault from given string."""
hparams = tf.contrib.training.HParams(
################################
# Experiment Parameters #
################################
epochs=1000,
... | 3bed61b035e51cca028cd8dbaf62c44a6dca1b9a | 44,607 |
def optionsSymbols(
symbol="",
expiration="",
includeExpired=None,
token="",
version="stable",
filter="",
format="json",
):
"""This call returns an object keyed by symbol with the value of each symbol being an array of available contract dates.
https://iexcloud.io/docs/api/#options-... | ea4ff999bd58777d162870b8499a881f0526d351 | 44,610 |
import textwrap
def text_word_wrap(text, width):
"""
Word-wrap a string to width `width`.
"""
return textwrap.wrap(text, width) | 7dbaae3a61be37a3208dd9c9b6a541aadb325e3e | 44,611 |
from typing import Union
def inspect_coefs(lm, X) -> Union[pd.Series, pd.DataFrame]:
"""
View a summary of a linear model's coefficients.
Works for both linear and logistic regression models.
>>> import pydataset
>>> iris = pydataset.data('iris')
>>> X, y = iris[['Sepal.Length', 'Sepal.Width... | 01827a747d6cb0e5d5c221ce358eb2e3b299f6db | 44,612 |
def clean_census_data(df):
"""
Clean up the census data results from the API. By default, the census data often
includes non-numeric characters as annotations or missing values.
# see https://www.census.gov/data/developers/data-sets/acs-5year/data-notes.html
# for estimate and annotation values
... | 978ac976d3a39815c48a827e42760044846eda1b | 44,613 |
def find_detection_probability(Mc, eta, redshifts, distances, n_redshifts_detection, n_binaries, snr_grid_at_1Mpc, detection_probability_from_snr,
Mc_step=0.1, eta_step=0.01, snr_step=0.1):
"""
Compute the detection probability given a grid of SNRs and detection probabilities... | 4d042c65616d6f4c4952f9478659e32b6dcd746a | 44,615 |
def maybe_value(tree: dict, *path_components: str):
"""
Get the value corresponding to last key in the key path ``[k1, k2, ..]``
on the input dictionary tree. The key sequence may match an actual key path
or match it up to a point or not match any path at all. If a key ``k[n]``
in the input sequence... | 6869f81a30d0d5ddf70394a48b7ae5588e778631 | 44,616 |
def response_json_ok(json):
"""Creates a tuple representing the HTTP package to
respond the requisition with the given JSON on its body
and status code 200
:param json: object to be sent on HTTP body
:return response: tuple representing the HTTP response package
"""
return _make_json_respons... | 07e7c7894ec6deab7795aa70500ab73a795a01ce | 44,618 |
def build_k_indices(y, k_fold, seed=1):
"""build k indices for k-fold."""
num_row = y.shape[0]
interval = int(num_row / k_fold)
np.random.seed(seed)
indices = np.random.permutation(num_row)
k_indices = [indices[k * interval: (k + 1) * interval]
for k in range(k_fold)]
return... | 7e9b1ff6a12669db8d92d6c9034551256ceaa9d0 | 44,619 |
import torch
def init_model(args, num_classes):
"""Initialise model"""
architecture = getattr(models, args.model)
if args.curve is None:
model = architecture.base(num_classes=num_classes,
**architecture.kwargs)
else:
curve = getattr(curves, args.curve... | db774fb07dc33fb28e770e06b18d7a0f5b3c8d3c | 44,620 |
def get_LoiterType_str(str):
"""
Returns a numerical value from a string
"""
if str == "VehicleDefault": return LoiterType.VehicleDefault
if str == "Circular": return LoiterType.Circular
if str == "Racetrack": return LoiterType.Racetrack
if str == "FigureEight": return LoiterType.FigureEight... | c8905381f56a070b8ecc83545638e0f4a40bc4af | 44,621 |
import json
def load_tour(fname):
"""
Reads a tour from a JSON file.
Input:
- fname : filename
Output:
- tour : loaded tour
"""
with open(fname, 'r') as fp:
return json.load(fp) | 7cd4db05867d2ab5dd26620c8ff2497eb5aa4a68 | 44,622 |
def get_lhn_accordion(driver, object_name):
"""Select relevant section in LHN and return relevant section accordion."""
selenium_utils.open_url(url.Urls().dashboard)
lhn_menu = dashboard.Header(driver).open_lhn_menu()
# if object button not visible, open this section first
if object_name in cache.LHN_SECTION_... | 595c56ba27bf5cd44c0763e49fc61438f36051c0 | 44,623 |
import itertools
def modular_sqrt_composite(c, factors):
"""
Calculates modular square root of composite value for given all modulus factors
For a = b^2 mod p*q*r*m... calculates b
:param c: residue
:param factors: list of modulus prime factors
:return: all potential root values
"""
n ... | ea4512dde1eb297911c60145e5f327e55397a4df | 44,624 |
def trim_zeros(x):
"""It's common to have tensors larger than the available data and
pad with zeros. This function removes rows that are all zeros.
x: [rows, columns].
"""
pre_shape = x.shape
assert len(x.shape) == 2, x.shape
new_x = x[~np.all(x == 0, axis=1)]
post_shape = new_x.shape
... | 18e81174191c8299c6c1b6ac38920c07b457d1db | 44,625 |
def show_user(username):
"""Some Comment"""
return 'Welcome: %s' % username | 29980cfe7dba8048aa0ecaa351d9baf4d47dd8ec | 44,627 |
def unfold_rep_seq(rep_seq: str) -> str:
"""Unfold the rep_seq string."""
unfolded = ""
matches = rep_seq_pat.findall(rep_seq)
for m in matches:
unfolded += m[0] * int(m[1]) + m[2]
return unfolded | da5f1434c1cd2970def90ef899fc8ad72c58aea4 | 44,628 |
def get_cost(ss, a, dist_mat, C, n):
"""Determines the cost of an airline route network from a sampleset.
Args:
- ss: Sampleset dictionary. One solution returned from the hybrid solver.
- a: Float in [0.0, 1.0]. Discount allowed for hub-hub legs.
- dist_mat: Numpy matrix providing dista... | d8e810133a08213d0815a551c1fd7eaaa650532f | 44,629 |
def get_epsilon_interpolator(
eps, t_break, eps2=-1, t_delta_phases=-1, transition_time=14, t_break_final=None, eps_final=None
):
"""
Return an interpolator that produces an epsilon when called with a time (relative to the model
start). The solution has at least 3 steps (4 if t_break_final and eps_final... | 7c456cfc737c9625da09555f8262e650124ae7ea | 44,631 |
def get_cqt_index(pitch, hparams):
"""Get row closest to this pitch in a CQT spectrogram"""
frequencies = librosa.cqt_frequencies(constants.TIMBRE_SPEC_BANDS,
fmin=librosa.midi_to_hz(constants.MIN_TIMBRE_PITCH),
bins_per_octave=... | 7dca5cb117f5c64874408b63728a296b99bcb781 | 44,632 |
import io
def save_file_in_minio(csv_file, shop_key):
"""
creates a file in the minio stores 'productstore' bucket
:param shop_key: A string that is used to specify a shop
:param csv_file: A object that is an instance of CsvFile
:return:
"""
with Span(span_name='save_file_in_minio', trace_... | b83b1452dc475b69966c7274446311220147c341 | 44,633 |
import unittest
import test
def suite():
"""Suite of test to run"""
glome_tests = unittest.TestLoader().loadTestsFromModule(test.glome_test)
autoglome_tests = unittest.TestLoader().loadTestsFromModule(
test.autoglome_test)
fuzzing_tests = unittest.TestLoader().loadTestsFromModule(test.fuzzing_... | becc2d4834cc6cf44b32d7a2502772c777c993c3 | 44,634 |
def kde_2d(df, w, x, y, xmin=None, xmax=None, ymin=None, ymax=None,
numx=50, numy=50):
"""
Calculates a 2 dimensional histogram from a Dataframe and weights.
For example, a results distribution might be obtained from the history
class and plotted as follows::
df, w = history.get_dis... | 2a824323cebd2de21b7eb2f83a882436b8ce91f3 | 44,635 |
import unicodedata
import re
def slugify(value):
"""
Converts to lowercase, removes non-word characters (alphanumerics and
underscores) and converts spaces to hyphens. Also strips leading and
trailing whitespace.
"""
value = (
unicodedata.normalize('NFKD', value)
.encode('ascii... | 0b2ca40d1595d079f0b85cebc250264866cf1b39 | 44,636 |
def hexpass(pwd):
"""Convert no alpha numeric characters in a password string to
hexadecimal
Args:
pwd(str): The password as a string
Returns:
The converted string
Examples
>>> print(hexpass('matter'))
'matter'
>>> print(hexpass('m@tt3r'))
"m%40tt3r'
"""
... | 07e91b8d2b3890ac3594235c74c420f5b1164118 | 44,637 |
def get_best_align_elem(tensor_size, tensor_dtype):
"""Get the best tiling factor for alignment axis."""
basic_align_elem = int(ct_util.BLOCK_SIZE / get_bytes(tensor_dtype))
lcm = least_common_multiple(tensor_size, basic_align_elem)
gcd = greatest_common_divisor(tensor_size, basic_align_elem)
if gcd... | 5b545bf8ca59053b046031deddab2681075d0f66 | 44,638 |
def new_spline(Tend, n_parts, targetvalues, tag, bv=None, use_std_approach=True):
"""
:param Tend:
:param n_parts:
:param targetvalues: pair of arrays or callable
:param tag:
:param bv: None or dict of boundary values (like {0: [0, 7], 1: [0, 0]})
:return: Spli... | 6d4bc880802c7f093bf7dfb57d0b510190f305f4 | 44,642 |
from operator import concat
def sample_and_group(npoint, nsample, xyz, points, density_scale = None):
"""
Input:
npoint:
nsample:
xyz: input points position data, [B, N, C]
points: input points data, [B, N, D]
Return:
new_xyz: sampled points position data, [B, 1, C]... | bb49ddba21180c14826668abbdcea78ae4f046f7 | 44,643 |
def main(corpus, allrules, names, maxrules, iteration, options, display):
"""
Produces lists of grams, from monograms up to k-grams.
Duplicate found in /scripts/readnames.py
Example use to get monograms, birgams, and trigrams:
getKgrams(getPNs(), 3)
Args:
corpus (set) = set of all tokens... | 10f2b5533a23ca1d5401d647fe59909581f749bd | 44,644 |
def bin2hex(binary):
""" Converts Binary to HExaDEcimal"""
binary_split1 = (binary[0:4])
binary_split2 = (binary[4:8])
hex1 = b[binary_split1]
hex2 = b[binary_split2]
return str(hex1) + str(hex2) | 078bd13a5c9e014f96321d5f9bfd3469f31f4b41 | 44,645 |
def derive_along_path(path, seed):
"""Derive an extended key from a 64-byte binary seed and a BIP-0044 path.
Returns the extended key obtained by following the given derivation path,
starting at the extended master key derived from the given binary seed.
"""
elements = list(element.rstrip("'") for... | 44eab8ba7868f178b32c339bb0e341cb03588e4f | 44,646 |
def _convert_to_float(score):
"""
Convert a string ('score') to float.
If the string is empty, return None.
If the string is float-like, return its float.
"""
if len(score) == 0:
return None
else:
return float(score) | 48cbc42310595d5a6ae8d8296feb7d81e61d52dc | 44,647 |
import click
import functools
def ensure_host_configured(f):
"""Ensure that this configuration has been set up."""
@click.pass_obj
@functools.wraps(f)
def _wrapper(cfg, *args, **kwargs):
if cfg.get('remote.ssh.host', '*') == '*':
click.echo(f"{click.style('ERROR', fg='red')}: No c... | f44ec26db18a3a228620b9e3319529ff728c9cfa | 44,648 |
def _next_good_prime(p, R, qq, patience, qqold):
"""
Find the next prime `\\ell` which is good by ``qq`` but not by ``qqold``, 1 mod ``p``, and for which
``b^2+4*c`` is a square mod `\\ell`, for the sequence ``R`` if it is possible in runtime patience.
INPUT:
- ``p`` -- a prime
- ``R`` -- an... | cfb3701cff0d4a6dcbe53ed34bb5e2f02504819f | 44,649 |
def leapyear(year):
"""Judge year is leap year or not."""
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) | afd3239d8616e2439fd551506f37cd5a93f00bd8 | 44,651 |
def correlate_clines(x1,x2,y1,y2,penalty):
"""use dynamic time warping to correlate centerlines
inputs:
x1, y1 - coordinates of first centerline
x2, y2 - coordinates of second centerline
penalty - parameter that forces more parallel correlation (or not)
outputs:
p - indices of correlation in... | 7a7b64d6775e2a8efe3752edbc04055a761dcdfb | 44,652 |
from typing import List
from typing import OrderedDict
def _serialize_params(params: List[ParamsDependency]):
"""Return two types of values from stage:
`keys` - which is list of params without values, used in a pipeline file
which is in the shape of:
['lr', 'train', {'params2.yaml': ['lr']}]
... | 018c569b462a1aad2276e4d57df09f83483e569f | 44,653 |
def evolve_profile(diff_matrix, x_points, dc_init, exp_norm_profiles=None,
plot=True, return_data=False, labels=None):
"""
Theoretical diffusion profile, given the diffusion matrix.
Parameters
----------
diff_matrix : tuple
diffusion matrix, tuple of (eigenvalues, eigenv... | 35550b0980430fa9d3e96bc7203591de82663663 | 44,654 |
def evaluate(model, inputs, **kwargs):
"""Performs model rollouts and create stats."""
initial_state = {k: v[0] for k, v in inputs.items()}
num_steps = inputs['cells'].shape[0]
prediction = _rollout(model, initial_state, num_steps)
error = tf.reduce_mean((prediction - inputs['velocity'])**2, axis=-1)
scala... | 9d5a981ef28c9f9e724787049c5934dbb0c5876f | 44,655 |
def add_stereo_from_geometries(rxn, rct_geos, prd_geos):
""" Add stereo assignments to this reaction object from geometries.
:param rxn: a reaction object
:type rxn: Reaction
:param rct_geos: the reactant geometries
:param prd_geos: the product geometries
:returns: a reaction object with stereo... | 0766b6a5ba80bafae9c2ac9f19d6491e15810f5a | 44,656 |
def determine_suitable_lda(displace_elev, margin):
"""Given a displacement elevation and safety marign, determine the
minimum acceptable LDA settings."""
return displace_elev * margin | 6db43c125ee98bfefe91f9d44c601dcacdf7aff3 | 44,657 |
def current_client_year():
"""
gets the current year based on client timezone.
this is a helper method to let get the client year
without providing value to `current_year` method.
:rtype: int
"""
return get_component(DateTimePackage.COMPONENT_NAME).current_client_year() | 108805b978ab30b91ff5b3ffe9b540219726e3c9 | 44,658 |
def einsum(x1, x3):
"""paddle.einsum only support in dynamic graph mode.
x1 : n c u v
x2 : n c t v
"""
n, c, u, v1 = x1.shape
n, c, t, v3 = x3.shape
assert (v1 == v3), "Args of einsum not match!"
x1 = paddle.transpose(x1, perm=[0, 1, 3, 2]) # n c v u
y = paddle.matmul(x3, x1)
# ... | fd9d7544376aa84e26de898eb5e91b02f8b30280 | 44,659 |
def format_raw_object(raw_object, internal_dict):
"""Format a RawObject."""
raw = raw_object.GetChildMemberWithName("raw_").GetValueAsUnsigned()
# SmallInt
if raw & 0x1 == 0:
return str(raw_object.GetChildMemberWithName("raw_").GetValueAsSigned() >> 1)
low_tag = (raw >> 1) & 0x3
if low_... | 141908858f5de01277a94db22e4e6b53d34bfd0c | 44,660 |
def constructfullKMap(tmap, kmap):
"""construct a complete k-map from the complete t-map and mapping between t-vals and k-vals"""
newarr = tmap.copy()
for t, k in enumerate(kmap):
newarr[tmap==t] = k
return newarr | d034522b00facc29cd9218f50a5f22ed1963c24c | 44,661 |
def get_format_from_name(name: str) -> str:
"""
Function to infer the input format. Used when the input format is auto.
"""
try:
int(name)
src_format = "numeric"
except ValueError:
if len(name) == 2:
src_format = "alpha-2"
elif len(name) == 3:
... | ca5baa8790837002261bab68f3989f57fa2943af | 44,662 |
def get_linexp_from_variables(variables):
"""
Return a linear expression from the supplied list
of variables.
"""
linexp = gp.LinExpr()
for v in variables:
linexp += v
return linexp | f20d845544fcaac541346f45b58e63129be9df0a | 44,663 |
def get_landing_from_url(path):
""" determine whether a URL is a landing page.
This should always return boolean, not search result.
"""
if LANDING_RE.search(path):
return True
else:
return False | 1cc5ce37d57c0b0c36b3bb33b6e39dbdbc363b8a | 44,664 |
def svn_diff_fns_invoke_datasource_close(*args):
"""svn_diff_fns_invoke_datasource_close(svn_diff_fns_t _obj, void diff_baton, svn_diff_datasource_e datasource) -> svn_error_t"""
return _diff.svn_diff_fns_invoke_datasource_close(*args) | f4ef81415ee0879fe454ee2d6e47e27fb95f74bf | 44,665 |
async def set_turn(pnum):
"""Set turn manually."""
try:
player_num = int(pnum)
except ValueError:
return jsonify({"status": "error", "error": "invalid player id"})
if player_num < 0 or player_num > 3:
return jsonify({"status": "error", "error": "invalid player id"})
try:
... | c0648676e79ac6fee4a7540b0ef56a76cd275fb0 | 44,666 |
def do_mixup(x, mixup_lambda):
"""Mixup x of even indexes (0, 2, 4, ...) with x of odd indexes
(1, 3, 5, ...).
Args:
x: (batch_size * 2, ...)
mixup_lambda: (batch_size * 2,)
Returns:
out: (batch_size, ...)
"""
out = (x[0 :: 2].transpose(0, -1) * mixup_lambda[0 :: 2] + \
... | 7642f9825c87487d6f80de8d5be9f7e6be98df9b | 44,668 |
def get_function_inputs(f):
"""
Given function signatures gets the name of the function.
:param f: a callable function
:return: input names on a tuple.
"""
if hasattr(f, cts.INTERNAL_PARAMETERS):
# 'internal_parameters' is defined inside the solver() annotation, see solver.py for details... | bcd96b4de330d6277a4fb31ee6420a4fb60bd34a | 44,669 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.