content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def softmax_logits_kld(ops, p_logits, q_logits, keepdims=False):
"""
Compute the KL-divergence between two softmax categorical distributions
via logits. The last dimension of `p` and `q` are treated as the
softmax dimension, and will be reduced for computing KL-divergence.
.. math::
\\ope... | b8566c611e6dd01374d1239bcdab81e2c371fe11 | 14,500 |
def E_inductive_from_ElectricDipoleWholeSpace(
XYZ,
srcLoc,
sig,
f,
current=1.0,
length=1.0,
orientation="X",
kappa=1.0,
epsr=1.0,
t=0.0,
):
"""
Computing Inductive portion of Electric fields from Electrical Dipole in a Wholespace
TODO:
Add descri... | bc98b693771a535f74f693ee097b682632f4fbf8 | 14,501 |
import pytz
from datetime import datetime
def str2posix(timelist):
""" This will take a list of strings with the date along with a start and
end time and make a list with the posix times.
Inputs
timelist - A list of strings with the data followed by two times.
The date for ... | 476fc634b967419818ef41d9ff4b21f9e4f76ff1 | 14,502 |
def keys_verif(verif: bool = True):
"""
Used to verify existence of private or/and public keys of ElGamal.
"""
print("\nChecking the presence of keys in the system....")
if isFileHere("public_key.kpk", config.DIRECTORY_PROCESSING):
# from cipher.asymmetric import elGamal as elG
p... | 824b8c31ad9cc0fb1b2ef7eef585e47c2e338a8b | 14,503 |
def r2(ground_truth, simulation, join='inner', fill_value=0):
"""
R-squared value between ground truth and simulation
Inputs:
ground_truth - ground truth measurement (data frame) with measurement in the "value" column
simulation - simulation measurement (data frame) with measurement in the "value" ... | 75d78e575bef0a59620cbdbf1992396a8edd0929 | 14,504 |
import os
def add_team_batting_stats(df, years, batter_metrics):
"""
"""
gids = list(set(df['gameId']))
bat_saber_paths = [
CONFIG.get('paths').get('batter_saber') + gid + \
"/batter_saber_team.parquet" for gid in
os.listdir(CONFIG.get('paths').get('batter_saber'))
]
cu... | bdce73590dfe1a0ee7883ce4c65544b612298704 | 14,505 |
def depth_analysis_transform_1(rgb_tensor, depth_tensor, num_filters):
"""Builds the analysis transform."""
with tf.variable_scope("analysis"):
# --------------------------------------- rgb branch
with tf.variable_scope("layer_0"):
layer = tfc.SignalConv2D(
num_filters, (9, 9), corr=True, s... | 27637e35619f61e5da2b965392a39b38cdfb6a29 | 14,506 |
def boxPlot(med, quartiles, minmax, mean=None, outliers=None, name='boxplot', horiz=True, offset=0,
legendGroup='boxplot', showleg=False, plot=False, col='blue', width=8):
"""
Makes very light plotly boxplot. Unlike theirs, this can take externally calc'd values rather than just data to make it go m... | ba4b746bc5129cef758a01a26633d0fcf0ab3245 | 14,507 |
def hub_quantile_prediction_dict_validator(target_group_dict, prediction_dict):
"""
Does hub prediction_dict validation as documented in `json_io_dict_from_quantile_csv_file()`
"""
error_messages = [] # return value. filled next
valid_quantiles = target_group_dict['quantiles']
prediction_quanti... | ec13824557ef9533d7c4a777daadd07414752767 | 14,508 |
def allclose_periodical(x, y, a, b, atol=1e-10):
"""
Checks np.allclose(x,y), but assumes both x and y are periodical with respect to interval (a,b)
"""
assert(len(x) == len(y))
period = b-a
x_p = np.remainder(x-a,period) # now in 0, b-a
y_p = np.remainder(y-a,period)
return all(np.isclo... | bd1c58a362a9c3926bffbcb0a27e355bfc982955 | 14,509 |
import operator
def get_categories_to_rows_ratio(df):
"""
Gets ratio of unique categories to number of rows
in the categorical variable; do this for each categorical
variable
:param df: pd.DataFrame
:return: array of tuples
"""
cat_columns = get_categorical_variable_names(df)
rati... | 2734b898b6c6538b65d54709be617a6dd393c3da | 14,510 |
def _width_left_set(size: int, lsize: int, value: list, fmt: str, meta: dict) -> dict:
"""Width setting of paragraph with left repositioning."""
return Plain([RawInline(fmt, '<p style="text-align:left !important;'
'text-indent:0 !important;'
'position:rela... | 6042b0d255fe804d7423b5e49dd700bd7f0b9bdf | 14,511 |
def GetMappingKeyName(run, user):
"""Returns a str used to uniquely identify a mapping."""
return 'RunTesterMap_%s_%s' % (run.key().name(), str(user.user_id())) | b4eb80ca5f084ea956f6a458f92de1b85e722cda | 14,512 |
def get_invitee_from_table(invite_code: str, table):
"""
Get a dictionary of the stored information for this invite code.
Args:
invite_code: The invitation code to search for
table: A DynamoDB table for querying
Returns:
A dictionary of information stored under the invite code
... | 1377e20a58174f69d8984e36aab3426c0eb392bd | 14,513 |
import math
def d_beta_dr(radius, beta, mass_r, epsilon, pressure, h_r):
""" d_beta_dr """
return 2. * (1 - 2 * (mass_r/radius)) ** (-1.) * h_r * \
( -2. * math.pi * (5*epsilon + 9*pressure + f(epsilon, pressure)) + (3/radius**2.) + 2*(1 - 2 * mass_r / radius)**(-1) * \
((mass_r/radius) + 4 * ... | 0880439516b70e07c01be3164a3c030bb9deeaca | 14,514 |
import json
def score(capstone, student_api):
"""
Calculates the score of the students' API model
:param student_api: StudentApi object
:return: score as a float
"""
# Check which simulators have datapoints with outcomes outcomes
simulator_ids = []
for simulator in capstone.simulators... | bb4f545835f480c9fac97acc698daef08a7684f2 | 14,515 |
def clean_lhdf(df: pd.DataFrame):
"""
Removes unneccessary columms from the location history data frame and computes new required columns
Parameters
----------
df : pandas.DataFrame
DataFrame to process
Returns
-------
Copy of `df`, altered the following way:
* Colums remov... | 86280a333082e964553030d4e586a267e93edfae | 14,516 |
def year_from_operating_datetime(df):
"""Add a 'year' column based on the year in the operating_datetime.
Args:
df (pandas.DataFrame): A DataFrame containing EPA CEMS data.
Returns:
pandas.DataFrame: A DataFrame containing EPA CEMS data with a 'year'
column.
"""
df['year']... | 1c7bbc6465d174465151e5e777671f319ee656b7 | 14,517 |
def is_thrift(target):
"""Returns True if the target has thrift IDL sources."""
return isinstance(target, JavaThriftLibrary) | 4a56cf5cec923933fec628173cb2ab1a122b0127 | 14,518 |
def get_instance(value, model):
"""Returns a model instance from value. If value is a string, gets by key
name, if value is an integer, gets by id and if value is an instance,
returns the instance.
"""
if not issubclass(model, db.Model):
raise TypeError('Invalid type (model); expected subcla... | 85544b057e3e6c82730ba743a625610c55b48ff0 | 14,519 |
def clean_infix(token, INFIX):
"""
Checks token for infixes. (ex. bumalik = balik)
token: word to be stemmed for infixes
returns STRING
"""
if check_validation(token):
return token
for infix in INFIX_SET:
if len(token) - len(infix) >= 3 and count_vowel(token[len(infix):]) >= 2:
if token[0] == token[... | fdd8e90bdea14ca2344dd465622bd2e79905e4fe | 14,520 |
def seq_to_encoder(input_seq):
"""从输入空格分隔的数字id串,转成预测用的encoder、decoder、target_weight等
"""
input_seq_array = [int(v) for v in input_seq.split()]
encoder_input = [PAD_ID] * \
(input_seq_len - len(input_seq_array)) + input_seq_array
decoder_input = [GO_ID] + [PAD_ID] * (output_seq_len - 1)
e... | 9a9203aa9e3005acd7d55516fbe8c5710ea25ae3 | 14,521 |
def getMergers(tree, map_strain2species, options):
"""merge strains to species.
returns the new tree with species merged and
a dictionary of genes including the genes that have been merged.
Currently, only binary merges are supported.
"""
n = TreeTools.GetSize(tree) + 1
all_strains = map_... | 48fb083027e00d93754ee4064edbc268ea4047a5 | 14,522 |
def convolve_with_gaussian(
data: np.ndarray, kernel_width: int = 21
) -> np.ndarray:
"""
Convolves a 1D array with a gaussian kernel of given width
"""
# create kernel and normalize area under curve
norm = stats.norm(0, kernel_width)
X = np.linspace(norm.ppf(0.0001), norm.ppf(0.9999), k... | 63949d9c235a1a467858077de8dda8455c139551 | 14,523 |
def post_netspeed(event, context):
"""
Speed test data ingestion handler
"""
return process_reading(event['query'], NETSPEED_SQL) | 8414fe3608b7433a177f0c8c54cce61d01339b67 | 14,524 |
import json
def notify_host_disabled(token, host_name):
"""
Notify OpenStack Nova that a host is disabled
"""
url = token.get_service_url(OPENSTACK_SERVICE.NOVA, strip_version=True)
if url is None:
raise ValueError("OpenStack Nova URL is invalid")
# Get the service ID for the nova-com... | 904c951a37b8b84df4aa48951c424686a123ff30 | 14,525 |
def compute_moments_weights_slow(mu, x2, neighbors, weights):
"""
This version exaustively iterates over all |E|^2 terms
to compute the expected moments exactly. Used to test
the more optimized formulations that follow
"""
N = neighbors.shape[0]
K = neighbors.shape[1]
# Calculate E[G]... | 5a2984174f366a34f16490bb7b9252ec4eaf08db | 14,526 |
import functools
def sum_fn(fun, ndims=0):
"""Higher order helper for summing the result of fun."""
@functools.wraps(fun)
def wrapped(*args):
batch_loglik = fun(*args)
return jnp.sum(
batch_loglik.reshape((-1,) +
batch_loglik.shape[-ndims +
... | 521a4084fee84f16de5714010be9528296f8b231 | 14,527 |
from typing import Optional
def get_control_policy_attachments(language: Optional[str] = None,
output_file: Optional[str] = None,
policy_type: Optional[str] = None,
target_id: Optional[str] = None,
... | cfa39ca8926c281151b5ae06ef89ce865dfd0af4 | 14,528 |
def get_gdb(chip_name=None,
gdb_path=None,
log_level=None,
log_stream_handler=None,
log_file_handler=None,
log_gdb_proc_file=None,
remote_target=None,
remote_address=None,
remote_port=None, **kwargs):
"""
set to != N... | 15dc451b9cbf21c5f96279a17449e4169e0bae83 | 14,529 |
import math
from datetime import datetime
def parse_source_gpx_file(inp_path, source):
"""Parse a GPX file having the following structure:
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance... | 22a3c724f27a29afbb5a69fd36dc1ed618a6c8b3 | 14,530 |
from typing import Callable
from typing import Awaitable
def check(func: Callable[..., Awaitable[Callable[[CommandContext], Awaitable[bool]]]]) -> Check:
"""
A decorator which creates a check from a function.
"""
return Check(func) | 2354eef311e1867333ade47996fb37cee07ce4cd | 14,531 |
def service_c(request):
""" Renders the service chair page with service submissions """
events = ServiceEvent.objects.filter(semester=get_semester())
submissions_pending = ServiceSubmission.objects.filter(semester=get_semester(), status='0').order_by("date")
submissions_submitted = ServiceSubmission.ob... | 96d9b281c562a0ddb31d09723012cc9411c4ff09 | 14,532 |
def get_tank_history(request, tankid):
"""
Returns a response listing the device history for each tank.
"""
# Sanitize tankid
tankid = int(tankid)
# This query is too complex to be worth constructing in ORM, so just use raw SQL.
cursor = connection.cursor()
cursor.execute("""\
SE... | 39c21c9761ff0e40e1c1f8904cf9b9881faf13ed | 14,533 |
import inspect
def get_absolute_module(obj):
"""
Get the abolulte path to the module for the given object.
e.g. assert get_absolute_module(get_absolute_module) == 'artemis.general.should_be_builtins'
:param obj: A python module, class, method, function, traceback, frame, or code object
:retu... | ea2c85d9ba90414cddce00dcc5ed092b8c6777a2 | 14,534 |
def parse_c45(file_base, rootdir='.'):
"""
Returns an ExampleSet from the
C4.5 formatted data
"""
schema_name = file_base + NAMES_EXT
data_name = file_base + DATA_EXT
schema_file = find_file(schema_name, rootdir)
if schema_file is None:
raise ValueError('Schema file not found')
... | 14d651a48c2fe65ad68c441722c4c39854efef2a | 14,535 |
import torch
def to_numpy(tensor: torch.Tensor):
"""
Convert a PyTorch Tensor to a Numpy Array.
"""
if tensor is None:
return tensor
if tensor.is_quantized:
tensor = tensor.dequantize()
return tensor.cpu().detach().contiguous().numpy() | ed6bd50ef5db30b3df1304a0152998f2f27750c6 | 14,536 |
from flask_sqlalchemy import _wrap_with_default_query_class, SQLAlchemy
def initialize_flask_sqlathanor(db):
"""Initialize **SQLAthanor** contents on a `Flask-SQLAlchemy`_ instance.
:param db: The
:class:`flask_sqlalchemy.SQLAlchemy <flask_sqlalchemy:flask_sqlalchemy.SQLAlchemy>`
instance.
:t... | 565c010a49e9d0ac2e82b40803b4f0871b526177 | 14,537 |
def add_vcf_header( vcf_reader ):
"""
Function to add a new field to the vcf header
Input: A vcf reader object
Return: The vcf reader object with new headers added
"""
# Metadata
vcf_reader.metadata['SMuRFCmd'] = [get_command_line()]
# Formats
vcf_reader.formats['VAF'] = pyvcf.parse... | 36e5819de6c09c7e60638b183bfe415fc19361db | 14,538 |
def get_seats_percent(election_data):
"""
This function takes a lists of lists as and argument, with each list representing a party's election results,
and returns a tuple with the percentage of Bundestag seats won by various political affiliations.
Parameters:
election_data (list): A list of l... | a131d64747c5c0dde8511e9ec4da07252f96a6ec | 14,539 |
def get_player_gamelog(player_id, season, season_type='Regular Season', timeout=30):
"""
Coleta de histórico departidas de um determinado jogador
em uma determinada temporada, considerando ainda um
tipo específico de temporada (pré-season, temporada regular
ou playoffs).
Parâmetros
--------... | d21132df8a4f72055f37ef7039427f42ce03610e | 14,540 |
import re
def unbound_text_to_html5(text, language=None):
"""
Converts the provided text to HTML5 custom data attributes.
Usage:
{{text|unbound_text_to_html5:"Greek"}}
"""
# If the language is English, then don't bother doing anything
if language is not None and language.lower() ... | 1fe50c4844e126395c1aa1e8d5ba464217003557 | 14,541 |
def sort_points(points):
"""Sorts points first by argument, then by modulus.
Parameters
----------
points : array_like
(n_points, 3)
The points to be sorted: (x, y, intensity)
Returns
-------
points_sorted : :class:`numpy.ndarray`
(n_points, 3)
The sorted po... | 3d5ae7cdfa33abba906cefaf3cd1ab0ab5899e32 | 14,542 |
def get_pairs(scores):
"""
Returns pairs of indexes where the first value in the pair has a higher score than the second value in the pair.
Parameters
----------
scores : list of int
Contain a list of numbers
Returns
-------
query_pair : list of pairs
This contains a list of pairs of indexes in ... | 1d4bf17dffb7ec8b934701254448e5a7dfe41cf9 | 14,543 |
def make():
"""Make a new migration.
Returns:
Response: json status message
"""
response = None
try:
with capture_print(escape=True) as content:
current_app.config.get('container').make('migrator').make(request.form['name'])
response = {'message': content.get_te... | 24524cc1906f621e9e927d3e0b7265b65ab8ebe5 | 14,544 |
def find_files(args, client):
""" Get a list of all the objects to process"""
objects = []
continuation_token = 'UNSET'
while continuation_token:
if continuation_token == 'UNSET':
object_list = client.list_objects_v2(Bucket=args['bucket'],Prefix=args['prefix'])
else:
... | 784e5514539d794854efbe910f2a0039002c0af9 | 14,545 |
from typing import Union
import os
from typing import Optional
from typing import List
import filecmp
def are_dirs_equal(
dir1: Union[str, os.PathLike],
dir2: Union[str, os.PathLike],
ignore: Optional[List[str]] = None,
) -> bool:
"""
Compare the content of two directories, recursively.
:para... | a6923f280d2b1d73f4b121388febb23027dc2d47 | 14,546 |
import codecs
import traceback
def writeCSV(info, resultFile):
"""
Write info line to CSV
:param info:
:return:
"""
try:
with codecs.open(resultFile, 'a', encoding='utf8') as fh_results:
# Print every field from the field list to the output file
for field_pretty... | e1ec45c308b1f18c1633f3213166a8edaf7122b2 | 14,547 |
def generate_hmac(str_to_sign, secret):
"""Signs the specified string using the specified secret.
Args:
str_to_sign : string, the string to sign
secret : string, the secret used to sign
Returns:
signed_message : string, the signed str_to_sign
"""
message = str_to_sign.... | c773cb1f470f0f52934758e7f66fe01047419cbd | 14,548 |
def interpolate_scores(coords: np.array, scores: np.array, coord_range: tuple, step: float = 0.001) -> np.array:
"""
Given a coord_range and values for specific coords - interpolate to the rest of the grid
Args:
coords: array of lons and lats of points that their values are known
scores: arr... | 2ed5660191f01018344e9b55af372f10133bc6a9 | 14,549 |
def remove_blank_from_dict(data):
"""Optimise data from default outputted dictionary"""
if isinstance(data, dict):
return dict(
(key, remove_blank_from_dict(value))
for key, value in data.items()
if is_not_blank(value) and is_not_blank(remove_blank_from_dict(value))
... | ae77d0b5b9a1cffdd1832df3a5513cc79e600138 | 14,550 |
from typing import List
from typing import Dict
import re
import json
import subprocess
def upload_to_database(
database_secrets_manager_arn: str, user_mapping: List[Dict]
) -> str:
"""Uploads data from disk to an RDS postgres instance. Uses the
provided user_mapping to replace the user subs of data in th... | 061fe70844ab5ed6136d6c0b087ed91405aae280 | 14,551 |
import os
import ssl
import urllib
def new_client(
dockerd_url=None,
tls=False,
tls_verify=False,
cert_path=None,
timeout=None,
):
"""
Return a newly configured Docker client.
"""
_dockerd_url = dockerd_url
if not _dockerd_url:
_dockerd_url = os.gete... | 8a9bf9b09881fa6daac7bf4aedb2610c92d084f4 | 14,552 |
def merge_mosaic_images(mosaic_dict, mosaic_images, orig_images, Y_orig=None):
""" Merge the list of mosaic images with all original images.
Args:
mosaic_dict: Dictionary specifying how mosaic images were created, returned from make_mosaic
mosaic_images: List of all mosaic images returned from ... | d16875462c09b671db785ec101eb09028b1a7cbe | 14,553 |
def show2D(dd, impixel=None, im=None, fig=101, verbose=1, dy=None, sigma=None, colorbar=False, title=None, midx=2, units=None):
""" Show result of a 2D scan
Args:
dd (DataSet)
impixel (array or None)
im (array or None)
"""
if dd is None:
return None
extent, g0, g1,... | d9560e2dd54ed8daf8450e2db8e1f5d8357a601c | 14,554 |
def get_job(api_key, jq_id):
"""
Fetch a job and its status
:param api_key: user id of the client
:param jq_id: job queue id
:return: job queue id
"""
if Auth.verify_auth_key(api_key):
if Auth.verify_job(api_key, jq_id):
return trigger.get_job(jq_id)
return abort(400) | f323386e530e354f52bcbcc6301c5fb1af4e4767 | 14,555 |
def contour_to_valid(cnt, image_shape):
"""Convert rect to xys, i.e., eight points
The `image_shape` is used to to make sure all points return are valid, i.e., within image area
"""
# rect = cv2.minAreaRect(cnt)
if len(cnt.shape) != 3:
assert 1 < 0
rect = cnt.reshape([cnt.shape[0], cnt.s... | a4f85d77c0805903b220d3670edc5db05ea001ed | 14,556 |
def search(datafile, query, bool_operator):
"""
Queries on a set of documents.
:param datafile: The location of the datafile as a pathlib.Path
:param query: the query text
:param bool_operator: the operator. Must be one of [OR, AND]
:return: the list of indexes matching the search criteria
... | 6f8ec35063178e49a557de1849363568561638ed | 14,557 |
from typing import Optional
from typing import List
def recurse_structures(
structure: Component,
ignore_components_prefix: Optional[List[str]] = None,
ignore_functions_prefix: Optional[List[str]] = None,
) -> DictConfig:
"""Recurse over structures"""
ignore_functions_prefix = ignore_functions_pr... | 696e04a0184ebb7b8d2e0789e711a676c12ed89c | 14,558 |
from spinalcordtoolbox.image import Image
import dipy.reconst.dti as dti
import dipy.denoise.noise_estimate as ne
def compute_dti(fname_in, fname_bvals, fname_bvecs, prefix, method, evecs, file_mask):
"""
Compute DTI.
:param fname_in: input 4d file.
:param bvals: bvals txt file
:param bvecs: bvecs... | 149cfbc3f4fa2f3c1a33e4d4e6ee09983176e1b4 | 14,559 |
import tqdm
def solve(
netlist=None,
parameter_values=None,
experiment=None,
I_init=1.0,
htc=None,
initial_soc=0.5,
nproc=12,
output_variables=None,
):
"""
Solves a pack simulation
Parameters
----------
netlist : pandas.DataFrame
A netlist of circuit elemen... | fa51e4e69a434e3a3c728b4675844c0bfa29d3fd | 14,560 |
def global_node_entropy(data, dx=3, dy=1, taux=1, tauy=1, overlapping=True, connections="all", tie_precision=None):
"""
Calculates global node entropy\\ [#pessa2019]_\\ :sup:`,`\\ [#McCullough]_ for an
ordinal network obtained from data. (Assumes directed and weighted edges).
Parameters
----------
... | a14e7419bcd58d41400b888443df726836e6d04a | 14,561 |
def get_cert(certificate):
"""
Return the data of the certificate
:returns: the certificate file contents
"""
cert_file = "{}/certs/{}".format(snapdata_path, certificate)
with open(cert_file) as fp:
cert = fp.read()
return cert | da2ac96bf16a74de9ac75a46d14f3b95b5f64264 | 14,562 |
def model(data, ix_to_char, char_to_ix, num_iterations = 35000, n_a = 50, dino_names = 7, vocab_size = 27):
"""
Trains the model and generates dinosaur names.
Arguments:
data -- text corpus
ix_to_char -- dictionary that maps the index to a character
char_to_ix -- dictionary that maps a characte... | b1fb202b2c697cae1473c91597b39914e6197dce | 14,563 |
import random
def random_choice(gene):
"""
Randomly select a object, such as strings, from a list. Gene must have defined `choices` list.
Args:
gene (Gene): A gene with a set `choices` list.
Returns:
object: Selected choice.
"""
if not 'choices' in gene.__dict__:
rais... | 8a01a2039a04262aa4fc076bdd87dbf760f45253 | 14,564 |
def get_actor(payload: PayloadJSON, actor_id: int) -> ResourceJSON:
"""Return an actor by actor_id"""
actor = ActorModel.find_by_id(actor_id)
if actor is None:
abort(404)
return jsonify({"success": True, "actor": actor.json()},) | 0808cba237e47a45dd095f86d44153f97a947e66 | 14,565 |
import string
def check_if_punctuations(word: str) -> bool:
"""Returns ``True`` if ``word`` is just a sequence of punctuations."""
for c in word:
if c not in string.punctuation:
return False
return True | 64ba5f9dc69c59490a2ea69e7c2d938151d71b37 | 14,566 |
import re
def normalize_text(string, remove_stopwords=False, stem_words=False):
"""
Remove punctuation, parentheses, question marks, etc.
"""
strip_special_chars = re.compile("[^A-Za-z0-9 ]+")
string = string.lower()
string = string.replace("<br />", " ")
string = string.replace(r"(\().*(\... | 0aff8864f526ffe194c661acc69ccb2cf91a6f24 | 14,567 |
def get_new_codes():
""" Return New Codes and Refresh DB"""
db = dataset.connect(database_url)
new_codes = get_code()
table = db['promo']
""" Get New Codes"""
new = {}
for key, value in new_codes.items():
if table.find_one(promo=key) is None:
new[key] = [new_codes[key... | e3ece2e8b43fa43ac4c8d384dbf55957d8bc62c6 | 14,568 |
def process_bulk_add_ip(request, formdict):
"""
Performs the bulk add of ips by parsing the request data. Batches
some data into a cache object for performance by reducing large
amounts of single database queries.
:param request: Django request.
:type request: :class:`django.http.HttpRequest`
... | d38bc7766f232b972637da9c92567ebde91ddf52 | 14,569 |
def gen_public_e(lambda_: int) -> int:
""" Generates decrecingly smaller sequence of bytes and
converts them to integer until one satisfies > lambda
Continues with half the ammount of necesary bytes decreasing
by one integer until gcd(candidate, lambda) == 1.
"""
bytes_ = 1028 + 1
candidat... | 903df12b7af83be24d3ef377e2aa95a00a7df089 | 14,570 |
from typing import Union
from re import T
from typing import Callable
def lazy(maybe_callable: Union[T, Callable[[], T]]) -> T:
"""
Call and return a value if callable else return it.
>>> lazy(42)
42
>>> lazy(lambda: 42)
42
"""
if callable(maybe_callable):
return maybe_calla... | 83522ae39b8ec19e86d5e30b2b0a9131a7c56a35 | 14,571 |
from typing import List
import subprocess
def _git_diff(staged_or_modified: bool, extension: str) -> List[str]:
"""
Args:
extension: the extension of files considered, such as "py" or "ml"
staged_or_modified (bool) Whether to consider staged files (True)
or mo... | 520b3f59061a74b8df3dce22340a47ff413f3c02 | 14,572 |
from random import shuffle
def shuffle_list(*ls):
""" shuffle multiple list at the same time
:param ls:
:return:
"""
l = list(zip(*ls))
shuffle(l)
return zip(*l) | ec46e4a8da2c04cf62da2866d2d685fc796887e5 | 14,573 |
def cancer_variants(institute_id, case_name):
"""Show cancer variants overview."""
data = controllers.cancer_variants(store, request.args, institute_id, case_name)
return data | 185282e9308f7a9f8a0d7faf4c5d3608dee556cc | 14,574 |
def nodes(G):
"""Returns an iterator over the graph nodes."""
return G.nodes() | 3a1a543f1af4d43c79fd0083eb77fedd696547ec | 14,575 |
from typing import Union
def cyclePosition(image: np.ndarray, startPosition: position) -> Union[position, bool]:
"""
:param image: numpy image array
:param startPosition: from where to go to Tuple (x,y)
:return: newPosition (x,y), or false if new coords would fall out of bounds
"""
if not imag... | a4d3eaf1ddecc884f7391614ae04ff4b10029af3 | 14,576 |
import os
def get_image(file_name):
"""retrieves an image from a file and returns it as an np array of pixels"""
image_array = []
file_name = os.path.abspath(file_name)
img = Image.open(file_name)
img = img.convert("RGB")
img = img.resize((image_size, image_size))
in_data = np.asarray(img)... | cec87f685ba9b613aee371c57c436b5a9cae43c3 | 14,577 |
def context_to_ingestion_params(context):
"""extract the ingestion task params from job/serving context"""
featureset_uri = context.get_param("featureset")
featureset = context.get_store_resource(featureset_uri)
infer_options = context.get_param("infer_options", InferOptions.Null)
source = context... | 41925ce484bbc273caf9a8f0f33eba0e7163a7c8 | 14,578 |
def bining_for_calibration(pSigma_cal_ordered_, minL_sigma,
maxL_sigma, Er_vect_cal_orderedSigma_,
bins, coverage_percentile):
""" Bin the values of the standard deviations observed during
inference and estimate a specified coverage percentile
in... | cb241f6292726a86a7505e950f32fd1c1fefd19f | 14,579 |
def add_user(request):
"""注册用户"""
info = {}
tpl_name = 'user/add_user.html'
if request.method == 'POST':
# 保存用户提交数据
nickname = request.POST.get('nickname')
if User.objects.filter(nickname__exact=nickname).exists():
# "昵称" 存在
info = {'error':'"昵称"存在'}
... | bbfd3bc8ed47f19f527352f39d5e5b2bdc80d450 | 14,580 |
def process_input(input_string, max_depth):
"""
Clean up the input, convert it to an array and compute the longest
array, per feature type.
"""
# remove the quotes and extra spaces from the input string
input_string = input_string.replace('"', '').replace(', ', ',').strip()
# convert the s... | ca0fddd0b3bf145c7fc0654212ae43f02799b466 | 14,581 |
import random
def generate_new_shape() -> tuple[int, list[int], list[int]]:
"""Generate new shape
#0:
hot_cell_y = [0,1,2,3]
hot_cell_x = [5,5,5,5]
X
X
X
X
#1:
hot_cell_y = [0,0,0,0]
hot_cell_x = [3,4,5,6]
XXXX
#2... | d7c2c710f72ed5d21b7e63779815ee7bfb8421f4 | 14,582 |
def get_process_list(process):
"""Analyse the process description and return the Actinia process chain and the name of the processing result
:param process: The process description
:return: (output_names, actinia_process_list)
"""
input_names, process_list = analyse_process_graph(process)
outp... | f1e6689c50e00117379107fc840a09f4638c3912 | 14,583 |
def createAES(key, IV, implList=None):
"""Create a new AES object.
:type key: str
:param key: A 16, 24, or 32 byte string.
:type IV: str
:param IV: A 16 byte string
:rtype: tlslite.utils.AES
:returns: An AES object.
"""
if implList is None:
implList = ["openssl", "pycrypto... | c41a5d028028383630b0977522a9617334c94d03 | 14,584 |
from typing import OrderedDict
import binascii
import json
import sys
def command_info(opts):
"""Display general information from a .zs file's header.
Usage:
zs info [--metadata-only] [--] <zs_file>
zs info --help
Arguments:
<zs_file> Path or URL pointing to a .zs file. An argument beginning with
... | 8917e69c78a04ff70df181de8851b9688a498988 | 14,585 |
import os
def load_triple(cdict, label2words, extend=True):
"""
Loading triples of color modifiers
Parameters
----------
cdict : dict
Color dictionary maps a string to list of rgb tuples.
label2words : dict
Dictionary mapping color labels to color names.
Returns
-----... | 457a2f11b74485736e8f530ba3dc159ed3096078 | 14,586 |
def update_status_issue(issue, status_id, notes):
"""Request to change the status of a problem in a redmine project.
'issue': A hash of the issue is bound to a redmine project.
'status_id': Id status used by redmine the project.
'notes': Comments about the update.
Return value:
0 - on succe... | 6c0118f514083d228ac1d27271d297b3e593be52 | 14,587 |
from typing import Optional
def _get_avgiver_epost(root: ET.Element, ns: dict) -> Optional[str]:
"""
Sought: the email of the submitter
Can be found in a child element (<mets:note>) of an <mets:agent> with
ROLE="OTHER", OTHERROLE="SUBMITTER", TYPE="INDIVIDUAL"
"""
try:
agent = [
... | 9be1f53fcf9799f3a559cd12b3bfa056aaac11a7 | 14,588 |
def xavier_init(fan_in, fan_out, constant=1):
"""
Xavier initialization of network weights\
"""
low = -constant * np.sqrt(6.0 / (fan_in + fan_out))
high = constant * np.sqrt(6.0 / (fan_in + fan_out))
return tf.random_uniform((fan_in, fan_out),
minval=low, maxval=high... | 35b6f7b75eb44f1828d82c6743ec4751db4ff234 | 14,589 |
def strToMat3(dbstr):
"""
convert a string like e00, e01, e02, ... into Mat3
:param str:
:return: panda Mat4
"""
exx = dbstr.split(',')
exxdecimal = map(float, exx)
assert(len(exxdecimal) is 16)
return Mat3(exxdecimal[0], exxdecimal[1], exxdecimal[2],
exxdecimal[4... | 8db33dc5e2fab613cd6cba00021486fe722c8d32 | 14,590 |
def map2(func, *matrix):
"""
Maps a function onto the elements of a matrix
Also accepts multiple matrices. Thus matrix addition is
map2(add, matrix1, matrix2)
"""
matrix2 = []
for i in xrange(len(matrix[0])):
row2 = []
matrix2.append(row2)
for j in xrange(len(ma... | 9af6f311c80e70789ba6d623776fc2f80edbd905 | 14,591 |
def register_libtype(cls):
"""Registry of library types we may come across when parsing XML.
This allows us to define a few helper functions to dynamically convery
the XML into objects. See buildItem() below for an example.
"""
LIBRARY_TYPES[cls.TYPE] = cls
return cls | bb94e9f73ec04be834fa6be7de0cebf7c10a57ec | 14,592 |
def construct_tablepath(fmdict, prefix=''):
"""
Construct a suitable pathname for a CASA table made from fmdict,
starting with prefix. prefix can contain a /.
If prefix is not given, it will be set to
"ephem_JPL-Horizons_%s" % fmdict['NAME']
"""
if not prefix:
prefix = "ephem_JPL-H... | 95041aab91ac9994ef2068d5e05f6cd63969d94e | 14,593 |
def _grad_mulAux(kern,x,y,yerr,original_kernel):
"""
__grad_mulAux() its necesary when we are dealing with multiple terms of
sums and multiplications, example: ES*ESS + ES*ESS*WN + RQ*ES*WN and not
having everything breaking apart
Parameters
kern = kernel in use
x = range of values... | ce140d8a73a8304d0601077b5ed01f93cb17deab | 14,594 |
def get_unbiased_p_hat(number_candidates, c1, c2, p):
"""Get the p_hat to unbias miracle.
Args:
number_candidates: The number of candidates to be sampled.
c1: The factor that the conditional density of z given x is proportional to
if the inner product between x and z is more than gamma.
c2: The fac... | 5d45696557835f2bc655b601e015bb08356fe2dd | 14,595 |
def prox_gradf(xy, step):
"""Gradient step"""
return xy-step*grad_f(xy) | 7700850b9bfb5c5be5f0a63a678df93991673d81 | 14,596 |
import numpy
import math
def CBND(x, y, rho):
"""
A function for computing bivariate normal probabilities.
::
Alan Genz
Department of Mathematics
Washington State University
Pullman, WA 99164-3113
Email : alangenz@wsu.edu
This function is bas... | 3b418e50acec31482df7137f484d396b1673d476 | 14,597 |
def prune(root: Node, copy: bool = True) -> Node:
"""
Prune (or simplify) the given SPN to a minimal and equivalent SPN.
:param root: The root of the SPN.
:param copy: Whether to copy the SPN before pruning it.
:return: A minimal and equivalent SPN.
:raises ValueError: If the SPN structure is n... | e242156bca1d8a3be8ca673a6629dadf967ccb5b | 14,598 |
def GetRevisionAndLogs(slave_location, build_num):
"""Get a revision number and log locations.
Args:
slave_location: A URL or a path to the build slave data.
build_num: A build number.
Returns:
A pair of the revision number and a list of strings that contain locations
of logs. (False, []) in ca... | fb8b25a0f33194af288d411b2218edf904ab9f14 | 14,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.