content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import numpy
def vdisp_trailing(sdf):
"""Return the velocity dispersion in km/s for the trailing tail"""
# Go out to RA=245 deg
trackRADec_trailing=\
bovy_coords.lb_to_radec(sdf._interpolatedObsTrackLB[:,0],
sdf._interpolatedObsTrackLB[:,1],
... | 3eed9f0bdbaa84c67a09bbd52a1623dc1d66bdb3 | 63,661 |
def is_equal(M, N):
"""
Determines if both matrices are equal.
:param M: A matrix.
:param N: A matrix.
:return: True if both M and N are equal to each other. False otherwise.
"""
return np.array_equal(M, N) | ec90ca098d94217ff3b8fab5a7be0aa624986bf0 | 63,665 |
def view_election_statistics_table(self, request):
"""" View for the standalone statistics table. """
layout = ElectionLayout(self, request, 'statistics')
return {
'election': self,
'layout': layout,
'type': 'election-table',
'scope': 'statistics'
} | f6ed76fcb8172a75b13a011357870fc2f9400cbe | 63,666 |
def combineNeighborPeaks(peaks, energyScale):
""" Combine three neighboring peaks together using intensity for weighted average calculations.
The peaks must be responsed. The baseline is not calculated for the new peaks
and is set to 0.
Args:
peaks: List of Peak
energyScale: Energy sca... | 254c09988aa8c4ee0f25e83f2f0e3b35469582bb | 63,667 |
def extrinsic_euler_yxy_from_active_matrix(R, strict_check=True):
"""Compute extrinsic yxy Euler angles from active rotation matrix.
Parameters
----------
R : array-like, shape (3, 3)
Rotation matrix
strict_check : bool, optional (default: True)
Raise a ValueError if the rotation m... | 6dfb58398a872f1259eea77e03e5e402b927d618 | 63,668 |
def calc_uncertainity_polygon(lon,lat,wspd):
"""
Function creates the uncertainity polygon of storm track
Arguments:
Lon, Lat, Wind speed
Returns:
polygon
"""
error = get_ibtracs_uncertainity(wspd)
hours = np.arange(1,len(error)+1,1)
# interpolate
points_num = 10... | 6a91259f65764dc6c842d447c21765cf855223f9 | 63,670 |
def validate_installs(list_of_packages):
"""
Wrapper function to validate multiple installs
:param list_of_packages: packages to validate
:return: Dictionary of {"package_name": install_validity(true/False)
"""
package_validity = {}
for package in list_of_packages:
package = package.... | 4df6654bcbadd7059b0b3c684505003aa558ee7d | 63,672 |
def as_list(obj, tuple_to_list=False, if_none=NotImplemented):
"""
This is useful to allow arguments that are theoretically lists, but
tend to be single items in practice. As syntactic sugar, we allow
passing in these single items in some cases. For example, multiple
allowed statuses or zones migh... | d1331365111cf16919285575600f437e09cb0405 | 63,673 |
def create_whimsy_computation_tensorflow_constant():
"""Returns a tensorflow computation and type `( -> float32)`."""
value = 10.0
tensor_type = computation_types.TensorType(tf.float32)
value, type_signature = tensorflow_computation_factory.create_constant(
value, tensor_type)
return value, type_signatu... | 953b73077eda5b151a523459b26f8f7b921bde3f | 63,675 |
def estimateValueFromAgent (stateSamples, agent, rewardFn) :
"""
Use the learnt value function network through
A2C to estimate value for states.
"""
def estimateForState (s) :
cpus = list(range(C.N_PARALLEL))
affinity = dict(cuda_idx=C.CUDA_IDX, workers_cpus=cpus)
agent_ = ... | 52c3c4f377804f3b154d098768dc1c56eaa3ac61 | 63,676 |
from pathlib import Path
def reclassify_from_map(in_raster, map_values, dst_raster=None, overwrite=False):
""" Remap raster values from map_values dictionary. If the
are missing values in the dictionary 0 value will be returned
Args:
in_raster (path to raster): Input raster to reclassify
... | 93c48dee8ce42b8c31d67b5b73ff317c56ff87f3 | 63,678 |
def somme(*nombres):
"""Retourne la somme des nombre de la liste donnée
"""
total = 0
for nombre in nombres:
total += nombre
return total | 683a8b48a59d538d9883f25cf5ab8f8f2bbf9232 | 63,679 |
from datetime import datetime
def dayStart (origin):
"""Reset datetime's time part to start of the day (i.e. 00:00:00)."""
return datetime.datetime(origin.year, origin.month, origin.day) | 39909b9b6ffe7d5363e9eae2856608820a0c8a08 | 63,681 |
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/start (enter YYYY-MM-DD)<br/>"
f"/api/v1.0/start/end (enter YYYY-MM-DD/YYYY-MM-DD)"... | 1ff99658d4586de603c75ff2738a98b5c4ea48f4 | 63,682 |
def trimVersionString(version_string):
"""Trims all lone trailing zeros in the version string after major/minor.
Examples:
10.0.0.0 -> 10.0
10.0.0.1 -> 10.0.0.1
10.0.0-abc1 -> 10.0.0-abc1
10.0.0-abc1.0 -> 10.0.0-abc1
"""
if version_string == None or version_string == '':
... | ddaba8c5ed3d16cf9f1c6ce8f4c82784968b306e | 63,683 |
def filter_section_with_drugs(input_data: pd.DataFrame, drug_lex_path: str):
"""
Filter to sections where section text contains drug terms.
:param input_data: pandas dataframe with publication text
:param drug_lex_path: file path for list of drug terms to search for
:return: Dataframe with sections... | 9680ebe5252a482ab6792603b1e84f12ab77fec8 | 63,684 |
def find_builds_with_status(service, branch, target, starting_build_id):
"""Find Android builds (and their status) in the target branch whose build IDs
are >= to the provided build ID."""
build_list = None
for i in range(2):
build_list = query_for_build_status(service, branch, target, starting_build_id)
... | 7af8505bfb4de2dffbca66e7db7373160ca30158 | 63,685 |
def ReadRosterFromFile(file_name, hub_map, rosterC):
""" roster_tools.ReadRosterFromFile
PURPOSE:
Reads a roster file with the following fields:
<**Last Name>,<**First Name>,<**Grade>,<**Parent/Guardian Name(s)>,<***Teacher Name>
** - indicates always required field
*** - indicates field that i... | 44691daff187724e869d5044861a50b5fdce20e2 | 63,686 |
def extract_sectors(pred_df, thres):
"""Extracts labels for sectors above a threshold
Args:
pred_df (df): predicted sector
thres (float): probability threshold
"""
long_df = (
pred_df.reset_index(drop=False)
.melt(id_vars="index", var_name="division", value_name="probabi... | a772e965685ca8ac8cd6a52861c36e9cf7faf887 | 63,687 |
def run_CIS_checks5(region_list):
"""
Checks CIS lvl 5 (Networking).
Returns: list
"""
control = []
control.append(control_5_1(region_list))# Testing with port 3389 and 22. Add more admin ports
increment_progress()
control.append(control_5_2(region_list))# Testing with port 3389 and 22. ... | d2f2f74063425fd132a1c216550a29e3c297f993 | 63,688 |
def _formats_count_query(
storage_service_id, start_date, end_date, storage_location_id=None
):
"""Fetch information from database on file formats.
:param storage_service_id: Storage Service ID (int)
:param start_date: Inclusive AIP creation start date
(datetime.datetime object)
:param end_... | 3e89fe4c223c078271ef65b2c78b0689daf4a21c | 63,689 |
import bisect
def find_closest(numeric_list, query_number):
"""
Given a list of numbers, and a single query number, find the number in the sorted list that is numerically
closest to the query number. Uses list bisection to do so, and so should be O(log n)
"""
sorted_numeric_list = sorted(numeric_l... | ae2dad58162f38f7c1e4d7149943488a96c3c8dc | 63,690 |
def survey_year_plot(continent_code='All', country_code='All'):
"""Takes a continent code and country code and returns choropleth object"""
filtered_data = q.geo_filter(continent_code=continent_code, country_code=country_code)
figure = px.choropleth(
filtered_data,
locations="country_code"... | c0a3ca40f864c3037b4141a197305d97f95b1136 | 63,692 |
def set_starting_position(poly, ggr=None):
"""Check and set starting position."""
if not ggr:
starting_position = "upperleftcorner" # EnergyPlus default
else:
starting_position = ggr.Starting_Vertex_Position.lower()
poly = poly.order_points(starting_position)
return poly | 0c04182e3bb23e817e551a5a361fba28f812aad4 | 63,693 |
def get_zone_list(verbose=False):
"""
This function retrieves a list of all the zones
within the IDS.
Returns a list sorted by zone name, or None if
some error occurred.
"""
output = run_iquest('select order(ZONE_NAME)',
format='%s', verbose=verbose)
if not outp... | 53ccefa61836eef04d692a522f8c3248951b58b2 | 63,694 |
from io import StringIO
def get_evaluate_resource(model_name, model):
"""get resource associated with evaluate"""
parser = reqparse.RequestParser()
parser.add_argument('variable', type=str, required=True)
for var_symbol in model:
if type(var_symbol) != UndefinedFunction:
func = mo... | c4b2f4ac3b7437130e50b616387a2549d8678800 | 63,695 |
def _parse_image_format(image_link):
"""Parse an image format from a download link.
Args:
image_link: link to download an image.
>>> link = "http://blogs.elpais.com/.a/6a00d8341bfb1653ef01a73dbb4a78970d-pi"
>>> Google._parse_image_format(link)
>>> link = "http://minionslovebananas.com/ima... | cee5ec7a102cd457b1899d1229386cc5b17103e3 | 63,698 |
import random
def rand(plan, num=1):
"""Shuffle to generate new perm"""
def shuffle_tasks():
perm = plan.perm[:]
random.shuffle(perm)
return perm
return [shuffle_tasks() for _ in range(num)] | 5c4318e4be1330f0a78eeec30665626eb5802934 | 63,701 |
def get_mongo_conn(db="test"):
"""
use me like this:
collection = get_mongo_conn()["collection_name"]
collection.insert({})
"""
return MONGO_POOL[db] | 1ca41703988c4c60e44a2d667404cf40b3423399 | 63,702 |
def generate_manifest_header(manifest_id, key_size, manifest_type):
"""
Create a manifest header
:param manifest_id: Manifest id
:param key_size: Size of RSA key
:param manifest_type: Manifest type
:return Instance of a manifest header
"""
if manifest_type == manifest_types.PFM:
... | 08f5a05d89024a7b7067ca9005cd18e0bcd287a1 | 63,703 |
def stash_data(data, expire=None):
"""Stores data in an encrypted form and returns a key and a decryption secret."""
if expire is None:
expire = 60*60*24*90
try:
expire = int(expire)
assert expire > 0
except:
raise DAError("Invalid expire value")
return server.stash_d... | d51d649e596220957401bc4768277bef6e6c1146 | 63,704 |
import logging
def _sync_build_in_memory(build, result):
"""Syncs |build| state with swarming task |result|."""
# Task result docs:
# https://github.com/luci/luci-py/blob/985821e9f13da2c93cb149d9e1159c68c72d58da/appengine/swarming/server/task_result.py#L239
if build.status == model.BuildStatus.COMPLETED: # p... | 7246de3f925ec2740bef8d8a76baee4202d13725 | 63,705 |
def getMembershipDays(membership, onDate, houseDates=housedata.dates):
"""
Returns the number of days service in a membership up to the given date,
excluding periods when the House is in dissolution. The onDate is a
datetime.date.
"""
# Set the start date to the membership start date
startDate = convertMnisDat... | 4510cddea33a772ffa9999f26caae23dc70d67f6 | 63,706 |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the in... | e528f8d79f136b41fa92de5e9ac17de1fd200258 | 63,707 |
def parse_perseus_xml(files):
"""Parses the given XML files. Returns the parsed files as well as a list of files which couldn't be parsed at all."""
raw_texts = []
failed_to_parse = []
print("Parsing: ", end="")
for i, f in enumerate(files):
raw_text = ""
with open(f) as fp:
... | 8879a978a441db2fa4fc2183d627321903414693 | 63,708 |
def stetson_kernels(radius, nhalf, nbox, sigsq):
"""Stetson kernel generation."""
# Mask identifies valid pixels in convolution box
mask = np.zeros([nbox, nbox], dtype='int8')
g = np.zeros([nbox, nbox]) # Gaussian convolution kernel
row2 = (np.arange(nbox)-nhalf)**2
for i in range(nhalf+1):
... | 89acc82f196f73b0d41fdbb9f8507e05a2e32dce | 63,709 |
def good_discovery(status, device_name):
"""Checks the hdisk discovery results for a good discovery.
Acceptable LUA discovery statuses are :-
DEVICE_AVAILABLE: hdisk discovered on all the ITL paths and available.
DEVICE_IN_USE: hdisk discovered on all the ITL paths and is in-use by
the server.
... | 26e8130b39921faf84f94d6e243b09fffbee8b47 | 63,710 |
def okkOokOo(s):
""" okkookoo == PEP8, forced mixedCase by CodeWars """
return ''.join(chr(int(''.join(SCORE.get(a, '') for a in word), 2))
for word in s.split('?')) | b59b2c7d6445eb80f0d692c76943220e42c3d20a | 63,711 |
from typing import Optional
def multipletests(
srs: pd.Series,
method: Optional[str] = None,
nan_mode: Optional[str] = None,
prefix: Optional[str] = None,
) -> pd.Series:
"""
Wrap statsmodel's multipletests.
Returns results in a series indexed like srs.
Documentation at
https://ww... | 325085e348b8aae61228ca36550b8ea5871ed6b1 | 63,712 |
from unittest.mock import Mock
def _mock_channel(*, name, **kwargs):
"""Create a mock channel and associated DB record"""
if not Channel.objects.filter(name=name).exists():
ChannelFactory.create(name=name)
return Mock(display_name=name, **kwargs) | aa0003b47cc2b3382a89cb8e592df62ed91da142 | 63,713 |
from typing import List
def extract_strings(b: DeltaBytes, min_length, no_filter) -> List[DecodedString]:
"""
Extract the ASCII and UTF-16 strings from a bytestring.
"""
ret = []
for s in floss.strings.extract_ascii_strings(b.bytes):
if len(s.string) > MAX_STRING_LENGTH:
conti... | 477f33b1652e5ac25b81f9d70f35ad0aa22d302a | 63,714 |
def import_ori(filename):
""" Read in Filename for EJMT Tunnel mock model fault orientations """
#filename = 'Mock_FaultOrientations.csv'
""" Extract values and store in nested lists with filename identifier """
with open(filename, 'r') as f:
for x in range(1): # Skip header
nex... | ad9f8b5c158a372cacbe6f9449c358708af38aa2 | 63,715 |
import torch
def quantile_regression_loss(input, target, tau, weight):
"""
input: (N, T)
target: (N, T)
tau: (N, T)
"""
input = input.unsqueeze(-1)
target = target.detach().unsqueeze(-2)
tau = tau.detach().unsqueeze(-1)
weight = weight.detach().unsqueeze(-2)
expanded_input, exp... | 808749c54df36a150c18fccd638bf0e85272a458 | 63,717 |
from typing import Tuple
def settings_credit_callback(update: Update, context: CallbackContext) -> Tuple[str, InlineKeyboardMarkup, int]:
"""Handles the settings_foto_cane callback.
Adds the user_id to the table of credited users, if it wasn't already there
Args:
update (Update): update event
... | 0e90285a52230260d778fe2f0300af21ece802a9 | 63,718 |
def get_spotting(ID):
"""
Function to get one spotting document from Elasticsearch
Params:
ID::str
id of the spotting document
Returns:
doc::dict
The document retrieved from ES
"""
if not ID:
return False
try:
global INDEX
ref... | 4d511758cb270f4cf023e40baabc534efadc8d98 | 63,719 |
from typing import List
from typing import Callable
def parametrize_over_experiments(models: List) -> Callable:
"""Parametrize a TestCase over different kind of experiments.
Args:
models: list of model descriptions. The ``TestCase`` will be
repeated for each of the entries in the list.
... | 351e2a7c8be2e5af61bcd8e06bee288e4504dac6 | 63,723 |
def open_opencart_admin_url(driver, request):
"""Get base URL and attend admin link"""
url = 'admin/'
return driver.get("".join([request.config.getoption("--address2"), url])) | 0c1d0493833b98869324bcbe65ee8f8888fd6c5c | 63,724 |
import copy
def GetFilteredEvents(events, filteredIndex):
"""
returns a class of filered events by index's wanted
:param events: class of events in current time
:param filteredIndex: indexs of events watned
:return: class of filtered events
"""
eventsPos = copy.deepcopy(events.po... | 0e5b93afd95cba439a620a85d8e88ec4ddc90f82 | 63,725 |
import copy
def build_single_tree(data, data_oob, y_i, y_nn_i, d_i, x_i, w_i, x_type,
x_values, x_ind, x_ai_ind, c_dict, mmm, n_min, alpha_reg,
node_table, pen_mult, regrf=False):
"""Build single tree given random sample split.
Parameters
----------
data : ... | 058858ce2df1be1f5e460ed1b54bd3b94acced52 | 63,726 |
import random
import base64
def password_encrypt(text: str, key: str):
"""translate from encrypt.js"""
_rds = lambda length: ''.join([random.choice('ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678') for _ in range(length)])
pad = lambda s: s + (len(key) - len(s) % len(key)) * chr(len(key) - len(s) % len(... | 17af8d702a536d48e67c40fab3455761746ae1f3 | 63,727 |
import json
def load_config(path: str):
"""
Loads a config file as a spec_config object
:param path: The path to the config file
:return: A loaded spec_config or None
"""
try:
with open(path, 'r') as f:
return json.load(f, cls=spec_decoder)
except:
return None | 06d77f27a10872cde047bb96ebcc28733fc763f7 | 63,728 |
from re import T
def index_fn(model_predict, input_var, target_var):
"""
Theano function returns an array containing boolean values that indicate
whether predicted label matches target_var
"""
index_temp = T.eq(T.argmax(model_predict, axis=1), target_var)
return theano.function([input_var,ta... | dc2ebcc25a5d61f5c12c661a91e12519336f9672 | 63,729 |
def change_encoding_improve(infile, outfile, enc1, enc2="utf-8",
process=None, fLOG=noLOG):
"""
Changes the encoding of a text file, removes quotes.
By default *process* is @see fn process_line
but the function has access to the distribution of the number of columns
in th... | 829aff6c56d765300a238d4d7c1b754793db4ed7 | 63,730 |
import torch
def compute_feature(block: torch.Tensor) -> list:
"""Compute features.
Args:
block (torch.Tensor): 2D image block.
Returns:
list: Features with length of 18.
"""
feat = []
alpha, beta_l, beta_r = estimate_aggd_param(block)
feat.extend([alpha, (beta_l + beta_r... | 0302d51a07050e516f92120181bc86912b20eaab | 63,731 |
def stop_es(bot, update):
"""Ends the automaton"""
logger.info('%s (@%s) stopped the bot', update.message.from_user.first_name, update.message.chat.username)
update.message.reply_markdown(st.strings["force_end"])
return bot.ConversationHandler.END | d920bbfc9986834fa5f869197d592ffc380a6538 | 63,732 |
def pdf_gaussian_algebraic(
returns: np.ndarray, K: float, L: float, N: float, Lambda: float
) -> np.ndarray:
"""Computes de one dimensional Gaussian-Algebraic PDF.
:param returns: numpy array with the returns values.
:param K: number of companies.
:param L: shape parameter.
:param N: strength ... | 6508ee67164ce996c4502d6f710e1fb7be690a2b | 63,734 |
def documentation_tests(session):
"""Run documentation tests."""
return docs(session, batch_run=True) | 058f31d789491f392e0eee06e219298519405ac4 | 63,735 |
from typing import List
from typing import Tuple
from typing import Any
def paras_to_sents(paras: List[str],) -> Tuple[List[Any], List[Any], str]:
""" sent-segment paras sents list, slice_list and lang
"""
sents: List[str] = []
slice_list: List[slice] = []
lang: str = Text(" ".join(paras[:30])).de... | 7ea6e9123acc749d3c0de5e7744980c2ae7172e9 | 63,736 |
def export(signature, **kws):
"""
Construct a decorator that takes a function and exports one
A signature is a string with
name ret_type(arg_type, argtype, ...)
"""
name, restype, argtypes = _process_sig(signature)
return _internal_export(name=name, restype=restype, argtypes=argtypes, **kw... | faef680517a36f2759cc4c825f9e60ffe6ada335 | 63,737 |
def multi_generator(gan, z, num, share_params = True, reuse = False):
"""
Args:
gan : instance of a generative adversarial network
num: Number of the generator
reuse : Whether you want to reuse variables from previous
share_params : Whether weights are tied in initial layers... | 2c998300aa0c9331524286bf9d41b06443bae9d0 | 63,738 |
import binascii
import re
import struct
import pathlib
def ProcessPlugxXORFile(inFile,PlugxData,pos):
"""
IN: PlugX data to decrypt.
OUT: Bool True or False
Description:
Decrypts PlugX DAT file and assumes files are not compressed
"""
PlugX_Decrypted = Decrypt_XOR( PlugxData,pos )
if ... | a53a17bde0ed1942cb76f14f58cfe7fb125cda68 | 63,739 |
def count_features_type(types, include_binary=False):
""" Counts two or three different types of features
(binary (optional), categorical, continuous).
:param types: list of types from get_type
:returns a tuple (binary (optional), categorical, continuous)
"""
if include_binary:
return (
... | 4158122256c9a407f58987d278657e4a006e6a13 | 63,740 |
def CRy(control: int, target: int, angle: float) -> QCircuit:
"""
Convenience initialization CRy (controlled Pauli Y Rotation)
Parameters
----------
control: int
control qubit
target: int
target qubit
angle:
Hashable type (will be treated as Variable) or Numeric type... | e9bd8dd87a32f7ca604c0a05ebb81309176308b5 | 63,741 |
def _with_iteration(fn):
"""Uses iteration to produce vmap-like output."""
def wrapper(*args):
outputs = []
# Iterating over the first axis.
for inputs in strict_zip(*args):
outputs.append(fn(*inputs))
return jax.tree_util.tree_multimap(lambda *x: jnp.stack(x), *outputs)
return wrapper | 00855ddb1d85304af38152e7961d8b89ef5c09f8 | 63,742 |
def optimize(w_p, w_a, w_f, w_e, corpus_weights, scenario, char_set, startsolution="", fixation_constraints=1,
coherence_constraints=1, capitalization_constraints=1):
"""
Optimizes the pre-defined scenario with the given weights.
Parameters:
w_p, w_a, w_f, w_e: weights for the individu... | 34439faa3bef324d3658f64dbdc680eb39cbca7d | 63,743 |
import torch
def sequence_cross_entropy_with_logits(logits, targets, mask, label_smoothing, reduce):
# type: (Tensor, Tensor, Tensor, float, bool)-> Tensor
"""
label_smoothing : ``float``, optional (default = 0.0)
It should be smaller than 1.
"""
# shape : (batch * sequence_length, num_cla... | db05c49a15287999a8864fe8b789d671495e82b3 | 63,744 |
def areafiltering_remove_larger_objects_binary(image, kernel=None, n=None):
"""
Removes all objects in the image that have an area smaller than
the threshold specified.
Additional Arguments
--------------------
n : int
Specifies the threshold.
"""
nb_components, output, s... | 9e64432afa47bbb8e39455abd83ced27b2504502 | 63,746 |
def dsdlogdp(dp, n, gm, gsd):
"""
Discrete PDF for a surface-weighted lognormal
particle size distribution.
:param dp: Particle diameters at which to evaluate
the PDF in building the discrete model.
:type dp: numpy array
:param n: The area under the curve of the continuous PDF
... | ee268df8370a35aada1e3a03c4065e521142e2ff | 63,748 |
def is_pandas_module(fullname: str) -> bool:
"""Check if a fully qualified name is from the pandas module"""
return fullname.startswith("pandas.") | 0becdbfd7c1c4f5b7990cbc0466a6e45f25acb14 | 63,749 |
import io
def starting_metadata(overrides):
"""Fake the xdata associated with a brand new submission, adding in `overrides` to tweak test cases."""
d = io.get_default_metadata()
d["job_id"] = "fake_job_id"
d.update(overrides)
return d | 75ee436b3ef65975d04920ad75ba972af4d39294 | 63,750 |
def validate_port_operation(session, row):
"""Validate port operation based on dependencies.
Validate port operation depending on whether it's dependencies
are still in 'pending' or 'processing' state. e.g.
"""
if row.operation in (sdn_const.POST, sdn_const.PUT):
network_dict = jsonutils.lo... | 41f19871ce074535a50d50242298fa547b7ebdd0 | 63,751 |
def sigmoid(z):
"""The sigmoid function"""
try:
z=1 / (1 + np.exp(-z))
except OverflowError:
pass
# print(z)
# sys.exit()
return z | 8dbf9418b97de631fb1081f618ceabfaa2d0ef8d | 63,752 |
from functools import reduce
def unitary_to_monodromy_coordinate(unitary):
"""
Given a unitary matrix, produces its alcove coordinate.
"""
unitary = unitary * np.linalg.det(unitary) ** (-1 / 4)
sysy = np.array([
[0, 0, 0, 1],
[0, 0, -1, 0],
[0, -1, 0, 0],
[1, 0... | a3901f9f814c3bf09be213288f8cecacd4aab9b0 | 63,755 |
from typing import Mapping
def _add_empty_values(step: rlds_types.Step,
spec: Mapping[str, tf.TensorSpec]) -> rlds_types.Step:
"""Adds zero elements to step for the keys in spec not present in step.
Args:
step: Dictionary representing a Step.
spec: Tensor spec.
Returns:
Dicti... | d4aba17659aa84646d7c214b8447a16432f6b2f4 | 63,756 |
import pickle
import base64
def merge_cart_cookie_to_redis(request, response, user):
"""
用户登录时合并购物车数据到redis方法
:param request: 请求的request对象
:param response: 返回的响应response对象
:param user: 登录的用户对象
:return: response对象
"""
# 从cookie中取出购物车数据,
cookie_cart_str = request.COOKIES.get('cart')
... | 039d0e706f55ee7a4cd04361a68a33ef1f7b67bb | 63,757 |
import itertools
def _schedule_menu(update, context): # pylint: disable=unused-argument
"""Present the user the scheduling options"""
chat_id = update.callback_query.message.chat_id
comics = database_query("SELECT name FROM sources")
buttons = []
for name in itertools.chain.from_iterable(comics)... | 7cb1b81771f0ef4d60f4b31d0695aa2c9a1fd23d | 63,758 |
from re import A
import io
def pure(a: A) -> Resource[R, E, A]:
"""
A Resource that always returns the same constant.
"""
return Resource(io.pure((a, noop_close))) | 10900bd6582d0489cf63d0b9f667d6ddb6819d5a | 63,759 |
def find_func(identifier: str):
"""Find the function of an identifier that has been registered"""
return [k for k, v in _AI_REGISTRY.items() if v == identifier][0] | 3c9451ca8596d7c23ee5c360d9cd6bc9d050793a | 63,760 |
def _Scan():
"""Checks that license meta-data is present for all third-party code.
Returns:
Whether the check succeeded.
"""
third_party_dirs = _FindThirdPartyDirs()
# First, check designated third-party directories using src/tools/licenses.py.
all_licenses_valid = True
for path in sorted(third_part... | 3fb2750dcc65d6a8187e32166e4a6e155e1ee0d6 | 63,761 |
def set_mapping(joystick, mapping):
"""Set the button mapping.
Note:
Hat keys should have a set value for the proper quadrant.
Args:
joystick (Joystick/str): Joystick object or String GUID
mapping (dict): Dictionary of name: Key values to map to the joystick/game controller.
R... | 065988362e34bb25a4d3013f5a62df5abdfe7403 | 63,762 |
def create_raster(*args, **kwargs):
"""Shortcut for `Dataset().acreate_raster`
>>> help(Dataset.create_raster)
See Also
--------
- :py:func:`Dataset.create_raster`
- :py:meth:`Dataset.acreate_raster`
"""
return Dataset().acreate_raster(*args, **kwargs) | c6795876482d2c515505123a203675446ec30675 | 63,764 |
from typing import Optional
import random
import io
def random_digits(length: int = 32, base: int = 10, upper: bool = False, rnd: Optional[random.Random] = None) -> str:
"""
Overview:
Create random digits.
Arguments:
- length (:obj:`int`): Length of the digits, default is 32.
- ba... | 680a5201e183cf57e56adea1e79718026beda052 | 63,765 |
def process_manual_category(tag, manual_tag):
"""
处理category信息
"""
replace_tag = str(manual_tag)
if str(manual_tag) in ["1", "1.0"]:
replace_tag = tag
if "[" and "]" not in replace_tag:
tag_list = replace_tag.split(",")
else:
tag_list = eval(replace_tag)
return... | 8303cd69df4c5dce47a2dcc4546ef1490f2b2f1b | 63,766 |
def squeeze_first(inputs):
"""Remove the first dimension in case it is singleton."""
if len(inputs) == 1:
inputs = inputs[0]
return inputs | c2c0cabc873baf88ce7673f2c8889fedce0f05da | 63,767 |
from rpy2.robjects import numpy2ri
import copy
def pen_rf_importance(X, y, cost_vec=None, cost_param=0, num_features_to_select=None,
imp_type="impurity", min_samples_leaf=1,
n_estimators=500, rf_importance_vec=None, is_disc=None):
""" Cost-based feature ranking with pen... | 637095abac615829d5167eb9185c43ea039c4598 | 63,768 |
def estimate_best_parameters(grid, best_grid_pars=None):
"""
Estimate the best parameters by interpolating the grid
parameters:
============
- grid: pd.DataFrame
Contains the full grid. Get this by calling read_chi2_output()
- best_grid_pars: pd.Series or dict
... | 2aa1be84de6f8c8a1000d86ae6bae903743bf1fd | 63,769 |
def get_total_distance_of_path(path, table):
"""
Calculates the total distance of an individual bee's path.
Terminates at starting node to complete cycle.
"""
# Creates a copy of path, puts head at end of list.
# Zip lists to create pairs of neighbor coords,
# will create a cycle that termin... | d6c655b7bbed075dc8323d5d60ee128b8693d792 | 63,770 |
def shift_point(point, latitude_shift_km, longitude_shift_km):# -> tuple(float, float):
"""Shifts the coordinates of a given point.
Args:
point (tuple): Starting point as (latitude, longitude), in degrees
latitude_shift_km (float): Latitude offset in kilometers
longitude_shift_km (float... | 36544b82d10e3bae93f343757fdcd654f7f4a78b | 63,771 |
import time
def timing(func):
"""
Wrapper for class instance methods enabling the timing of execution.
Important for measuring speed and performance measurement.
Parameters
___________
func : func
Function to be wrapped and timed following execution.
Returns
________
wrap... | d84d51959be1def284fb7d6a6264c4c1138acd85 | 63,772 |
from typing import Dict
import torch
from typing import Tuple
def compute_accuracy(output_tensors_by_model: Dict[str, torch.Tensor],
target: torch.Tensor,
topk: Tuple = (1,),
) -> Dict[str, Dict[str, torch.Tensor]]:
"""Computes the accuracy over the k... | 68228b68e26f502f162df6fa902401c2e5cda981 | 63,773 |
def is_valid_string_minsize(param, minsize=None, required=True):
"""Checks if the parameter is a valid string and his size is more than minsize.
If the parameter minsize is None than the size is ignored
If the parameter required is True than the string can not be None
@param param: Value to be validate... | b1ed83ef3b44cf94f02fadf31f42ac9fe40679fa | 63,774 |
from typing import Counter
def removeInsignificantNodes(dataframe,filename = None,csvSeparator = ';'):
"""
Removes nodes that occur only once, as they are just the supposed ends of given tube.
Parameters
----------
dataframe : pandas.DataFrame()
Dataframe containing arranged da... | 0aa345d257aba84e67a73845a795f820de9190dd | 63,775 |
def _phaseSpaceThresh(u):
"""
Implements the Goring+Nikora2002 despiking method, with Wahl2003
correction.
"""
if u.ndim == 1:
u = u[:, None]
u = np.array(u) # Don't want to deal with marray in this function.
Lu = (2 * np.log(u.shape[0])) ** 0.5
u = u - u.mean(0)
du = np.zer... | dd70d5fae352fedc6a6e9519697747d99645aa1e | 63,776 |
def run_command(cmd_name):
"""
Executes a single Waf command. Called by :py:func:`waflib.Scripting.run_commands`.
:param cmd_name: command to execute, like ``build``
:type cmd_name: string
"""
ctx = Context.create_context(cmd_name)
ctx.log_timer = Utils.Timer()
ctx.options = Options.options # provided for conv... | 6c0a6b4173b7ea5c0fb63c9a8cdd9c9687771fa5 | 63,778 |
from analysis_functions import unique
from numpy import median,std,cast,float32,any,where
def images_zinger_replaced(images,sigma=5.730729):
"""Returns images_zr after replacing zingers in images with median values.
Zingers are identified according to statistical criteria. Also returns the
indices for ima... | 2ece2c42f4cdcadf4d981de83b0b32d0ad504e61 | 63,780 |
def get_constant(name):
"""Use this to get the value of a VBA constant.
@param name (str) The name of the VBA enum constant to get.
@return (int) The enum value if the given name names a VBA enum
constant, None if not.
"""
name = safe_str_convert(name).lower()
if is_constant(name):
... | b8a165397fc7ac02462f5319bdc3d490c12daab6 | 63,781 |
def _create_line2d_collection(coords, indices, infos=None, picker=False, **kwargs):
"""
Generic function to create a LineCollection from coordinates.
:param coords: list of line coordinates (list should look like this: \
`[[(x11, y11), (x12, y12), (x13, y13), ...], [(x21, y21), (x22, x23), ...], ..... | d2af45a15f4d180bcca4b144173e00042e2dfd0c | 63,782 |
import pickle
import math
def fitting_shape_coefficients(filename, bounds='Default', n=5,
return_data=False, return_error=False,
optimize_deltaz=False, solver='gradient',
deltaz=None, objective='hausdorf',
... | d62d4186d3892af622eae1edbe5b64572197d6ae | 63,784 |
def find_executable(executable):
"""Return the full path to an executable searching PATH."""
for path in _find_executables(executable):
return path
return None | 7beca9f748fe22b0dfb982cb880e6ad858b37faf | 63,785 |
def uniformCostSearch(problem):
"""Search the node of least total cost first."""
nv = [] # Initialize empty array for visited nodes
s = util.PriorityQueue() # Initialize priority queue for fringe
s.push((problem.getStartState(), ()),... | c4769a250d618eae055d39b0fe390793f86eca36 | 63,786 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.