content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from django.contrib.auth import logout
def signout(request):
"""Logs out user"""
logout(request)
return redirect('/') | 9b10ffc58f066affc915baf926815c032e041409 | 3,634,124 |
def _get_cached_item(cache_key):
"""Returns an item from memcache if cached
"""
return memcache.get() | 0265025d0599a7ec887c866ce5712d1f89c9832b | 3,634,125 |
def format_dnb_company_investigation(data):
"""
Format DNB company investigation payload to something
DNBCompanyInvestigationSerlizer can parse.
"""
data['dnb_investigation_data'] = {
'telephone_number': data.pop('telephone_number', None),
}
return data | 9c27990bad98b36649b42c20796caabeaae1e21b | 3,634,126 |
def audio_feat(id):
"""
Return audio features of a track.
search_id[0]['insert_feature_here']
id="4nb8OcZG8lpnHi5DmkEnY2" #Sample ID
audio_feat("4nb8OcZG8lpnHi5DmkEnY2")
:param id:
:return:
"""
return sp.audio_features(tracks=id) | 168801f4b0e01bf5fb4d416162bde5bfdd0d592e | 3,634,127 |
def params_v2_biasless(exp_name, convtype='chebyshev5', pooltype='max', nmaps=16,
activation_func='relu', stat_layer=None, input_channels=1,
gc_depth=8, nfilters=64,
const_k=5, var_k=None,
filters=None, batch_norm_output=False,
... | b5db72cd020115283f06d768920b55161a333139 | 3,634,129 |
import io
def get_ccd_pos(filename, radec=None, verbose=True):
"""
Parameters
----------
"""
astrom_file = io.filename_to_guider(filename)
if len(astrom_file)==0:
if verbose:
print("No astrom file found for %s"%filename)
return [np.NaN,np.NaN]
astrom_file = a... | e112e6ccbda8b28d2ac23bba1ab5b23fc7a2aab9 | 3,634,130 |
def learning_curve(estimator, X, y, groups=None,
train_sizes=np.linspace(0.1, 1.0, 5), cv=None, scoring=None,
exploit_incremental_learning=False, n_jobs=1,
pre_dispatch="all", verbose=0, shuffle=False,
random_state=None):
"""Learning curve.... | e8109033f2be16494c29c7d8626a3ad23646b9ed | 3,634,132 |
def directed_dfs(digraph, start, end, max_total_dist, max_buildings):
"""
Finds the shortest path from start to end using a directed depth-first
search. The total distance traveled on the path must not
exceed max_total_dist, and the number of buildings on this path must
not exceed max_buildings.
... | 1a88077d9441fc246f3d93194bb1ce53e0e48383 | 3,634,133 |
def zeta(z, x, beta2):
"""
Eq. (6) from Ref[1] (constant term)
Note that 'x' here corresponds to 'chi = x/rho',
and 'z' here corresponds to 'xi = z/2/rho' in the paper.
"""
return 3 * (4* z**2 - beta2 * x**2) / 4 / beta2 / (1+x) | aa623a1876fbb13128132960840ea388dac67e85 | 3,634,134 |
def getCountry(user):
"""
Returns the object the view is displaying.
"""
# get users country from django cosign module
user_countries = TolaUser.objects.all().filter(user__id=user.id).values('countries')
get_countries = Country.objects.all().filter(id__in=user_countries)... | 6d5825cf28729326626585ae566a221b6e90db47 | 3,634,135 |
def calculate_relative_enrichments(results, total_pathways_by_resource):
"""Calculate relative enrichment of pathways (enriched pathways/total pathways).
:param dict results: result enrichment
:param dict total_pathways_by_resource: resource to number of pathways
:rtype: dict
"""
return {
... | 7060e032f2a619929cfcf123cf0946d7965b86de | 3,634,136 |
def _import_config(config_dict, validating=False):
"""Applies a previously exported configuration to the current system.
This method only exists to decouple the import logic from the atomic transaction so that this method can be reused
for validation without making any permanent changes.
:param config... | f891437d68a05a0d98e489ac07fef4dbc77cfd25 | 3,634,137 |
def clean_name(name):
"""Clean a name string
"""
# flip if in last name, first name format
tokens = name.split(',')
if len(tokens) == 2:
first, last = tokens[1], tokens[0]
else:
first, last = name.split(' ')[:2]
# remove punctuation
first_clean = first.strip().capitaliz... | ef5fe3e53ba1134c45c30f4b6342a0641e85f114 | 3,634,138 |
def find_prime(num_bits: int) -> int:
"""Find a prime represented with given number of bits.
Generates random numbers of given size until one of them is deemed prime by
a probabilistic primality check.
Args:
num_bits: size of the prime in terms of bits required for representing it
Return... | 91b09571720fb181d4be135c767c9a9f7ca4c6e0 | 3,634,139 |
import struct
def UnpackS8(buf, offset=0, endian='big'):
""" Unpack an 8-bit signed integer into 1 byte.
Parameters:
buf - Input packed buffer.
offset - Offset in buffer.
endian - Byte order.
Return:
2-tuple of unpacked value, new buffer offset.
"""
try:... | e610b09e5e080634fbcbe3c37b65c8f12988db7e | 3,634,140 |
def estimator(data):
""" Provide the estimate calulations based on that data received """
#Collect required data from data imput
impact = {}
severeImpact = {}
reportedCases = data['reportedCases']
periodType = data['periodType']
timeToElapse = data['timeToElapse']
totalHospitalBeds = data['totalHospital... | 82ad0497914ea038a365bc19357b37bf61af3fab | 3,634,141 |
def diff_align(dfs, groupers):
""" Align groupers to newly-diffed dataframes
For groupby aggregations we keep historical values of the grouper along
with historical values of the dataframes. The dataframes are kept in
historical sync with the ``diff_loc`` and ``diff_iloc`` functions above.
This fu... | 2a92476cd913404b737dc941d51083f64ef70978 | 3,634,142 |
def get_usage_data(
es_client, start_date, end_date, match_terms={}, addl_cols=[], index="path-schedd-*"
):
"""Returns rows of usage data"""
default_cols = [
"Owner",
"ScheddName",
"GlobalJobId",
"RecordTime",
"RemoteWallClockTime",
"RequestCpus",
"Cp... | 665601cab0ac7c12bbde5f702b99ac75bc679872 | 3,634,143 |
def check_email_address_validity(email_address):
"""Given a string, determine if it is a valid email address using Django's validate_email() function."""
try:
validate_email(email_address)
valid_email = True
except ValidationError:
valid_email = False
return valid_email | 809de97c1e87a08e2ebf68b50096fc6d11104c17 | 3,634,144 |
def load_targets_file(input_file):
"""
Takes a string indicating a file name and reads the contents of the file.
Returns a list containing each line of the file.
Precondition: input_file should exist in the file system.
"""
with open(input_file, 'r') as f:
f = f.readlines()
out = [i.replace('\n','').replace('\... | 40d305e244264d6c3249bb9fb914cda3ebcda711 | 3,634,146 |
def plot_avg_profile(rad_dict, ylim=[0, None]):
"""
Function for plotting up average profiles including differences
Parameters
----------
rad_dict : dict
Dictionary of objects and variables to process. See example
ylim : list
ylimits to use
Returns
-------
ax : mat... | c79d28b289c3f403c49bc5695edc3b17215cf7f0 | 3,634,147 |
def localized_dt_string(dt, use_tz=None):
"""Convert datetime value to a string, localized for the specified timezone."""
if not dt.tzinfo and not use_tz:
return dt.strftime(DT_NAIVE)
if not dt.tzinfo:
return dt.replace(tzinfo=use_tz).strftime(DT_AWARE)
return dt.astimezone(use_tz).strft... | 6ae8fd12d93c360e9f23ec3e4e5080474dc7ea59 | 3,634,148 |
def dissolve_project_data(project_data):
"""
This functions uses the unionCascaded function to return a dissolved MultiPolygon geometry
from several Single Part Polygon geometries.
"""
multipolygon_geometry = ogr.Geometry(ogr.wkbMultiPolygon)
for item in project_data:
polygon = ogr.Crea... | 1e657087a564e9e134b11bfa382f337c65efa6d2 | 3,634,150 |
def pega_salada_sobremesa_suco(items):
""" Funcao auxiliar que popula os atributos salada, sobremesa e suco do cardapio da refeicao fornecida."""
alimentos = ["salada", "suco", "sobremesa"]
cardapio = {}
for alim in alimentos:
tag = alim.upper() + ":" # tag para procurar o cardapio dos alimento... | 4ccf2907a4e828d1357e16e827ad587e4a50a287 | 3,634,152 |
def readRGBImg(datapath, driver="GTiff"):
"""
Reads image path and returns 3-D numpy matrix of RGB image.
:param datapath: Path/String
Image path that is opened by rasterio.
:param driver: String
GDAL driver for opening the image. Default: 'GTiff'.
:return: rasterio data, Ndarray
... | 9f20ea8ca8c9594ddad570a650e5a496cf87e1ad | 3,634,153 |
def show_hidden_word(secret_word, old_letters_guessed):
"""
:param secret_word:
:param old_letters_guessed:
:return: String of the hidden word except the letters already guessed
"""
new_string = ""
for letter in secret_word:
if letter in old_letters_guessed:
new_string = ... | 2b3618619dcde2875da9dc8600be334e7aaadaad | 3,634,154 |
def get_total_gap(data : np.ndarray) -> float:
"""
Computes the total gap in time units for a given dataset
:param data: datset of the lightcurve
:return: total gap in units of time
"""
values,counts,most_common = get_diff_values_counts_most_common(data)
values[values - most_common < 10**-5... | 9cba80b47c430b38236f9160e6b62a8eb2ba9cab | 3,634,157 |
def print_srt_line(i, elms):
"""Print a subtitle in srt format."""
return "{}\n{} --> {}\n{}\n\n".format(i, format_srt_time(elms[0]),
format_srt_time(float(elms[0]) +
float(elms[1])),
... | cd089bdc06417f3f0915f97272ba7ec0bdc7d153 | 3,634,158 |
def depthwise_separable_conv(inputs,
num_pwc_filters,
width_multiplier,
scope,
downsample=False):
"""Depth-wise separable convolution."""
num_pwc_filters = round(num_pwc_filters * width_multiplier)
... | d6de489b766800957dceba05b1ba76f337974b04 | 3,634,159 |
def filter_packages(packages: list, key: str) -> list:
"""Filter out packages based on the given category."""
return [p for p in packages if p["category"] == key] | 46f11f5a8269eceb9665ae99bdddfef8c62295a2 | 3,634,160 |
def ptlinear(x, W, b=None, b2=None, is_pre_training=False, activation=None):
"""Pre trainable Linear function, or affine transformation.
It accepts two or three arguments: an input minibatch ``x``, a weight
matrix ``W``, and optionally a bias vector ``b``. It computes
:math:`Y = xW^\top + b`.
Args... | 2a3ae59b1c7e5e15506ec251fa336b89ff1e5f48 | 3,634,161 |
def cubic_bezier(pts, t):
"""
:param pts:
:param t:
:return:
"""
p0, p1, p2, p3 = pts
p0 = pylab.array(p0)
p1 = pylab.array(p1)
p2 = pylab.array(p2)
p3 = pylab.array(p3)
return p0 * (1 - t) ** 3 + 3 * t * p1 * (1 - t) ** 2 + \
3 * t ** 2 * (1 - t) * p2 + t ** 3 * p3 | 3239f0afcda78605d3ea2cf3e77bd3ee3827b358 | 3,634,162 |
from typing import List
def _GetServerComponentArgs(config_path: str) -> List[str]:
"""Returns a set of command line arguments for server components.
Args:
config_path: Path to a config path generated by
self_contained_config_writer.
Returns:
An iterable with command line arguments to use.
"""... | 7f768c8eaa6dc47dc2be3da5297cf17550e26896 | 3,634,163 |
import random
import string
def random_string(length=4):
"""Generates a random string based on the length given
Keyword Arguments:
length {int} -- The amount of the characters to generate (default: {4})
Returns:
string
"""
return "".join(
random.choice(string.ascii_upper... | ad9816e22a898e1e7d17d1bc9f0e56265bb09ac6 | 3,634,164 |
def FindBySummaryName(name):
"""
Find the first instance of a virtual machine with the specified name.
"""
vms = GetAll()
for vm in vms:
try:
summary = vm.GetSummary()
config = summary.GetConfig()
if config != None and config.GetName() == name:
return vm
... | 981d8e13b6bdf39302f5a192453bbb1ea1f4e943 | 3,634,165 |
def get_potential_trace_fields(poly,sln=2):
"""Given a minimal polynomial of a trace field, returns a list of minimal polynomials of the potential invariant trace fields."""
pol = pari(poly)
try:
return [str(rec[0].polredabs()) for rec in pol.nfsubfields()[1:] if _knmiss(rec[0].poldegree(),pol.polde... | a952fefdd98f38b0c23d3ca3962b85584daa70be | 3,634,166 |
def launch():
"""Initialize the module."""
return UERRCMeasurementsWorker(UERRCMeasurements, PRT_UE_RRC_MEASUREMENTS_RESPONSE) | d26a4e28b5e541eaba9543211b477ba3734a5082 | 3,634,168 |
def enlarge_histogram(file = None,filename = None):
"""
Arguments:
file: an image file that is going to be processed
filename: a filename of the file to be processed
Returns:
The same input image but with its histogram enlarged.
"""
if file is None and filename... | 5997647820fb4cee16f0c4e3d6e588859ee2ea77 | 3,634,169 |
def task(n):
"""Return 2 to the n'th power"""
return 2 ** n | 5780e22d4916664d66279d8ad8afed3b176d9adb | 3,634,170 |
def get_relationship(context, user_object):
"""caches the relationship between the logged in user and another user"""
user = context["request"].user
return get_or_set(
f"relationship-{user.id}-{user_object.id}",
get_relationship_name,
user,
user_object,
timeout=259200... | 5c640f51b8319ad918e6c176be4ca5fab143de1c | 3,634,172 |
def _ts_midpoint(x1, d: int):
"""moving midpoint: (ts_max + ts_min) / 2"""
return _ts_max(x1, d) + _ts_min(x1, d) | b8916ea7bb347a828fc504bbd19bf5eeeed57e5c | 3,634,173 |
import numbers
def maybe_delivery_mode(
v, modes=DELIVERY_MODES, default=PERSISTENT_DELIVERY_MODE):
"""Get delivery mode by name (or none if undefined)."""
if v:
return v if isinstance(v, numbers.Integral) else modes[v]
return default | 20221a11f9af378e2b877cf76941f2f05ff2c8da | 3,634,174 |
def load_pairs(path: str) -> list:
"""
Loads the pairs specified in a file in the format of "word1 word2" separated by new line.
:param path: Path to the file containing the pairs.
:return: The list of unique tuples contained in the file, but not their inverse counterpart as opposed to
load_constrai... | 7f98937c14315d00feb32db79c54e6c79fa32e3a | 3,634,175 |
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: the file path to the i... | b85dd2ee866231a0db53bfab8151fdad9e875ff8 | 3,634,176 |
def is_illumina_run(run_dir):
"""
Detects signature files in the run directory (eg RunInfo.xml) to detemine
if it's likely to be an Illumina sequencing run or not.
:param run_dir: The path to the run.
:type run_dir: str
:return: True if it looks like an Illumina run.
:rtype: bool
"""
... | 7069e29c977da3d4f23bf6e3321ec3ebc7b44d9f | 3,634,177 |
from datetime import datetime
import requests
def polo_return_chart_data(currency_pair,
start_unix=None,
end_unix=None,
period_unix=14400,
format_dates=True,
to_frame=True):
"""
... | 51f8ecfce81359132ede56ff5b37f106e54183b2 | 3,634,179 |
def ergtoboatspeed(min,sec,ratio,crew,rigging,erg):
""" Calculates boat speed, given an erg split for given crew, boat, erg
"""
res = ergtopower(min,sec,ratio,crew,erg)
pw = res[0]
res = constantwatt(pw,crew,rigging)
return res | d192c0e9edc1ef46468dc4762c22d45320ad36a9 | 3,634,180 |
def interval_range(
start=None, end=None, periods=None, freq=None, name=None, closed="right",
) -> "IntervalIndex":
"""
Returns a fixed frequency IntervalIndex.
Parameters
----------
start : numeric, default None
Left bound for generating intervals.
end : numeric , default None
... | a2873a34780da22c8955278c358f45d0432b1f53 | 3,634,182 |
def get_summary_description(node_def):
"""Given a TensorSummary node_def, retrieve its SummaryDescription.
When a Summary op is instantiated, a SummaryDescription of associated
metadata is stored in its NodeDef. This method retrieves the description.
Args:
node_def: the node_def_pb2.NodeDef of a TensorSum... | 80df9bd63c23aa9f1f92d5d3a1f49dd54c4f0737 | 3,634,183 |
def _einsum_kronecker_product(*trans_mats):
"""Compute a Kronecker product of multiple matrices with :func:`numpy.einsum`.
The reshape is necessary because :func:`numpy.einsum` produces a matrix with as many
dimensions as transition probability matrices. Each dimension has as many values as
rows or col... | 39622c94ea9138b4cb2511922166178998231b2e | 3,634,184 |
def calc_loss_class(true_box_conf, CLASS_SCALE, true_box_class, pred_box_class):
"""
== input ==
true_box_conf : tensor of shape (N batch, N grid h, N grid w, N anchor)
true_box_class : tensor of shape (N batch, N grid h, N grid w, N anchor), containing class index
pred_box_class : tensor of shape ... | 3971cdce266fc0af85f9a3d56e0266ecb31ff0da | 3,634,185 |
def unmixGradProjMatrixNNLS(image, A, tolerance=1e-4, maxiter=100):
"""
Performs NNLS via Gradient Projection of the primal problem.
Terminates when duality gap falls below tolerance
"""
if image.ndim == 2:
(n1, n3) = image.shape
n2 = 1;
elif image.ndim == 3:
(n1, n2, n3)... | ac6bb769e9343f49095166a751fa1c40e2e6ed06 | 3,634,186 |
def seismic():
"""Benchmark Seismic object."""
# coords = [{"x": np.arange(10)}, {"y": np.arange(10)}, {"z": np.arange(100)}]
coords = [("x", np.arange(10)), ("y", np.arange(10)), ("z", np.arange(100))]
cube = segyio.tools.cube("../data/test.segy")
# seis = from_segy("tests/data/test.segy")
retu... | 556aa9407162951756754be9c24c80986e475cb5 | 3,634,187 |
import math
def sterrmean(s, n, N=None):
"""sterrmean(s, n [, N]) -> standard error of the mean.
Return the standard error of the mean, optionally with a correction for
finite population. Arguments given are:
s: the standard deviation of the sample
n: the size of the sample
N (optional): the... | 30ad7b9b184b1a86b8d9bf03ee515b34aab3b368 | 3,634,188 |
def change_device_status(dispatcher, device_name, status):
"""Set the status of a device in Nautobot."""
if menu_item_check(device_name):
prompt_for_device(
"nautobot change-device-status",
"Change Nautobot Device Status",
dispatcher,
offset=menu_offset_va... | 6f8e7d7637fed71b501aa89791c638d80caa1eab | 3,634,189 |
def text_to_vector(sentences):
"""
#使用one-hot方法将文本转为向量, 例如:
Sentence1 不 知道 你 在 说 什么 。
Sentence2 我 就 知道 你 不 知道 。
词表: 不 就 你 什么 我 说 知道 在 。
S1 [1 0 1 1 0 1 1 1 1]
S2 [1 1 1 0 1 0 2 0 1]
即得到分词后的句子之后,先得到词表
每个词对应一个位置,如“不”对应第一个位置,等等
如果s1出现了不一次,就把s1的第一个位置设为1,如果没有出现就是0,
如果出现了两次“不”,那么s1的第一个位置就是2,以此类推
"""
# 先将所... | a065b6f99c0083473b76d20c13a3722326d29587 | 3,634,190 |
import tqdm
def block_solve_agd(
r_j,
A_j,
a_1_j,
a_2_j,
m,
b_j_init,
t_init=None,
ls_beta=None,
max_iters=None,
rel_tol=1e-6,
verbose=False,
zero_thresh=1e-6,
zero_fill=1e-3,
):
"""Solve the optimization problem for a single block with accelerated
gradient ... | 168be883091592c86f7c2cd38f7d1980abd3f4c5 | 3,634,194 |
def bin_array_max(arr, bin_size, pad_value=0):
"""
Given a NumPy array, returns a binned version of the array along the last
dimension, where each bin contains the maximum value of its constituent
elements. If the array is not a length that is a multiple of the bin size,
then the given pad will be u... | db16540a8d5e4ac91948dab6a0c94b86398635b5 | 3,634,196 |
def harmony(img, center, angle=None):
"""Harmonize the pattern by exploiting symmetry
If the shape of the pattern is not anymore odd after the rotation has been
performed the pattern is padded with zeros such that its shape is odd.
:param img: pattern
:param center: center coordinates in patte... | e2a2ddab67d28d34210aaf8926595670a0e046d8 | 3,634,197 |
def is_following(request, author) -> bool:
"""Checks if this author is in the user's subscriptions"""
if Follow.objects.filter(user=request.user, author=author):
return True
return False | 32a81b0d6482d5fd99d6d1b55e518b59238d87bd | 3,634,199 |
def find_revert_op(input_state_index: int):
"""Looks in the Cayley table the operation needed to reset the state to ground state from input state_tracker
:param input_state_index: Index of the current state tracker
:return: index of the next Clifford to apply to invert RB sequence
"""
for i in rang... | cba4a4f764f02abbfb14527cff4f1470d0c6ff3a | 3,634,200 |
def _column_number_to_letters(number):
"""
Converts given column number into a column letters.
Right shifts the column index by 26 to find column letters in reverse
order. These numbers are 1-based, and can be converted to ASCII
ordinals by adding 64.
Parameters
----------
number : int... | c9a68bcd32c8f254af322bc61e447cfae61cb6d2 | 3,634,201 |
import gurobipy as gb
def toGRBFromStr():
""" Module for program-wide constant maps (e.g., dicts that should never change) """
return {"=": gb.GRB.EQUAL,
"le": gb.GRB.LESS_EQUAL,
"ge": gb.GRB.GREATER_EQUAL} | 7fb8a522d787716d3006722511d7afb3c5378d3a | 3,634,202 |
def _generate_mea_comment(obj: GamObject, object_module: GamObject):
"""
Check whether the object has a module, then generate the measurement comment and update the object ID to add
the measurement to.
Args:
obj (GamObject): The object.
object_module (GamObject): The object module, if t... | 89a119a542c14e5edc745878127503b0f996007e | 3,634,203 |
def master_do(func, *args, **kwargs):
"""Help calling function only on the rank0 process id ddp"""
try:
rank = dist.get_rank()
if rank == 0:
return func(*args, **kwargs)
except AssertionError:
# not in DDP setting, just do as usual
func(*args, **kwargs) | befe0d157591c10cb6e590a82e5c3f5253fe4663 | 3,634,204 |
def news_msg(result):
""" Interface Function for news intent """
campus_publication = ""
news_result = []
try:
campus_publication = result.parameters['club']
campus_publication = campus_publication.lower()
except BaseException:
campus_publication = ""
return "I couldn... | a60df1affbfda2ec68c1d4c27daaa495002e5780 | 3,634,205 |
def init_aws_client():
"""Initializes and returns AWS boto3 client object"""
client = boto3.client("network-firewall")
return client | 28d06097d97e4a364beff767cc0177922a3aff88 | 3,634,206 |
def _chunk_member_lag(chunk, repl_member_list, primary_optimedates, test_run_indices):
"""Helper function to compute secondary lag from values in a chunk
:param collection.OrderedDict chunk: FTDC JSON chunk
:param list[str] repl_member_list: list of all members in the replSet
:param str primary: which ... | 115ba53505d5bcbb9e0c1cdf0eab675fae73e568 | 3,634,208 |
def graph_build_split(X, edge_index, node_mask: np.array):
""" subgraph building through spliting the selected nodes from the original graph """
row, col = edge_index
edge_mask = (node_mask[row] == 1) & (node_mask[col] == 1)
ret_edge_index = edge_index[:, edge_mask]
return X, ret_edge_index | 45b62a79b6c35ceda181e15d7a4a00dda8146fc6 | 3,634,209 |
def get_pagination_class():
"""
Returns custom pagination class, set in settings
"""
pagination_class = LIKES_REST_PAGINATION_CLASS
if pagination_class:
try:
return import_string(pagination_class)
except ImportError:
pass
return api_settings.DEFAULT_PAGI... | 57c12519b1f4a6a2a4e5533176e9901e3f468bf9 | 3,634,210 |
def get_us_presidents_gender(president):
"""Given the name of a US President, return his gender, or None if not found. """
data = load('us_president_gender')
for row in data:
if row['president'] == president:
return row['gender']
return None | 46bca2773092fa31a53ebb774cbcca6d8863d1a8 | 3,634,211 |
import warnings
def ProtoFromTfRecordFiles(files,
max_entries=10000,
features=None,
is_sequence=False,
iterator_options=None):
"""Creates a feature statistics proto from a set of TFRecord files.
Args:
... | d0891996a1f1889b575cd042a78eb0b17a95b4c5 | 3,634,212 |
def smallest_evenly_divisible(min_divisor, max_divisor, minimum_dividend=0):
"""Returns the smallest number that is evenly divisible (divisible
with no remainder) by all of the numbers from `min_divisor` to
`max_divisor`. If a `minimum_dividend` is provided, only dividends
greater than this number will ... | fa23d9a413a0909bfc05d7eb928aec8ade4cb06f | 3,634,213 |
def pct75(input_tensor, weights_tensor):
"""Compute the 75th percentile of a given tensor."""
del weights_tensor
return tfp.stats.percentile(input_tensor, 75) | 8c447827559841d50e02a68b99da6d7abf422fda | 3,634,214 |
import copy
def get_bad_sequences(GoodSequenceList, Bad1st_list, BadOther_list):
"""Take each good sequence and implant a codec error at any possible byte
position.
RETURNS: List of bad sequences.
"""
result = []
for sequence in GoodSequenceList:
# Implement a couple of bad sequences ... | 52ce3a1c9ee468c7b2c39d5113d783667884deba | 3,634,215 |
def factorial(n):
"""
Returns the factorial of n
Parameters
----------
n : int
denotes the non-negative integer for which factorial value is needed
"""
if(n<0):
raise NotImplementedError(
"Enter a valid non-negative integer"
)
if(n==0 or n==... | fe0b7100e1292d1e96daf18545d9fdfb931f9f74 | 3,634,216 |
import time
def check_redis(*args, **kwargs):
"""Checks if configured Redis instance is pingable."""
try:
r = StrictRedis.from_url(current_app.config['CACHE_REDIS_URL'])
t1 = time.time()
res = r.ping()
t2 = time.time()
return 'redis', res, {'time': t2 - t1}
except (... | 10ba4595b869747def8592b901125a197f794fea | 3,634,217 |
def Divide(a, b):
"""Returns the quotient, or NaN if the divisor is zero."""
if b == 0:
return float('nan')
return a / float(b) | 3ed0b07949bb802177e52bf8d04e9dfde92ab2de | 3,634,218 |
def guess_typecode(value):
"""Guess Gwyddion typecode for `value`."""
if np.isscalar(value) and hasattr(value, 'item'):
# Seems to be a numpy type -- convert
value = value.item()
if isinstance(value, GwyObject):
return 'o'
elif isinstance(value, string_types):
if len(valu... | 3440c8008596d479d084e8fe68ca941ab6b23c17 | 3,634,220 |
from typing import Dict
from typing import Any
def create_region(entity: Entity, author: Identity) -> Identity:
"""Create a region"""
custom_properties: Dict[str, Any] = {"x_opencti_location_type": "Region"}
return Location(
created_by_ref=author,
name=entity.value,
region=entity.... | c1c21da1568f030b9b1a84263ddc3547226233b2 | 3,634,221 |
def post(post_id):
"""
实例化一个评论表单,并将其传入post.html
:param post_id:
:return:
"""
post = Post.query.get_or_404(post_id)
form = CommentForm()
if form.validate_on_submit():
comment = Comment(comment_body=form.comment_body.data,
post=post,
... | 6b209ef5fd464ffbc0fa71c259d4105dbeb4f79d | 3,634,222 |
def noisify(chse, dE, dt, dU):
"""
Create a nosified chain
Parameters
chse : Chain instance
cE: float
spread in on-site energies
dt: float
spread in hoppings
dU: float
spread in interaction
"""
dEs = np.zeros((chse.N,))
dts = np.zeros((chse.N,))
dUs =... | 7e4e1d4c2872e081fbc50536bda7883bb50cce35 | 3,634,223 |
def kepio(keplcfile):
"""Read in a Kepler LC file and return the time, flux, and error"""
with fits.open(keplcfile) as hdu:
print(hdu.info())
t = hdu[1].data["TIME"]
f = hdu[1].data["SAP_FLUX"]
e = hdu[1].data["SAP_FLUX_ERR"]
return t,f,e | 2bfc458200a2c4a04715eebd2306368e8f3581c2 | 3,634,224 |
def camera_matrix(K: np.ndarray, R: np.ndarray, t: np.ndarray) -> np.ndarray:
"""Derive the camera matrix.
Derive the camera matrix from the camera intrinsic matrix (K),
and the extrinsic rotation matric (R), and extrinsic
translation vector (t).
Note that this uses the matlab convention, such tha... | 274ca0736397850eb82a155000fd8265196315aa | 3,634,225 |
import ntpath
def path_leaf(path):
"""
Extract the file name from a path.
If the file ends with a slash, the basename will be empty,
so the function to deal with it
Parameters
----------
path : str
Path of the file
Returns
-------
output : str
The name of the ... | 58930f081c2366b9084bb279d1b8b267e5f93c96 | 3,634,226 |
def focus_metric(data, merit_function='vollath_F4', **kwargs):
"""Compute the focus metric.
Computes a focus metric on the given data using a supplied merit function.
The merit function can be passed either as the name of the function (must be
defined in this module) or as a callable object. Additional... | c8f571e11202d39d8f331fca5fc93333aeb71e62 | 3,634,229 |
def get_canonical_import(import_set):
"""Obtain one single import from a set of possible sources of a symbol.
One symbol might come from multiple places as it is being imported and
reexported. To simplify API changes, we always use the same import for the
same module, and give preference to imports coming from... | ae53ca4d271ab543a7a13f1ce8240ce6eb328bbb | 3,634,230 |
def additive_white_gaussian_noise(signal, noise_level):
"""
Add gaussian white noise to audio signal.
:param signal: Audio signal to permute.
:param noise_level: standard deviation of the gaussian noise.
"""
# SNR = 10 * log((RMS of signal)^2 / (RMS of noise)^2)
# RMS_s = np.sqrt(np.mean(si... | c4705b2fa67ce319609677a91bb7efa3e9c427b7 | 3,634,231 |
import torch
from typing import Iterable
def _tensor_in(tensor: torch.Tensor, iterable: Iterable[torch.Tensor]):
"""Returns whether `tensor is element` for any element in `iterable` This function is necessary because `tensor in
iterable` does not work reliably for `Tensor`s.
See https://discuss.pytorch.o... | 84ac8a129440c9c8d7785029b04bd403514a3bb9 | 3,634,232 |
def flip(a, dim=0):
"""
Flip an array along a dimension.
Parameters
----------
a : af.Array.
Multi dimensional array.
dim : optional: int. default: 0.
The dimension along which the flip is performed.
Returns
-------
out : af.Array
The output after flippin... | 1c006acae6d6bfccb92a519da197fa6e3792e2c8 | 3,634,233 |
def get_cnn_model(params):
"""
Load base CNN model and add metadata fusion layers if 'use_metadata' is set in params.py
:param params: global parameters, used to find location of the dataset and json file
:return model: CNN model with or without depending on params
"""
input_tensor = Inp... | c87ee7d11439adf5fd7bc98e3d70398c32421089 | 3,634,234 |
def is_development_mode(registry):
"""
Returns true, if mode is set to development in current ini file.
:param registry: request.registry
:return: Boolean
"""
if 'mode' in registry.settings:
return registry.settings['mode'].lower() == 'development'
return False | af1b11fa69231a455406247b593f8ff49855bc3f | 3,634,235 |
def run_summarizer(parser, sentences, language='english'):
"""
:params parser: Parser for selected document type
:params sentences: Maximum sentences for summarizer.
:returns summary: Summarized page.
"""
summarizer = Summarizer(Stemmer(language))
summarizer.stop_words = get_stop_words(lan... | 9dd61447df7612b005b825c2e21fc3943596ab12 | 3,634,236 |
def mk_input(ctx, name, type):
"""
mk_input(Int_ctx ctx, char const * name, Int_type type) -> Int_net
Parameters
----------
ctx: Int_ctx
name: char const *
type: Int_type
"""
return _api.mk_input(ctx, name, type) | 05cba1813f9fb81ea132dac653073466862e4db0 | 3,634,237 |
def coo_fromdense_mhlo(mat, *, nnz, data_dtype, index_dtype,
index_type):
"""COO from dense matrix."""
mat_type = ir.RankedTensorType(mat.type)
rows, cols = mat_type.shape
buffer_size, opaque = _hipsparse.build_coo_fromdense_descriptor(
data_dtype, index_dtype, rows, cols, nnz)
... | c8cf5db1d05e9fcaf6d383f1d6cd9cfa2fe55ae8 | 3,634,238 |
def __get_wight(last_link: Link, end_link: Link, end_fraction, weight_function):
"""
Calculate the wight of the end_link.
:param last_link: Needed to determine from which direction you comes
:param end_link: Link from which the weight is calculated
:param end_fraction: fraction as Number (1 >= fract... | e80a82fa830d08890a51398f6f9e5ba69482405a | 3,634,239 |
def float_fraction(trainpct):
""" Float bounded between 0.0 and 1.0 """
try:
f = float(trainpct)
except ValueError:
raise Exception("Fraction must be a float")
if f < 0.0 or f > 1.0:
raise Exception("Argument should be a fraction! Must be <= 1.0 and >= 0.0")
return f | 8eb28dcaa0ed9250f4aa68d668ad424b5b5eded5 | 3,634,240 |
def handle_internal(msg):
"""Process an internal message."""
internal = msg.gateway.const.Internal(msg.sub_type)
handler = internal.get_handler(msg.gateway.handlers)
if handler is None:
return None
return handler(msg) | 0f5cae49cf5d36a5e161f88902c46af931fd622a | 3,634,241 |
def _lower_bound_grad(op, grad):
"""Gradient for `lower_bound` if `gradient == 'identity_if_towards'`.
Args:
op: The op for which to calculate a gradient.
grad: Gradient with respect to the output of the op.
Returns:
Gradient with respect to the inputs of the op.
"""
inputs, bound = op.inputs
... | 907ef212759f6a45ff32b78bcfede6222d978996 | 3,634,242 |
def obv(s_interval: str, df_stock: pd.DataFrame) -> pd.DataFrame:
"""On Balance Volume
Parameters
----------
s_interval: str
Stock data interval
df_stock: pd.DataFrame
Dataframe of stock prices
Returns
-------
pd.DataFrame
Dataframe with technical indicator
... | 36d3cd371bb37fa5ee74f10b774ae4408a9164d2 | 3,634,244 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.