content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_custom_data_format(*args):
"""
get_custom_data_format(dfid) -> data_format_t
Get definition of a registered custom data format.
@param dfid: data format id (C++: int)
@return: data format definition or NULL
"""
return _ida_bytes.get_custom_data_format(*args) | 8b8751f94a409dc656efbe8131de66a0916be9ea | 8,400 |
def memory(info, func, expr):
"""
checks if the function has been called with the same argument previously and
if so, returns the same results instead of running the function again
args:
-
"""
rows=None
if info:
if func in info.evaluated:
if expr in info.evaluated[func]:
rows = info... | 693ad671b21efbc872508b7a5a4c4aa31852d10a | 8,401 |
def friend_invitation_by_email_verify_for_api( # friendInvitationByEmailVerify
voter_device_id, invitation_secret_key, web_app_root_url=''):
"""
:param voter_device_id:
:param invitation_secret_key:
:param web_app_root_url:
:return:
"""
status = ""
success = False
# If a v... | 5765f5e06a40de81b36a2dc594f6f67ec236ddcb | 8,402 |
import os
def preprocess_rinex(rinex_file, target_directory=None):
"""Read a RINEX Navigation Message file and reformat the data.
Read a file with name "BRDC00IGS_R_yyyyddd0000_01D_MN.rnx" that was
downloaded from https://cddis.nasa.gov/archive/gnss/data/daily/yyyy/brdc/
where yyyy is the year and dd... | ec05ba7c6384d223b2059ffead82f09bb15b5e1e | 8,403 |
import torch
def _load_image(fnames, dim=None, device=None, label=False):
"""Load a N-D image from disk"""
dat, affine = _map_image(fnames, dim)
if label:
dtype = dat.dtype
if isinstance(dtype, (list, tuple)):
dtype = dtype[0]
dtype = dtypes.as_torch(dtype, upcast=True)... | 8f5dae0666d0173e57a8f0005a4f6d491d2bd58f | 8,404 |
import os
def GetCurrentVersion(paths, platform):
"""Find the current component version by iterating gsbucket root folder.
Args:
paths: ([str]) a list of folder paths strings.
platform: (str) the platform for which the component is being built
Returns:
str: current component version.
str: gs p... | 2358219202b827a399c83358a2d24994d4b0b898 | 8,405 |
from typing import Tuple
import ctypes
def dtpool(name: str) -> Tuple[int, str, bool]:
"""
Return the data about a kernel pool variable.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dtpool_c.html
:param name: Name of the variable whose value is to be returned.
:return:
Nu... | 96584733f7f2ad93ed50e0e48ccd1040eb08dd17 | 8,406 |
def add_similar_tracks(position_or_range = ":", howmany=5, relative_positions=True):
"""
Adds Up to the value of howmany tracks similar to
each track on the current playlist.
parameters:
===========
# position_or_range: The position of the track to add similar tr... | 778eadc4d00de1aa2f293d963cdd643499f234dd | 8,407 |
def get_hot_article_tags():
"""
获取文章的所有标签
:return: 返回所有文章的标签
"""
return Tag.objects.filter(is_hot=True) | d4158308ef3ea3cbce646548dc47def9e35fcef7 | 8,408 |
from unittest.mock import patch
def patch_user_interface_null() -> MockedUserInterfaceNull:
"""Patch player interface with no players."""
return patch("steam.api.interface", return_value=MockedUserInterfaceNull()) | 8491d7beef4dfbf949cfb5a27106a948e30487c2 | 8,409 |
import sys
def confirm(new_command, side_effect, settings):
"""Returns `True` when running of new command confirmed."""
if not settings.require_confirmation:
logs.show_command(new_command, side_effect, settings)
return True
logs.confirm_command(new_command, side_effect, settings)
try:... | ecadd95d87984720a8e42b2134857ff8eee07e84 | 8,410 |
import signal
import numpy
def first_localmax_index(data):
"""Return index of first local maxima.
If there is no local maxima (e.g. if all the values are zero),
it will simply return zero.
"""
localmax_indexes = signal.argrelextrema(data, numpy.greater, mode='wrap')
if localmax_indexes[0]... | 7cd7baa8d564dd2175e6fd8877a733fca41e63ef | 8,411 |
def _rds_clone_ ( dataset , name = '' ) :
"""Clone dataset
>>> dataset = ...
>>> cloned = datatset.clone ( 'new_name')
"""
name = name if name else dsID ()
return ROOT.RooDataSet ( dataset , name ) | f3e3156987eafb99f05fb99a2d8371c65959faf9 | 8,412 |
def getFirstDateOfQuarter(date):
"""
Return: {Date} The start date of the quarter for the given date.
"""
# Bug if first date of the quarter is used, so add 1 if that's the case.
if date.day == 1:
date = date + timedelta(days=1)
quarter_start = pd.to_datetime(date - pd.tseries.offsets.QuarterBegin(startingMo... | 4962bd2e57fe210fba57340f19384835c0ae1c07 | 8,413 |
def abbink_onset_detector(signal=None, rest=None, sampling_rate=1000.,
size=None, alarm_size=None, threshold=None,
transition_threshold=None):
"""Determine onsets of EMG pulses.
Follows the approach by Abbink et al.. [Abb98]_.
Parameters
----------
... | 0ae968c46ff4e5dd5496f09b637a1d5c039ab9fa | 8,414 |
import sys
def reparse(metadata):
"""Some things need to be parsed again after the build environment has been created
and activated."""
metadata.final = False
sys.path.insert(0, metadata.config.build_prefix)
sys.path.insert(0, metadata.config.host_prefix)
py_ver = '.'.join(metadata.config.vari... | 076efe659cbbc7826c2a2159617e4142b06f6e36 | 8,415 |
def _process_image(filename, coder):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height: integer,... | 6d978af3360692159300b4450cdd851aae842098 | 8,416 |
import multiprocessing
import psutil
import logging
import os
import time
import signal
import errno
def fork_processes_with_watchdog(
num_processes, is_shutdown_callback, child_pids=None,
stoploss_ratio=STOPLOSS_RATIO, timeout_period=TIMEOUT_PERIOD,
sleep_period=SLEEP_PERIOD, grace_period=GRACE_PERIOD,
... | 11fa328146865ca212436f7380d7895e9b62d7be | 8,417 |
import os
def load_fonts(folder="fonts/latin"):
"""Load all fonts in the fonts directories
"""
fonts = []
if folder is not None:
if os.path.isdir(folder):
# the folder exists whether it is relative or absolute path
for font in os.listdir(folder):
if fon... | 87e15b826e99b3d350fcb4ad8e58ac968644a4d0 | 8,418 |
def float_feature(value):
"""Wrapper for inserting float features into Example proto.
"""
if not isinstance(value,list):
value = [value]
return tf.train.Feature(float_list=tf.train.FloatList(value=value)) | 9333af60465a251883b3efe70de26ce9ce483657 | 8,419 |
def my_charts(request):
"""
define personal graphics page behavior
"""
data = [0, 0, 0, 0]
if request.method == 'POST':
month = request.POST.get('month')
if month is not None:
current_user_id = request.user.id_user
if month == 'all':
all_class... | adc11d0748246c753581675eee19b2780b16b832 | 8,420 |
def matrix2yzy_extrinsic(rotation_matrices: np.ndarray) -> np.ndarray:
"""
Ry(k3) @ Rz(k2) @ Ry(k1) = [[c1c2c3-s1s3, -s2c3, s1c2c3+c1c3],
[c1s2, c2, s1s2],
[-c1c2s3, s2s3, -s1c2s3+c1c3]]
"""
rotation_matrices = rotation_matrices.reshape((-1... | 8a37e65751a26d3fd5c360ce9068626bfee5c594 | 8,421 |
def smallest_subarray_with_given_sum(arr, s):
"""Find the length of the smallest subarray whose sum is >= s.
Time: O(n)
Space: O(1)
>>> smallest_subarray_with_given_sum([2, 1, 5, 2, 3, 2], 7)
2
>>> smallest_subarray_with_given_sum([2, 1, 5, 2, 8], 7)
1
>>> smallest_subarray_with_giv... | 4a1d63619fc200c32ffae80dc7d404f486efcdd1 | 8,422 |
from typing import OrderedDict
def create_lit_model(
model: str,
input_types: "OrderedDict[str, lit_types.LitType]", # noqa: F821
output_types: "OrderedDict[str, lit_types.LitType]", # noqa: F821
attribution_method: str = "sampled_shapley",
) -> lit_model.Model:
"""Creates a LIT Model object.
... | 355eaebe6e59733d1831f993d56462ee36e4ff9a | 8,423 |
from typing import List
from typing import Dict
from typing import OrderedDict
def show_lightning_round_zero_correct(database_connection: mysql.connector.connect
) -> List[Dict]:
"""Return list of shows in which a panelist answers zero Lightning
Fill-in-the-Blank round que... | 5c218639fd2321239d9f791221f2ad30f17ead02 | 8,424 |
import requests
def get_webpage(page_url):
"""Get the OOTS index webpage and return the content."""
result = requests.get(page_url)
if result.status_code == 200:
return result.text
else:
_logger.error(
colored(
"Unable to read the OOTS data,please check your... | e9b88f69b9dca0d5cf525a26e7e43fd118698225 | 8,425 |
def generate_config(context):
""" Entry point for the deployment resources. """
properties = context.properties
name = properties.get('name', context.env['name'])
bastion_props = {
'zone': properties['zone'],
'network': properties['network'],
'machineType': properties['machineT... | f22dbb3cb3500766badb6c28eb3de35b6ba5ba3c | 8,426 |
import inspect
def dump_args(func):
"""Decorator to print function call details - parameters names and effective values.
"""
def wrapper(*args, **kwargs):
func_args = inspect.signature(func).bind(*args, **kwargs).arguments
func_args_str = ', '.join('{} = {!r}'.format(*item) for item in fu... | 673158019aa3a8343718b9648b61ef4a3699f050 | 8,427 |
from typing import Tuple
def bigaussian(
n_particles: int,
mean: Tuple[float, float, float, float, float],
geometric_emittance_h: float,
geometric_emittance_v: float,
sigma_p: float,
) -> np.array:
"""Generate a bigaussian distributed distribution.
Args:
n_particles: Number of par... | a8c7b9cf7500fde899cdcc163a31450b59d0d7d0 | 8,428 |
def horizontal_tile(silhouette, reps = 2):
"""Places two silhouettes side-by-side with an empty line in the middle."""
silhouette = np.append(silhouette,np.zeros((silhouette.shape[0],1)),axis=1)
return np.tile(silhouette,(1,reps))[:,:] | ddccc0ff9cb7f1fba56dfc52de723f5253729952 | 8,429 |
def grads_norm(parameters):
"""get grad norms of the parameters, useful for model inspection"""
t = [p.grad for p in parameters if p.grad is not None]
return many_l2_norm(*t) | 9904f5313f63387ba0c4f139029759118f2ecae8 | 8,430 |
def django_admin_add_object(request, context):
"""show add object"""
if request and request.user.is_staff and (context.get('object', None) or context.get('model', None)):
object_class = context.get('model', None)
if not object_class:
object_class = context['object'].__class__
... | 909c79cc75913afff341eed84286edd79352fc0c | 8,431 |
def get_config():
"""Returns an instance of the configured config class.
:return: Project's defined Adyen configuration.
:rtype: :class:`AbstractAdyenConfig`
By default, this function will return an instance of
:class:`adyen.settings_config.FromSettingsConfig`. If
:data:`ADYEN_CONFIG_CLASS` is... | 16a26bd31752211d2aa7a22858f0317ba90b5bad | 8,432 |
import math
def aperiodic(amp, samples):
"""an aperiodic oscillating signal
Parameters
----------
amp : float
values range over +-amp
samples : int
number of samples to generate
Returns
-------
ndarray
"""
periods = np.abs(sine(samples, samples, 1)) + samples... | 42428a16fbfee7cf2a9d8b566fc122e9c56b7e6a | 8,433 |
import base64
def removeHs(ctab):
"""
Removes any hydrogens from the graph of a molecule. CTAB is urlsafe_base64 encoded string containing single molfile or
concatenation of multiple molfiles.
cURL examples:
curl -X GET ${BEAKER_ROOT_URL}removeHs/$(cat removeHs.mol | base64 -w 0 | tr "+/" "-_")
curl -X G... | f3064e2ce3a1db1bb260da49da2df3fb1eaf1310 | 8,434 |
def judge_key(key: str, up: any):
"""判断key是否存在"""
if dict == type(up):
if key in up:
return True
else:
for dict_key, dict_value in up.items():
if dict == type(dict_value) or list == type(dict_value):
result = judge_key(key, dict_value)
... | ee0086259343df30cfc7b72951a165b557a843f9 | 8,435 |
def apply_changes(patch_obj_dic, file_dic):
"""
If all checks are passed, write the changes to the patch file. Note that the original file is overwritten
:return:
"""
success = False
error_title = None
error_msg = None
# Checks that mutually exclusive options have not been set together. ... | ad52721ab338b0124869c32c2e08f202deeb981f | 8,436 |
def construct_1D_scan_fast(gate, swing, n_pt, t_step, biasT_corr, pulse_lib, digitizer, channels,
dig_samplerate, dig_vmax=2.0, iq_mode=None, acquisition_delay_ns=None,
enabled_markers=[], channel_map=None, pulse_gates={}, line_margin=0):
"""
1D fast scan pa... | cbbffe77187cfd923b1e9b5982fb1e2b6319a854 | 8,437 |
def assemble_f_local(ck, f_func, p1, p2, p3):
"""
Assemble the local contribution to the f_load_lv for the element
Parameters
----------
ck : np.array
basis function coef. matrix.
f_func : function
load function.
p1 : np.array
first vertex of the triangle element.
... | 9912026fbde63b0cf6780a8b3fc8131dbc99c809 | 8,438 |
def take_turn(num_rolls, opponent_score, dice=six_sided):
"""Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free Bacon).
Return the points scored for the turn by the current player. Also
implements the Hogtimus Prime rule.
num_rolls: The number of dice rolls that will be made.
oppone... | f072341dde309a7b612da896d2db348c92a7f0c4 | 8,439 |
def __sort_vertices(points):
"""Return vertices that are sorted by average center of all points."""
points = list(set(points))
if len(points) < 3:
return None
start_point = __find_average_center(points)
start_vector = Vector3D.by_points(start_point, points[0])
return sorted(points, key=lambda point:
... | b89374b1b8e06c3bcc87b074239c1cc13ecd7de4 | 8,440 |
from typing import List
from typing import Tuple
def create_feature(
tokens: List[str],
label_ids: List[int],
words_map: List[Tuple[int, int, bool]],
max_seq_length: int,
tokenizer: PreTrainedTokenizer,
cls_token_at_end=False,
cls_token="[CLS]",
cls_tok... | 7dccdf98a07ec254abc14c15bba4c5ea307e8f2b | 8,441 |
import os
def unified_genotyper(align_bams, items, ref_file, assoc_files,
region=None, out_file=None):
"""Perform SNP genotyping on the given alignment file.
"""
if out_file is None:
out_file = "%s-variants.vcf" % os.path.splitext(align_bams[0])[0]
if not file_exists(out... | 65d96b87b31508816ed3e87a53145605004d7f6e | 8,442 |
import os
def read_and_compress_table(parser, table, debug):
"""Read data from a FITS file and save it into a FITS binary table
The data are read from the FITS file specified in the "table"
section of the "parser" object (an instance of
ConfigurationParser). If "debug" is true, save additional
in... | 3533dd91f48cdba2064314dcec98c511443b319e | 8,443 |
from scipy.stats import norm, uniform
def calculate_log_likelihood_and_derivative_at_parameter_point_with_mRNA(protein_at_observations,model_parameters,mean_protein,measurement_variance,mRNA_parameters):
"""
Calculates the log of the likelihood, and the derivative of the negative log likelihood wrt each param... | 9d187b23c5a56e15c2bd900242823e5780991f7c | 8,444 |
def SEORedirectMiddleware(get_response):
"""
Intercepts 404 errors and checks the database for any defined
redirecs that match the current request path.
"""
def middleware(request):
response = get_response(request)
if response.status_code != 404:
return response
... | 750e8f3603114c8a6474f2fdfde76cefea1eacf7 | 8,445 |
def b2s(src):
"""
Convert from bytes to string
:param src: bytes
:return: string
"""
return src.decode(encoding=UTF_ENCODING) | 3a71fe7684ce57833db6861a250b0ba1d5fbfd47 | 8,446 |
def get_finetune_lfo_type(header: bytes) -> AutomationLfoType:
"""Return finetune LFO type."""
assert isinstance(value := _unpack(header, "FINETUNE_LFO_TYPE"), int), type(value)
return AutomationLfoType(value) | 2dcaf71353d0641dd1f0cac1bf83ecc720cd666b | 8,447 |
def locate(client: Client, structure: Structure) -> str:
"""Locates the respective structure."""
return client.run('locate', structure) | 93e2d83c6be7cc5d4a628233ccdadda2f9a914a5 | 8,448 |
def teraflops_for_accelerator(accel):
"""
Stores the number of TFLOPs available to a few accelerators, including driver handicaps.
Args:
accel (str): A string descriptor of which accelerator to use. Must be either "3090" or "V100".
Returns:
accel_flops (int): an integer of how many TFL... | a491beb06baf73325e2e7b5f0876e98ea312e2aa | 8,449 |
def reduced_supercell_vectors(ab, n):
"""
Returns all possible reduced in-plane lattice vectors and
transition matrices for the given starting unit cell lattice
vectors(ab) and the supercell size n
Args:
ab: a, b lattice vectors
n: (int) supercell size
"""
uv_list = []
... | fba60388b42beb170bfba96a9aeeccc4e1d74dbf | 8,450 |
import json
def jsonify(*args, **kwargs):
"""Creates a `Response` with the JSON representation of
the given arguments with an`application/json` mimetype. The
arguments to this function are the same as to the `dict`
constructor.
Example usage:
from cocopot import jsonify
@app.rout... | 04fe7d2808081f9a9f9b7eb610e168c8329298cb | 8,451 |
def logged_in_profile(client):
"""Add a Profile and logged-in User"""
user = UserFactory.create(username="george")
client.force_login(user)
return user.profile | b4ed5872cf8da789f3e6ab001b8afc556c0faa50 | 8,452 |
def get_storage_backend():
"""
Return the singleton instance of the storage backend in use.
"""
global _STORAGE_BACKEND
if _STORAGE_BACKEND is None:
module, klass = ClassLoader.split(str(config.STORAGE_BACKEND_CLASS))
cl = ClassLoader(module, klass, config.STORAGE_BACKEND_ARGS)
... | d23315854bf736637f483f1d802b868d4c45ff8a | 8,453 |
def _pr_compile(regex, cleanup=None):
"""Prepare a 2-tuple of compiled regex and callable."""
return (_re_compile(regex), cleanup) | 832e794bef679272231e336aa2128cf1457abb8d | 8,454 |
def config():
"""
Configuration via config.json (introduced in Anki 2.1)
"""
try:
getConfig = mw.addonManager.getConfig
except AttributeError:
return LEGACY_CONFIG
return getConfig(__name__) | cc099497d55ccef8195b47dd4d080695e9af370c | 8,455 |
def ping(request):
"""
This view returns a dummy json. It is meant to be used to check whether
the server is alive or not
"""
return Json(None) | 54f8d05454913b4119f1580f5d8a19a878e76c13 | 8,456 |
import numpy as np
import copy
def copy_ffn(model):
"""Copy feed forward network model.
Args:
model: A previously created ffn model
Returns:
A copy of the model
"""
#init model as list holding data for each layer start with input layer
newmodel = []
newmodel.append({
... | 5bde1163d5d53a75839b15aaa38a28ecc54b195c | 8,457 |
import tempfile
import os
import subprocess
import glob
def nlp_progress() -> TaskDB:
"""Parse a the whole nlp progress repo or a single markdown file.
Checkouts the nlp progress git repository and parses all the markdown files
in it.
Returns:
TaskDB: Populated task database.
"""
tdb... | 62a2d14d8939a3f2d20814e131771efc7ca7ec47 | 8,458 |
def is_big(label: str) -> bool:
"""Returns whether or not a cave is large based on its label"""
return label.isupper() | 7abdb0c5687e7870c96b767dc498e1f3c4ed21fe | 8,459 |
def fast_mult_polynoms(a, b):
"""Fast multiply of two polynoms in GF(2^8) using the log table
NB. This is NOT constant-time and leaks secret values in timing differences.
DO NOT USE THIS CODE TO IMPLEMENT SECURE APPLICATIONS
"""
if a == 0 or b == 0:
return 0
return POWER_X1_TABLE[(LOG_... | 3d670b2380963c50f74eb2f671ccdf7378ce58aa | 8,460 |
def get_page_for_group(user_groups, slug):
"""
Returns a page associated with user_groups given a slug.
"""
try:
page = get_pages_for_group(user_groups).get( slug = slug)
except Page.DoesNotExist:
page = None
return page | 6ea742688f07ca2ee0dd1ee4665598e074759229 | 8,461 |
def read_gps(gps_path):
"""Read GPS feed in CSV.
Expects GPS structured as:
vehicle_id: str
Internal system identification of the vehicle.
Should be unique per vehicle, and is used for tracking the
vehicle as it proceeds through the system.
route_id: str
... | 2ec09b69646b31e38b07e25bf2ffa0f0c002f52b | 8,462 |
def _ureduce(a, func, **kwargs):
"""
Internal Function.
Call `func` with `a` as first argument swapping the axes to use extended
axis on functions that don't support it natively.
Returns result and a.shape with axis dims set to 1.
Parameters
----------
a : array_like
Input tens... | 93be4e1a26dec25b74e6a9f330863ea7677cd614 | 8,463 |
def compute_autocorrelation_local(x, Fs, N, H, norm_sum=True):
"""Compute local autocorrelation [FMP, Section 6.2.3]
Notebook: C6/C6S2_TempogramAutocorrelation.ipynb
Args:
x: Input signal
Fs: Sampling rate
N: Window length
H: Hop size
norm_sum: Normalizes by the num... | 8e67de8279e0daae90ae3391064ea92b023dfafc | 8,464 |
def euclid_dist(vector_p1, vector_p2):
""" calculated the euclidean distance between 2 points """
distances = vector_p1 - vector_p2
return cp.hypot(distances[:, :, 0], distances[:, :, 1]) | 6f9d366cddb62f9ad1a8e26c9c2179fb73238a32 | 8,465 |
def _name_cleaner(agent_name):
"""Renames agent_name to prettier string for plots."""
rename_dict = {'correct_ts': 'Correct TS',
'kl_ucb': 'KL UCB',
'misspecified_ts': 'Misspecified TS',
'ucb1': 'UCB1',
'ucb-best': 'UCB-best',
'non... | e874745e804e07e385b377ec0ecd4247640ef6ce | 8,466 |
def add_training_args(parser):
"""Training arguments."""
group = parser.add_argument_group('train', 'training configurations')
group.add_argument('--experiment-name', type=str, default="gpt-345M",
help="The experiment name for summary and checkpoint")
group.add_argument('--batch... | 05c71d77320644fdaf00ef1638e76dbbce60ffb5 | 8,467 |
from typing import Optional
from typing import List
from typing import Dict
def _multi_class_confusion_matrix_plot(
thresholds: Optional[List[float]] = None,
num_thresholds: Optional[int] = None,
name: Text = MULTI_CLASS_CONFUSION_MATRIX_PLOT_NAME,
eval_config: Optional[config.EvalConfig] = None,
... | 9f670ad80ea10c05460815fd9af250d60b035d9e | 8,468 |
def innerL(i, os):
"""
Parameters
----------
i
os:OptStruct
Returns
-------
"""
ei = cal_ek(os, i)
if (os.labels[i] * ei < -os.tol and os.alphas[i] < os.C) or (
os.labels[i] * ei > os.tol and os.alphas[i] > 0
):
j, ej = select_j(i, os, ei)
alphaIol... | 1fc83191dbb16d863aef7c947408126d79c40099 | 8,469 |
import click
import logging
def create_client(ctx: click.Context, opts: ProxyContext) -> CumulocityClient:
"""Create Cumulocity client and prompt for missing credentials
if necessary.
Args:
ctx (click.Context): Click context
opts (ProxyContext): Proxy options
Returns:
Cumuloc... | cad28ef10409352fe25ae7310fbaae4a095b8a21 | 8,470 |
import struct
def get_float(data, index):
"""get a float value from data array"""
return struct.unpack('f', "".join(map(chr, data[4*index:(index+1)*4])))[0] | b78a5472bef42312bd765b6f9c58bfe9cddbf311 | 8,471 |
def gelu(tensor):
""" Gaussian Error Linear Unit - https://arxiv.org/abs/1606.08415 """
return 0.5 * tensor * (1 + tf.tanh(tf.sqrt(2 / np.pi) * (tensor + 0.044715 * tf.pow(tensor, 3)))) | acb5101815bb3cd0c30d602fefb0734707bf4acf | 8,472 |
def _uniqueElements(an_iterable):
"""
:param iterable an_iterable:
:param int idx:
:return list: has only one occurrence of each element
"""
used = []
unique = [x for x in an_iterable if x not in used and (used.append(x) or True)]
return unique | 8290d30e48c3ade4a547d7c3a8cf0c57b8d45b19 | 8,473 |
def guestbook_key(guestbook_name=None):
"""Constructs a Datastore key for a Guestbook entity with name."""
return ndb.Key('Guestbook', guestbook_name or 'default_guestbook') | fcff509ad5e48b58ffa823801af134c20e974b56 | 8,474 |
def _bias_scale(x, b, data_format):
"""The multiplication counter part of tf.nn.bias_add."""
if data_format == 'NHWC':
return x * b
elif data_format == 'NCHW':
return x * b
else:
raise ValueError('invalid data_format: %s' % data_format) | 19e5bb9419827f6e6976b1c5ed3cd40cdd676ad0 | 8,475 |
import re
def checkTableName(tables):
""" Check if table name has an underscore or not."""
bad = set()
output = []
for i in tables:
if re.search('.*_.*', i):
bad.add(i)
if bad:
output.append("These tables have underscores in the name")
for i in bad:
... | 2847c20712e6ce92367772678d058a05b5d10dc3 | 8,476 |
def load_split_from_tfds_builder(builder,
batch_size,
split,
preprocess_example=None,
augment_train_example=None,
shuffle_buffer_size=None,
... | 63c73f65cedc1fff92ce9a02ea23822c8e411439 | 8,477 |
import os
import torch
def load_model_weights(model, filename, verbose=1, cp_folder=""):
"""
Loads the weights of a PyTorch model. The exception handles cpu/gpu incompatibilities
Arguments:
model {torch module} -- Model to load the weights to
filename {str} -- Name of the checkpoint
... | b0f011e3b05d239be955df308a045496805a50c6 | 8,478 |
def analyze(tokens):
"""
表达式元素组合,形成操作树
"""
assert_non_empty(tokens)
# 数字或者操作符
token = analyze_token(tokens.pop(0))
# 如果是数字,直接放回就好了,继续求下一个,因为数字是自求解的,本身就是解
if type(token) in (int, float):
return token
# 如果是操作符,则需要组合为Exp表达式
if token in known_operators:
# 当前是操作符, 则需要检... | 369b0b3df423dd3a38e0756379442e428efb7ef3 | 8,479 |
from typing import Mapping
from typing import Any
def copy_dict(dic: Mapping[str, Any], depth: int = 1) -> Mapping[str, Any]:
"""Deep copy a dict
Args:
dic: The dict to be copied
depth: The depth to be deep copied
Returns:
The deep-copied dict
"""
if depth <= 1:
r... | a75f9ef7c8dc797ccdf47cdc3029c403b09e75cf | 8,480 |
def get_wrf_config(wrf_config, start_date=None, **kwargs):
"""
precedence = kwargs > wrf_config.json > constants
"""
if start_date is not None:
wrf_config['start_date'] = start_date
for key in kwargs:
wrf_config[key] = kwargs[key]
return wrf_config | c9e070b91ab93a7cb81a576aa799537361b7a26f | 8,481 |
from Bio import PDB
def pdb_to_structure(filename):
"""Import a structure object from a PDB file.
"""
try:
except ImportError:
print("I can't import Biopython which is needed to handle PDB files.")
raise
p = PDB.PDBParser()
structure = p.get_structure("S", filename)
for _ ... | 1b77b6bc5af75d03af847032827c07656addf4f3 | 8,482 |
def allocation_ncsist():
"""
Real Name: Allocation NCSIST
Original Eqn: IF THEN ELSE( ShiMen Reservoir Depth>=ShiMenReservoir Operation Rule Lower Limit , 6048, IF THEN ELSE( ShiMen Reservoir Depth >=ShiMenReservoir Operation Rule Lower Severe Limit, 6048*0.9 , 6048*0.8 ) )
Units: m3
Limits: (None, ... | f2b781869957d78dc59e6837a253bc0df29250bd | 8,483 |
def hamming(s1, s2):
"""Return the hamming distance between 2 DNA sequences"""
return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2)) + abs(len(s1) - len(s2)) | e3e1f3e9cc883f27d26f00c1b3c9495d29c1a139 | 8,484 |
def extract_geometric_plane(polygon: Polygon, plane_triangle_indices, tri_mesh: HalfEdgeTriangulation, normal: np.ndarray):
"""Will extract geometric details from the polygon and plane of interest
Args:
polygon (Polygon): Shapely Polygon of a flat surface
plane_triangle_indices (ndarray uint64)... | c1d3a359c013622e5ca4864e50de5c34e6001c9c | 8,485 |
import torch
def get_org_df(pr_label_f, metadata_df, seq_len):
"""
Returns the org_df given pr_label_f,metadata_df,
"""
org_r, org_c = torch.nonzero(pr_label_f, as_tuple=True)
org_df = cudf.DataFrame()
org_df["seq_row"] = cudf.Series(org_r)
org_df["org_seq_col"] = cudf.Series(org_c)
... | 543bfe8f95409eefeb792ee2f94d8518fa4a3fe3 | 8,486 |
from scipy.stats import norm
def binomial_proportion(nsel, ntot, coverage=0.68):
"""
Calculate a binomial proportion (e.g. efficiency of a selection) and its confidence interval.
Parameters
----------
nsel: array-like
Number of selected events.
ntot: array-like
Total number of eve... | 94b9d3cf766ca2f35f677a4421aabc1840097729 | 8,487 |
def nasnet_dual_path_scheme_ordinal(module,
x,
_):
"""
NASNet specific scheme of dual path response for an ordinal module with dual inputs/outputs in a DualPathSequential
module.
Parameters:
----------
module : nn.Module
... | aef487a25bc3349f14a112826ee4f8e8912dd324 | 8,488 |
import json
import traceback
def ifttt_budget_options():
""" Option values for the budget field """
if "IFTTT-Service-Key" not in request.headers or \
request.headers["IFTTT-Service-Key"] != get_ifttt_key():
return json.dumps({"errors": [{"message": "Invalid key"}]}), 401
try:
... | c987ca533fc0568e759e4e6c6affbdb7efeb4781 | 8,489 |
import sqlite3
def get_exp_date_stats(db_file_name, Table):
"""Caculate exp date stats of collection"""
conn = sqlite3.connect(db_file_name)
c = conn.cursor()
c.execute('''SELECT exp, count(exp) FROM {} GROUP BY exp'''.format(Table))
exp_dict = {}
results = c.fetchall()
for result in res... | 7641d6309939359c1d790b66a1310b5b78be99a4 | 8,490 |
import random
def create_default_identifier(node_address, token_address, target):
"""
The default message identifier value is the first 8 bytes of the sha3 of:
- Our Address
- Our target address
- The token address
- A random 8 byte number for uniqueness
"""
hash_ = sha... | ae63898d0130eda2cbc1a6e3861b288e9b1a4d10 | 8,491 |
import logging
def set_layers_to_non_trainable(model, layers):
""" Set layers of a model to non-trainable """
layers_to_non_trainable = [model.layers[i] for i in layers]
for layer in layers_to_non_trainable:
layer.trainable = False
for layer in model.layers:
logging.debug("Layer %s ... | 4f01706247984e4987d777d43d4b769cf262ee20 | 8,492 |
def print_scientific_16(value: float) -> str:
"""
Prints a value in 16-character scientific notation.
This is a sub-method and shouldnt typically be called
.. seealso:: print_float_16 for a better method
"""
if value == 0.0:
return '%16s' % '0.'
python_value = '%16.14e' % value # ... | 18072bfb5cc51e83f1c26086558abc4019e4737e | 8,493 |
def _interpolate_target(bin_edges, y_vals, idx, target):
"""Helper to identify when a function y that has been discretized hits value target.
idx is the first index where y is greater than the target
"""
if idx == 0:
y_1 = 0.
else:
y_1 = y_vals[idx - 1]
y_2 = y_vals[idx]
edg... | 7a84bc846c8446aa7449732fdb60171d6f144863 | 8,494 |
def azimuth_range_to_lat_lon(azimuths, ranges, center_lon, center_lat, geod=None):
"""Convert azimuth and range locations in a polar coordinate system to lat/lon coordinates.
Pole refers to the origin of the coordinate system.
Parameters
----------
azimuths : array_like
array of azimuths d... | a68e9e6731393f454d5725267b5a7c56e2afaedd | 8,495 |
def count_path_recursive(m, n):
"""Count number of paths with the recursive method."""
def traverse(m, n, location=[1, 1]):
# return 0 if past edge
if location[0] > m or location[1] > n:
return 0
# return 1 if at end position
if location == [m, n]:
return ... | ad31718d179bf46966117ecfa414807e6d356634 | 8,496 |
def markdown(caller):
"""Renders the argument to markdown. Useful in `{% filter markdown() %} `
blocks
Args:
caller (str): Markdown source
Returns:
str: rendered HTML
"""
return render_markdown(caller) | fd3fcea8ae9cbac660c1f8971e89baa1c61467ac | 8,497 |
from typing import List
import warnings
def aggregate_threedi_results(gridadmin: str, results_3di: str, demanded_aggregations: List[Aggregation],
bbox=None, start_time: int = None, end_time: int = None, subsets=None, epsg: int = 28992,
interpolation_method: ... | 30fed652c2073350d8683f314b40829f38e4e4ee | 8,498 |
from typing import Dict
from typing import Any
def color_menu(colno: int, colname: str, entry: Dict[str, Any]) -> int:
# pylint: disable=unused-argument
"""color the menu"""
if entry.get("__shadowed") is True:
return 8
if entry.get("__deprecated") is True:
return 9
return 2 | 090dc76475fbe7507c9687127306c34b0652e16a | 8,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.