content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_public_key() -> bytes:
"""
Retrieve the raw public key.
:return: Bytes of key
"""
key = Ed25519PrivateKey.from_private_bytes(config.WEBHOOK_KEY)
return key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) | 2cdad670643c215405bd0b988031f7485f0f9c5b | 3,631,800 |
def create_empty_array(n_k, n_vals_i, n_feats):
"""Create null measure in the array form.
Parameters
----------
n_k: int
the number of perturbations
n_vals_i: int
the number of indices of the output measure.
n_feats: int
the number of features.
Returns
-------
... | 58ae0dc05bd0c256c8cad41e8f43cf3f87a11d1d | 3,631,801 |
def transform_bbox(x):
"""
Function purpose: Transform bounding box (str) into geometry
x: bounding box (str)
"""
try:
ring = ogr.Geometry(ogr.wkbLinearRing)
ring.AddPoint(x[0], x[1])
ring.AddPoint(x[2], x[1])
ring.AddPoint(x[2], x[3])
ring.AddPoint(x[0], x[3... | a8946a9f54307e82e3a9e82294371695f3d5eb86 | 3,631,802 |
from ressources.interactions import getIntKey
def addUser(username: str, autoGenerateKeys: bool = True, keys: list = []):
"""
Create an user with the corresponding username to the users list and return the corresponding user id which can be used as index
username: name of the user
autoGenerateKeys: g... | ea01b6480a6953f9f4132e5245d98be29c8e77cd | 3,631,803 |
from re import DEBUG
from sys import stdout
def setup_logging(debug=False):
"""
Set up the logging for hypernode_vagrant_runner
:param bool debug: Log DEBUG level to console (INFO is default)
:return obj logger: The logger object
"""
logger = getLogger('hypernode_vagrant_runner')
logger.se... | 15af00b3d72cb51effa4e9606d590283cf7d4862 | 3,631,804 |
import json
def remove_conf(module):
"""
Remove specified module from db
Module is identified by its name in lowercase
"""
# Get the original document
res = db.delete("configuration", 'name', str(module).lower())
if res == None:
raise ConfError("Module '%s' wasn't deleted" % mo... | 1c7b4d70dabe05d1a9ac8d253b89e1c2bff6c9eb | 3,631,805 |
import re
def video(package):
"""method for download video
"""
params = package.get('params')
video_id = params.get(ParamType.VideoID)
request = package.get('request')
range_header = request.META.get('HTTP_RANGE', '').strip()
range_re = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I)
... | 6bf9fff7b49e5a22da945a4ff87784b408ab6086 | 3,631,806 |
import sqlite3
def task_items(max_entries=None):
"""Information about the items in the task queue. Returns a
generator of QueueItems.
Keyword arguments:
max_entries - (int) (Default: None) Maximum number of items to
return. Default is to return all entries.
"""
con = sqlite3.connect(s... | 9bbe72d6fadc134b0654a8e2736ff66e6aa718ec | 3,631,807 |
from typing import Tuple
from typing import Optional
def _remove_anchors_in_pattern(pattern: str) -> Tuple[Optional[str], Optional[str]]:
"""
We need to remove the anchors (``^``, ``$``) since schemas are always anchored.
This is necessary since otherwise the schema validation fails.
See: https://sta... | 9ff66372943df6b4e0c0243c18a82d1ea5c49008 | 3,631,808 |
def bfs(connections, start, goal=None):
"""
Requires a connections dict with tuples with neighbors per node.
Or a connections function returning neighbors per node
Returns
if goal == None: return dict of locations with neighbor closest to start
elif goal found: returns path to goal
el... | c93e619def9ca183ab5224bee50b021531d85f4a | 3,631,809 |
def reverse_complement(dna):
"""
Reverse-complement a DNA sequence
:param dna: string, DNA sequence
:type dna: str
:return: reverse-complement of a DNA sequence
"""
complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'}
return ''.join([complement[base] for base in dna[::-1]]) | efcb38e06fc494adabeb304934ebef9bd932a11f | 3,631,810 |
import pyarrow
def df_to_bytes(df: pd.DataFrame) -> bytes:
"""Write dataframe to bytes.
Use pyarrow parquet if available, otherwise csv.
"""
if pyarrow is None:
return df_to_bytes_csv(df)
return df_to_bytes_parquet(df) | 145eb7204ae77f5fd457eeb82c54e2e8b2f65b27 | 3,631,811 |
import tqdm
def select_training_voxels(input_masks, threshold=0.1, datatype=np.float32, t1=0):
"""
Select voxels for training based on a intensity threshold
Inputs:
- input_masks: list containing all subject image paths for a single modality
- threshold: minimum threshold to apply (after ... | f5868ce28f51abb4e8f84539b5bfffa028d2a184 | 3,631,812 |
import itertools
def find_intersections(formula_lists,group_labels,exclusive = True):
"""
Docstring for function pyKrev.find_intersections
====================
This function compares n lists of molecular formula and outputs a dictionary containing the intersections between each list.
Use
----
f... | ae023b053dc98f34b99ab1aa70161eb306a197f6 | 3,631,813 |
import starlink.Ast as Ast
import starlink.Atl as Atl
def wcs_align(hdu_in, header, outname=None, clobber=False):
"""
This function is used to align one FITS image to a specified header. It takes the following arguments:
:param hdu_in: the HDU to reproject (must have header and data)
:param header: t... | 41a0da7943845bbd63f5634d65b45804f1caaf7c | 3,631,814 |
import os
import tempfile
import csv
import zipfile
import shutil
def save_pumping_test(pump_test, path="", name=None):
"""Save a pumping test to file.
This writes the variable to a csv file.
Parameters
----------
path : :class:`str`, optional
Path where the variable should be saved. Def... | ae98a5f70932c37c3478e6320aac6bf2f568fc52 | 3,631,815 |
from typing import Dict
def merge_flag_dictionaries(a: Dict[str, str], b: Dict[str, str]) -> Dict[str, str]:
"""
>>> a = {'CFLAGS': '-1'}
>>> b = {'CFLAGS': ' -2'}
>>> merge_flag_dictionaries(a, b)
{'CFLAGS': '-1 -2'}
"""
a_copy = deepcopy(a)
b_copy = deepcopy(b)
... | 3d83f5083cfdb1a280c54fb42bd5bf0c89304b5f | 3,631,816 |
def _delete_magic(line):
"""Returns an empty line if it starts with the # [magic] prefix
"""
return '' if line.startswith(_PREFIX) else line | 9e14cb7cac1f3c991cfad01bde7e0c2bf1a24a72 | 3,631,817 |
import odbc
import pyodbc
import psycopg2
import pgdb
def init_db_conn(connect_string, username, passwd, show_connection_info, show_version_info=True):
"""initializes db connections, can work with PyGres or psycopg2"""
global _CONN
try:
dbinfo = connect_string
if show_connection_info:
print(dbinfo)
if USE... | 02487f08519d25203e9eabd3a504795114bc020a | 3,631,818 |
import re
def untokenize(words):
"""
Source: https://github.com/commonsense/metanl/blob/master/metanl/token_utils.py
Untokenizing a text undoes the tokenizing operation, restoring
punctuation and spaces to the places that people expect them to be.
Ideally, `untokenize(tokenize(text))` should be id... | e62720d5a5fc7048e73659d013cb92e274671533 | 3,631,819 |
def create_new_course(request_ctx, account_id, course_name=None, course_course_code=None, course_start_at=None, course_end_at=None, course_license=None, course_is_public=None, course_is_public_to_auth_users=None, course_public_syllabus=None, course_public_description=None, course_allow_student_wiki_edits=None, course_a... | fa5aea3872506356a60776093bca4faefe1caea0 | 3,631,820 |
from copy import deepcopy
def addReference(inData, reference):
"""
"""
data = deepcopy(inData)
existing_refs = [x for x in data['relatedIdentifiers'] if x['relationType']=='References']
ref_list = [ x['relatedIdentifier'] for x in existing_refs]
if ( reference not in ref_list):
prin... | 85dd0c18966b632a2173c27e913bfe94a4d5ec29 | 3,631,821 |
def len_path_in_limit(p, n=128):
"""if path len in limit, return True"""
return len(p) < n | 988858918109902e662144a6650a33e593ba90b7 | 3,631,822 |
import torch
def threshold(tensor, density):
"""
Computes a magnitude-based threshold for given tensor.
:param tensor: PyTorch tensor
:type tensor: `torch.Tensor`
:param density: Desired ratio of nonzeros to total elements
:type density: `float`
:return: Magnitude threshold
:rtype: `f... | d0c5a2726a2df195b0588af8af95dac187f50e1b | 3,631,823 |
def _nt_quote_args(args):
"""Quote command-line arguments for DOS/Windows conventions.
Just wraps every argument which contains blanks in double quotes, and
returns a new argument list.
"""
# XXX this doesn't seem very robust to me -- but if the Windows guys
# say it'll work, I guess I'll have ... | a4281afcbc572f02e719f97f92ec30bdf4ddb138 | 3,631,824 |
def algorithm_free_one_only_over_isls(
output_dynamic_state_dir,
time_since_epoch_ns,
satellites,
ground_stations,
sat_net_graph_only_satellites_with_isls,
ground_station_satellites_in_range,
num_isls_per_sat,
sat_neighbor_to_if,
list_gsl_interface... | ca540acb71218579c63f9d19b8f3597fb376488f | 3,631,825 |
def combine_fo_m(m, moved_f):
"""
derate
1 -> available
0 -> not available
rules for combing after moving fo
r -> min(m,fo)
"""
df = pd.DataFrame({"m": m,
"newf": moved_f})
return df.apply(min, axis=1) | 7e966becd686fca955ac77e13b685f85bc3d4e86 | 3,631,826 |
import random
import copy
def modify_drone(solution, simulation):
"""Modifies the drone of a random operation.
...
Parameters:
solution(List[Transportation]): The list of the transportations of the solution
simulation(Simulation): The simulation
Returns:
List[Transportation]:... | 69debcb5a42e52248b6b8e18c62642f8290126f6 | 3,631,827 |
def keygen():
"""
Generates random RSA keys
"""
a = gen_prime()
b = gen_prime()
if a == b:
keygen()
c = a * b
m = (a - 1) * (b - 1)
e = coPrime(m)
d = mod_inverse(e, m)
return (e, d, c) | e5bb7d6b8c7c52f6328dc3ce1955b513f49d45a4 | 3,631,828 |
def _succ(p, l):
"""
retrieve the successor of p in list l
"""
pos = l.index(p)
if pos + 1 >= len(l):
return l[0]
else:
return l[pos + 1] | 0eea63bd24da4079b9718af437c6d7e38ef25444 | 3,631,829 |
def generate_diff_mos(laygen, objectname_pfix, placement_grid, routing_grid_m1m2, devname_mos_boundary, devname_mos_body,
devname_mos_dmy, m=1, m_dmy=0, origin=np.array([0,0])):
"""generate an analog differential mos structure with dummmies """
pg = placement_grid
rg12 = routing_grid_m... | d851371ea4c513a4a77661ffb177ef3d41d39189 | 3,631,830 |
def fetch_rrlyrae_templates(**kwargs):
"""Access the RR Lyrae template data (table 1 of Sesar 2010)
These return approximately 23 ugriz RR Lyrae templates, with normalized
phase and amplitude.
Parameters
----------
Returns
-------
templates: :class:`RRLyraeTemplates` object
co... | 90b965be26a18481fa60bf1b49a956d90fc559ba | 3,631,831 |
def BVHTreeAndVerticesInWorldFromObj(obj):
"""
Input: Object of Blender type Object
Output: BVH Tree necessary for ray tracing and vertsInWorld = verts in global coordinate system.
"""
mWorld = obj.matrix_world
vertsInWorld = [mWorld @ v.co for v in obj.data.vertices]
bvh = BVHTree.FromPoly... | 81154ee936785c14a1228c705190114a9a84fecf | 3,631,832 |
def _readline(ser):
"""Read a line from device on 'ser'.
ser open serial port
Returns all characters up to, but not including, a newline character.
"""
line = bytearray() # collect data in a byte array
while True:
c = ser.read(1)
if c:
if c == b'\n':
... | 469c5b6afa786d8bf94dec72a918b6df3b3ba4d7 | 3,631,833 |
def axline(x=None,y=None,a=None,b=None,label=None,lab_loc=0,ax=None,plot_kw={},**kwargs):
"""Generalised axis lines.
This function aims to generalise the usage of axis lines calls (axvline/axhline) together and
to allow lines to be specified by a slope/intercept according to the function y=a*x + b.
Parameters... | cb9b5c1bb1b6bdf28c2eec7f9f6e9791533915fc | 3,631,834 |
def getPermCityState(permRecord):
"""Returns a string with the 'location' of the perm.
It is generated from the starting city and starting state.
This important conversion is used in many places and thus
warrants its own commonized utility method.
Input: a CSVRecord/permanent object.
Output: a ... | 6d7bc3f6f10fc7f04a22318292a94aad3fa64cae | 3,631,835 |
import click
def direct_group(parent):
"""Direct ldap access CLI group"""
@parent.group()
def direct():
"""Direct access to LDAP data"""
pass
@direct.command()
@click.option('-c', '--cls', help='Object class', required=True)
@click.option('-a', '--attrs', help='Addition attri... | d44e252ab86bc14bf30f6bb3472e6bfe48ff2004 | 3,631,836 |
import os
def listPDBCluster(pdb, ch, sqid=95):
"""Returns the PDB sequence cluster that contains chain *ch* in structure
*pdb* for sequence identity level *sqid*. PDB sequence cluster will be
returned in as a list of tuples, e.g. ``[('1XXX', 'A'), ]``. Note that
PDB clusters individual chains, so t... | 0ea03fba88bdd715691cb63fd7bb1cfa9d0831a8 | 3,631,837 |
def elem_to_Z(sym: str) -> int:
"""
Converts element symbol to atomic number.
Parameters
----------
sym : str
Element string.
Returns
-------
int
Atomic number.
Examples
--------
>>> rd.utils.elem_to_Z('H')
1
>>> rd.utils.elem_to_Z('Br')
35
... | 8539658768e25dece01583031e161927c766adc8 | 3,631,838 |
def fn_I_axion_p(omega,xi_11,zeta_11,h_11,c_11,P_nuc,l,v,a,b,beta_11,k2,L_squid, R_squid, L_i, k_i, C_1, L_1, L_2, k_f, N_series,N_parallel):
"""Total axion-induced current through primary circuit, as a function of:
-- angular frequency omega
-- piezoaxionic tensor component xi_11
-- electroaxionic tens... | 8eb0cd4c5e221e425551604677151865bca7f70a | 3,631,839 |
def _C(startmat,endmat):
"""Calculate right Cauchy-Green deformation
tensor to go from start to end
:startmat: ndarray
:endmat: ndarray
:returns: ndarray
"""
F=_F(startmat,endmat)
C=np.dot(F.T,F)
return C | 2f83b7423ecd0611b6f6baf8e015fd8da28ea5e7 | 3,631,840 |
import re
def valid_uuid(uuid):
"""
Check if the given string is a valid uuid
"""
regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I)
match = regex.match(uuid)
return bool(match) | 0fd773851b8aa9ef65fda4a0c9ac0b24fdda8588 | 3,631,841 |
def get_products_stats_data(domains, datespan, interval,
datefield='created_at'):
"""
Number of products by created time
"""
# groups products by the interval and returns the time interval and count
ret = (SQLProduct.objects
.filter(domain__in=domains,
... | 5be8a75bb9157fc1ac000a9c91caa2fd6584133a | 3,631,842 |
def task_schemas_json_orchestrator():
"""Schemas - generate hat-orchestrator JSON schema repository data"""
return _get_task_json(
[schemas_json_dir / 'orchestrator.yaml'],
[src_py_dir / 'hat/orchestrator/json_schema_repo.json']) | 4c988e9efa0a077e64da685b27c3c1281cf9ddf0 | 3,631,843 |
def stopStreaming():
"""
Stop streaming.
Will return an `error` if streaming is not active.
"""
return __createJSON("StopStreaming", {}) | abc164be9756a186d12bc90ebf56eedc9c04aff3 | 3,631,844 |
from bs4 import BeautifulSoup
from typing import Callable
from typing import Union
from typing import Dict
from typing import List
def process_doc(
doc: BeautifulSoup, proc: Callable = None, log: bool = True
) -> Union[None, Dict[str, Union[str, List]]]:
"""
Process soup to extract text in sections recurs... | fb97a6eb1a63bb9ef4cbff6d0abfceca886fbb73 | 3,631,845 |
def gain_corr_double_ExpDecayFunc(t, tau_A, tau_B, amp_A, amp_B, gc):
"""
Specific form of an exponential decay used for flux corrections.
Includes a "gain correction" parameter that is ignored when correcting
the distortions.
"""
y = gc * (1 + amp_A * np.exp(-t / tau_A) + amp_B * np.exp(-t / ta... | 998af4a236b0d11893319e59401bada9e70f9957 | 3,631,846 |
def cross_entropy_sequence_loss(logits, targets, sequence_length):
"""Calculates the per-example cross-entropy loss for a sequence of logits and
masks out all losses passed the sequence length.
Args:
logits: Logits of shape `[T, B, vocab_size]`
targets: Target classes of shape `[T, B]`
sequence_len... | 78ee272b2e6fe7b7f02579fdd0e9f90aab936e76 | 3,631,847 |
def get_common_interior_polygons(polygon, list_of_polygons):
"""Check if polygon resides inside any polygon
in the list_of_polygons.
Parameters
----------
polygon: matplotlib.Polygon
Returns
-------
list_of_common_polygons: list
A filtered list of ids
... | 489cd8afd61ce8431f253c445266c14b3f8b50f6 | 3,631,848 |
def handle_image_size(input_image: np.ndarray, dimension: tuple):
"""
:param input_image:
:param dimension:
:return:
"""
assert input_image.ndim == 3, (
"Image should have 3 dimension '[HxWxC]'" "got %s",
(input_image.shape,),
)
assert len(dimension) == 2, (
"'di... | d4327548130c86e7ffdfa34ad3ed3e72bb510eb4 | 3,631,849 |
def netconvecs_to_listoflists(t_vec, id_vec, minmax=None):
"""
Convert data from NetCon.record(tvec, idvec) vectors into a dict
where the keys of the dict are the ids and the value is a list of
timestamps associated with that id.
:param tvec: Timestamp vector.
:param idvec: Associated ids o... | e3ed2752c963de97379ce5fac7e7adb4bec2e334 | 3,631,850 |
import random
def log_roulette_selection_method(fx_input, optimization_type_input, n_individuals_input, seed_input):
"""Roulette selection method with a twist. Here the evaluation value is processed with a log function. It reduces the difference between individuals, which increases population diversity."""
r... | 72a440402b0af2b1a6dcec8aba1116094bc87ecd | 3,631,851 |
import torch
def evaluate(attention_model,x_test,y_test):
"""
cv results
Args:
attention_model : {object} model
x_test : {nplist} x_test
y_test : {nplist} y_test
Returns:
cv-accuracy
"""
attent... | 3216f6092c61f35bb74140ac51ef635f53691e19 | 3,631,852 |
def reorder_cols_df(df, cols):
"""Reorder the columns of a DataFrame to start with the provided list of columns"""
cols2 = [c for c in cols if c in df.columns.tolist()]
cols_without = df.columns.tolist()
for col in cols2:
cols_without.remove(col)
return df[cols2 + cols_without] | 917b0084ba34f8e1b1fc697c4838ff8404a2fc90 | 3,631,853 |
from typing import Union
from pathlib import Path
from typing import Optional
def uri_resolve(base: Union[str, Path], path: Optional[str]) -> str:
"""
Backport of datacube.utils.uris.uri_resolve()
"""
if path:
p = Path(path)
if p.is_absolute():
return p.as_uri()
if isi... | d280456a0071edd1cfce60a8d3b17c193c9ba446 | 3,631,854 |
def preprocess_report(rep, rep2):
""" Processes lists containing report grades """
rv = np.asarray([rep], dtype="float32")
rv2 = np.asarray([rep2], dtype="float32")
return rv, rv2 | 628659ba90af516497b005986854b86dde3c6edb | 3,631,855 |
from typing import Any
async def async_check_srv_record(hass: HomeAssistant, host: str) -> dict[str, Any]:
"""Check if the given host is a valid Minecraft SRV record."""
# Check if 'host' is a valid SRV record.
return_value = None
srv_records = None
try:
srv_records = await aiodns.DNSResol... | 40aef8e2446669040975a5d15c4be2c28e08b6e1 | 3,631,856 |
def add_923_heat_rate(df):
"""
Small function to calculate the heat rate of records with fuel consumption and net
generation.
Parameters
----------
df : dataframe
Must contain the columns net_generation_mwh and
fuel_consumed_for_electricity_mmbtu
Returns
-------
dat... | 907ac6ba469a65dfe25a84f7498e66b1e0535d19 | 3,631,857 |
def get_local_bounding_box_min_max():
"""Gets an Axis-Aligned Bounding Box for the canonical die model, in local coordinate space."""
return np.array([[-0.49946,-0.48874,-0.52908],
[0.50094,0.51166,0.47132]]).T | be707edf6e1d92726a55f355bbe0052323b9c27b | 3,631,858 |
def get_inception_features(inputs, inception_graph, layer_name="pool_3:0"):
"""Compose the preprocess_for_inception function with TFGAN run_inception."""
preprocessed = preprocess_for_inception(inputs)
return tfgan_eval.run_inception(
preprocessed,
graph_def=inception_graph,
output_tensor=layer... | ea6d8772291bb3e6b156f4905e2f22bb1539870c | 3,631,859 |
def v4_multimax(iterable):
"""Return a list of all maximum values.
Bonus 1 - on short solution.
"""
try:
max_item = max(iterable)
except ValueError:
return []
return [
item
for item in iterable
if item == max_item
] | fddeae328993fa77a0b73ab55c4e53a88b42b39c | 3,631,860 |
def sig_beg_to_adj_ground_ht(ds):
"""
Height in meters from GLAS signal beginning to whichever of the two lowest peaks has greater amplitude.
"""
return get_heights_from_distance(
ds, top_metric='sig_begin_dist', bottom_metric='adj_ground_peak_dist'
) | d83aeb47ac7df081f310dc2e445d232326b099b2 | 3,631,861 |
from typing import List
def tree_to_formula(tree: DecisionTreeClassifier, concept_names: List[str], target_class: int) -> str:
"""
Translate a decision tree into a set of decision rules.
:param tree: sklearn decision tree
:param concept_names: concept names
:param target_class: target class
:... | dc0c1d03aab3f5ef458f74665a5a203a53db87ee | 3,631,862 |
import os
def update_user_in_cache(user):
"""Get all users and create Cache files for each user."""
logger.info("Creating user in cache files.")
if ENABLE_USER_CACHING:
try:
if not os.path.exists(USER_CACHE_DIR):
os.makedirs(USER_CACHE_DIR)
# Create file f... | 769fbc5f8035943352b951181cd0da30da4c95a3 | 3,631,863 |
from datetime import datetime
def datefix(datestr):
""" transform string into a python datetime object
handle mm/dd/yy or mm/dd/yyyy or dashes instead of slashes """
fix = datestr.replace('-','/')
if len(fix) > 4:
try:
return datetime.strptime(fix, "%m/%d/%y")
except V... | 2cb728dfcec24b350d63a79fc3964d3325780b6a | 3,631,864 |
import math
def vector_angle(v1: Vector3D, v2: Vector3D) -> float:
"""
Calculate the angle between two given vectors.
Keyword arguments:
v1 -- First vector
v2 -- Second vector
"""
v1_n = normalize_vector(v1)
v2_n = normalize_vector(v2)
return math.acos(dot_product(v1_n, v2_n) / (v... | 694b5d49140ae409166bc55c7ecf6c19db8fe5bf | 3,631,865 |
from typing import Counter
def removed_mirrored_association(left_assoc, right_assoc):
"""
Remove the mirrored association (associations like (a, b) and (b, a)) that occurs in the intra-night associations.
The column id used to detect mirrored association are candid.
We keep the associations with the s... | 1f3bcd16c0f8321ba43d2f47163f59d7c0b12f26 | 3,631,866 |
import tqdm
import time
def sample_trajectory(smc_N, alpha, beta, radius, n_samples, seq_dist,
jt_traj=None, debug=False, reset_cache=True):
""" A particle Gibbs implementation for approximating distributions over
junction trees.
Args:
smc_N (int): Number of particles in SMC... | 6ee321c6cfe183c562fbb9b3d7c78a8ef7d36992 | 3,631,867 |
import re
def valgrind_supports_exit_early():
"""Checks if we support early exit from valgrind"""
version = helpers.run_subprocess(['valgrind', '--version'])
match = re.match(r'valgrind-(\d)\.(\d+).*', version)
if match:
return int(match.group(2)) >= 14
return False | a33d9795587b2f678c88d58ec058aead215b36fb | 3,631,868 |
import csv
import sys
def read_rows(input_file, expected_fields):
"""Read the input_file as a CSV; validate that the expected_fields are
present. Sys.exit if not
:return: pair of list of dicts (rows in the CSV), and a list of headers
found in the input_file"""
reader = csv.DictReader(input_file)
... | ab5a8d08a792db43e4569ac71417ff53783dba94 | 3,631,869 |
from typing import List
import hashlib
def document_etag(value: dict, ignore_fields: List[str] = None) -> str:
"""Computes and returns a valid ETag for the input value."""
h = hashlib.sha1()
h.update(dumps(value, sort_keys=True).encode("utf-8"))
return h.hexdigest() | 5415ee356f610728d764139eb1813f987f1bcce3 | 3,631,870 |
def answer(request):
"""
Save the answer.
GET parameters:
html:
turn on the HTML version of the API
BODY
json in following format:
{
"answer": #answer, -- for one answer
"answers": [#answer, #answer, #answer ...] -- for multiple ans... | 61ed14331bd682cdf85b428dfb89695c35237087 | 3,631,871 |
def valid_client_model(initialize_db):
"""
A fixture for creating a valid client model.
Args:
initialize_db (None): initializes the database and drops tables when
test function finishes.
"""
return Client(username='Leroy Jenkins', avatar_url='').save() | cc9a7d3bea9f50a5250d1fe98781af5441fba492 | 3,631,872 |
def merge_features(df: pd.DataFrame)-> pd.DataFrame:
"""
Merges features that estimate the same thing
"""
# kelvin conversions
df['station_max_temp_c'] += 273.15
df['station_min_temp_c'] += 273.15
df['station_avg_temp_c'] += 273.15
df = (df
.fillna(method = 'backfill')
... | 33c085a0b4defddcfc3310644ce371a9532dea1b | 3,631,873 |
def threatActorSTIX(adversaries):
"""
Parse the adversaries key to convert it to STIX
"""
adversariesList = []
for adv in adversaries: adversariesList.append(ThreatActor(name="%s"%(adv))) if len(adversaries) >= 1 else adversariesList.append(ThreatActor(name="%s"%(adversaries[0])))
return adversariesList | 723224b0c271ea0c7b9cedb99cfd27557cd9a5f1 | 3,631,874 |
import scipy
def merge_channels(data, sampling_rate, filter_data: bool = True):
"""Merge channels based on a running maximum.
Args:
data (ndarray): [samples, channels]
sampling_rate (num): in Hz
Returns:
ndarray: merged across
"""
data = np.array(data) # ensure data is a... | 6d6df0ef40ee350786b6ef19396b889f08e945cc | 3,631,875 |
def maximalEigenvector(A):
""" using the eig function to compute eigenvectors """
n = A.shape[1]
_,v = np.linalg.eig(A)
return abs(np.real(v[:n,0])/np.linalg.norm(v[:n,0],1)) | b45b9a1b7b44b98575c9ca282cdb3e4ef1cb58f2 | 3,631,876 |
from operator import sub
def remove_hyperlinks(text):
"""Remove hyperlinks from text."""
# If text is empty, return None.
if not text: return None
# If is tokenized, merge tokens.
if is_tokenized(text):
was_tokenized = True
normalized_text = merge_tokens(text)
else:
wa... | 5b1ee46644cb12365b4f4939cfb0ac6d00eebcea | 3,631,877 |
import os
import copy
def read_struct_file(struct_file, return_type=GeoStruct):
"""read an existing PEST-type structure file into a GeoStruct instance
Args:
struct_file (`str`): existing pest-type structure file
return_type (`object`): the instance type to return. Default is GeoStruct
R... | d7bed84565e48b7ee817ecab8ba62e2b988b4023 | 3,631,878 |
def _check_nx(path):
"""NX - This mitigation technique attempts to mark
as the binary as non-executable memory. E.g. An attacker
can't as easily fill a buffer with shellcode and jump
to the start address. It is common for this to be disabled
for things like JIT interpreters.
"""
headers = _e... | 1dfd1c14e7b49e211c7a6a42e10bd3201dc5262b | 3,631,879 |
def verify_auth(username, password):
""" Verify the HTTP Basic Auth credentials """
config = app.config
return username == config['USERNAME'] and password == config['PASSWORD'] | 18960b0355f158b601e4097694eb1b417715227c | 3,631,880 |
def mat_list_to_rf_array(mats_list: list) -> (np.ndarray, dict):
"""Make an RF array from a list of mats"""
rf_array = np.array(
[open_rf(x) for x in mats_list]
)
parameters = open_parameters(mats_list[0])
return rf_array, parameters | 3b6a84b76a096eabe0c14183d23a795da8c742f1 | 3,631,881 |
def show_options(last_row):
"""
Show the options. The user can choose what to do.
last_row: the last row in the worksheet (list).
"""
while True:
choose = input('What to do? (Q)uit/(L)ist/(N)ew [N]: ')
if choose is '' or choose.lower()[0] is 'n':
return True
eli... | 1d20d5de02f6011cfe4d4f635d43ee097cfc6568 | 3,631,882 |
def is_pilot_snipe(sortie):
"""
A pilot snipe is when a plane goes down because the pilot gets killed, and not because the aircraft is crtically
damaged. Currently, in the logs, a pilot snipe looks rather similar to a normal death. Even in a pilot snipe,
the logs think the aircraft gets shotdown before ... | 112770e8dceb339af7f67bb074739c4066b8121d | 3,631,883 |
import os
def merge_meta(meta: dict) -> dict:
"""
merge data for api: get meta config.
"""
modules = meta.pop(CONFIG_MODULE)
_meta = {meta.pop(CONFIG_NAME): meta}
for meta_name, detail in modules.items():
if SOURCE_META in detail.keys():
# meta config
file_path ... | c2f76d82881a4b7fb49be4525734c2e984a35bcb | 3,631,884 |
import os
def load_messages(language):
"""Load translation messages for given language from all `setup_wizard_requires`
javascript files"""
frappe.clear_cache()
set_default_language(get_language_code(language))
frappe.db.commit()
m = get_dict("page", "setup-wizard")
for path in frappe.get_hooks("setup_wizard_... | 1e778ecf5ec28cc16fc031529978d368e79ba1b7 | 3,631,885 |
def change_lang(request):
"""
Change current documentation language.
"""
lang = request.GET.get('lang_code', 'en')
response = redirect('/')
portal_helper.set_preferred_language(request, response, lang)
return response | 8b9ffce5b15159d3dad0c565d3caac8ed2a4fd71 | 3,631,886 |
import re
def cleanHtml(sentence):
"""
remove all Html canvas from the sentence
:param sentence {str} sentence
:return:
{str}: sentence without html canvas
"""
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, ' ', str(sentence))
return cleantext | 1a3edcd7227468f8f3102525538a728a9bc93fc0 | 3,631,887 |
def simple_decoder_fn_train(encoder_state, name=None):
""" Simple decoder function for a sequence-to-sequence model used in the
`dynamic_rnn_decoder`.
The `simple_decoder_fn_train` is a simple training function for a
sequence-to-sequence model. It should be used when `dynamic_rnn_decoder` is
in the training ... | e23c0d47096b2234e670ce7720f1936c4ee7b7b7 | 3,631,888 |
def explain_point_local(data_row, neighbors, oversampled_data, model_features, categorical_features, numeric_features, budget=999, show_pos_neg = False):
"""
Provides explanations on each point in the selected subset for local explanations.
Parameters:
-----------------
data_row: integer, the i... | dd4ef3aafbe7ac97d4bead509e7f746554b4f015 | 3,631,889 |
def pots_scan(n_src, ele_lims, true_csd_xlims,
total_ele, ele_pos, R_init=0.23):
"""
Investigates kCSD reconstructions for unitary potential on different
electrodes
Parameters
----------
n_src: int
Number of basis sources.
ele_lims: list
Boundaries for electrod... | 442b093422907801858efeba6e493ebf0c8e82c6 | 3,631,890 |
from typing import Any
def add_nav_entry(mkdocs_settings, nav_entry: NavEntry) -> Any:
"""
Add an additional entry to the Nav in mkdocs.yml
Args:
mkdocs_settings (): The mkdocs settings to update.
nav_entry (NavEntry): The NavEntry to add
Returns:
The updated mkdocs_settings
... | 06899c76b1788096b88237f3f12f6ef7cd786191 | 3,631,891 |
import re
def is_guid(value):
"""
проверяет на наличие только [a-zA-z/-]
"""
if re.match("^[A-Za-z0-9_-]*$", value):
return value
return None | ca9c84ebfe271d93bd7c8d3043f8dd1849fb3239 | 3,631,892 |
def load_scikit_learn_model(model_uri):
"""
Load a scikit-learn model from a local file.
:param model_uri: The location, in URI format, of the aiflow model, for example:
- ``/Users/aiflow/path/to/local/model``
- ``relative/path/to/local/model``
... | d10d22ec1f5eb659a18c4720860e72aa1a03a387 | 3,631,893 |
def epimorphism_in_laurent(tri, angle, cycles, ZH):
"""
The argument cycles specifies a group epimorphism from the
manifold to the filled manifold. This function returns the image
of the generators of the group ring under the induced epimorphism.
"""
n = tri.countTetrahedra()
S,U,V = faces_... | 8563c400ecc9420682144300be1a990df531b861 | 3,631,894 |
def merge_config(a, b):
"""Merges config b in a."""
for key, b_value in b.items():
if not isinstance(b_value, dict):
a[key] = b_value
else:
a_value = a.get(key)
if a_value is not None and isinstance(a_value, dict):
merge_config(a_value, b_value... | 2e194d9b19c2270968cd205062b4d3ec992cfced | 3,631,895 |
def tsi_moving_average(df, periods=7):
"""Function calculating Moving Average (MA) for TSI
Args:
df (pandas.DataFrame): Quotes with TSI values
periods (int, optional): The number of periods from which MA is calculated. Defaults to 7.
Returns:
pandas.DataFrame: Quotes extended by th... | 5491dc1a82b26d152baaa7d9a53048d63a658f69 | 3,631,896 |
def fit_index(dataset, list_variables):
""" Mapping between index and category, for categorical variables
For each (categorical) variable, create 2 dictionaries:
- index_to_categorical: from the index to the category
- categorical_to_index: from the category to the index
Parameters
---... | 7b8c73a5d23de2e537c1f28078d2e032095d6b1c | 3,631,897 |
def theoretical_motion(input, g):
"""
Compute the theoretical projectile motion.
Args:
input: ndarray with shape (num_samples, 3) for t, v0_x, v0_z
g: gravity acceleration
Returns:
theoretical motion of x, z.
"""
t, v0_x, v0_z = np.split(input, 3, axis=-1)
x = v0_x ... | 200a2430a79239f21e22db07feaf315d8919f21b | 3,631,898 |
from typing import List
import requests
def list_analyses() -> List[str]:
"""Get a list of all supported analyses."""
response = requests.get(_url("/info/analyses"))
assays = response.json()
return assays | 8f14ed36d572ca222df53dfa2fe8605b2975db48 | 3,631,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.