content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pack(a: ArrayLike, ox: int, oy: int, wx: int, wy: int, sx: int, sy: int, px: int = 0, py: int = 0,
is_column: bool = True) -> ShapeletsArray:
"""
Reverses the :obj:`~shapelets.compute.unpack` operation
For a thorough explanation of this method, consult the `ArrayFire documentation <https://arr... | ac1af1eeb76fed5ecf4a1d68f17a6683415a2f6d | 35,259 |
def maybe_create_token_network(
token_network_proxy: TokenNetworkRegistry, token_proxy: CustomToken
) -> TokenNetworkAddress:
""" Make sure the token is registered with the node's network registry. """
block_identifier = token_network_proxy.rpc_client.get_confirmed_blockhash()
token_address = token_prox... | 1c477f8ad02ac99c2039d59dc04eef5f6ea6b1ed | 35,260 |
def rmsprop(grad, init_params, callback=None, num_iters=100,
step_size=0.1, gamma=0.9, eps=10**-8):
"""Root mean squared prop: See Adagrad paper for details."""
flattened_grad, unflatten, x = flatten_func(grad, init_params)
avg_sq_grad = np.ones(len(x))
for i in range(num_iters):
g ... | 6c794d5a16dc7b46c055edfb714995f00450eb92 | 35,261 |
import re
def parse_transceiver_dom_sensor(output_lines):
"""
@summary: Parse the list of transceiver from DB table TRANSCEIVER_DOM_SENSOR content
@param output_lines: DB table TRANSCEIVER_DOM_SENSOR content output by 'redis' command
@return: Return parsed transceivers in a list
"""
res = []
... | 9a9e069543a8a80b9e741452c37ed1c665b56398 | 35,262 |
def get_excerpt(post):
"""Returns an excerpt between ["] and [/"]
post -- BBCode string"""
match = _re_excerpt.search(post)
if match is None:
return ""
excerpt = match.group(0)
excerpt = excerpt.replace(u'\n', u"<br/>")
return _re_remove_markup.sub("", excerpt) | b417fc18604020e91a9b5b4f4b154fba7fcbcdc1 | 35,263 |
def dropblock(net, is_training, keep_prob, dropblock_size,
data_format='channels_first'):
"""DropBlock: a regularization method for convolutional neural networks.
DropBlock is a form of structured dropout, where units in a contiguous
region of a feature map are dropped together. DropBlock works bet... | de401f315590505e5db9b58c78a13fdaa3b7f1bb | 35,264 |
def certify(String, cert, password):
"""check a certificate for a string"""
return certificate(String, password) == cert | 05ecd81e4738c4304e7d37c6c530035375ded09b | 35,266 |
def is_same_float(a, b, tolerance=1e-09):
"""Return true if the two floats numbers (a,b) are almost equal."""
abs_diff = abs(a - b)
return abs_diff < tolerance | a8c10ae330db1c091253bba162f124b10789ba13 | 35,267 |
def generate_grid_speed(method, shape, speed_range):
"""Generate a speed distribution according to sampling method.
Parameters
----------
method : str
Method for generating the speed distribution.
shape : tuple
Shape of grid that the speed distribution should be defined on.
spee... | 700b1a6341bc1f218be04ff957ee3d02f9520adf | 35,268 |
def common_atoms(cycle1, cycle2):
"""
INPUT: two cycles with type: list of atoms
OUTPUT: a set of common atoms
"""
set1 = set(cycle1)
set2 = set(cycle2)
return set1.intersection(set2) | 1e85887a6199bf88a71709057c79025c0937a420 | 35,269 |
def get_two_body_decay_scaled_for_chargeless_molecules(
ion_pos: Array,
ion_charges: Array,
init_ee_strength: float = 1.0,
register_kfac: bool = True,
logabs: bool = True,
trainable: bool = True,
) -> Jastrow:
"""Make molecular decay jastrow, scaled for chargeless molecules.
The scale f... | 97ded768c3c0f9b61d3f5fc0e313b072b7ba241f | 35,271 |
def compute_huffman_code(message_probs):
"""
The input is a dictionary of messages, and their relative probabilities (which must add to 1).
The output is a dictionary of each message and it's new codeword (a bytestring) in the Huffman encoding.
"""
return tree_to_encoding(message_tree(message... | fa760829736810ec908ea2ed9103937477971a2d | 35,272 |
from typing import Optional
from typing import Dict
from typing import Any
def genomics_cnn(batch_size: int,
len_seqs: int,
num_motifs: int,
len_motifs: int,
num_denses: int,
num_classes: int = 10,
embed_size: int = ... | 5553dfda33e2596ba3372d9b7158f9964bfd6cfd | 35,273 |
def setDuration(*args):
"""setDuration(ALInterpolationBangBangAcceleration pObject, float pDuration)"""
return _almathinternal.setDuration(*args) | 74f8bf125266a0174aa39f6e7284854bf066a32f | 35,277 |
def regex(pattern):
"""
Does a pattern search using the system's `find` utility
:param pattern: a pattern you intend to search for
:return: String
"""
cmd = "find " + MIGRATION_FOLDER + " -type f -exec grep -il " + pattern + " {} +"
out = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stder... | 5b5df47dc85239db2294fa36411d259617756186 | 35,278 |
def _mp_fabber_options(wsp):
"""
:return: General Fabber options for multiphase decoding
"""
# General options. note that the phase is always PSP number 1
options = {
"method" : "vb",
"noise" : "white",
"model" : "asl_multiphase",
"data" : wsp.asldata,
"mask" ... | af1c724bd9b88a0d76e7c7d18a3fa2b19591984e | 35,279 |
def get_player_objects_from_challenge_info(player, should_be_completed=False, search_by_discord_name=True):
"""
Search for a challenge in the DB corresponding to the player
param str/int player: The gamertag or id of the player to search for
param bool should_be_completed: If the challenge should alrea... | e4a39d3a72063b41d5b9b92f0b1535ba164beeb1 | 35,280 |
def get_output(interpreter, score_threshold, labels):
"""Returns list of detected objects."""
boxes = output_tensor(interpreter, 0)
class_ids = output_tensor(interpreter, 1)
scores = output_tensor(interpreter, 2)
count = int(output_tensor(interpreter, 3))
def get_label(i):
id = int(clas... | 83518a28025d7d39bf475cd0f6aa222ad7197659 | 35,282 |
def provide_session(func):
"""
Function decorator that provides a session if it isn't provided.
If you want to reuse a session or run the function as part of a
database transaction, you pass it to the function, if not this wrapper
will create one and close it for you.
"""
@wraps(func)
de... | d11233a852a8c2f4ac7a95179b588e7b497bbf3a | 35,283 |
def encode_urlencoded_form(fields):
"""
Encode dict of fields as application/x-www-form-urlencoded.
"""
body = urlencode(fields, doseq=1)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
return body, headers | 26d4b99070e8d354775f7f2b6e97673dedd582f0 | 35,284 |
def process_wrapper(row, seq, cds_seq, seq_lookup, tile_begins, tile_ends, qual, locate_log, mutrate, base,
posteriorQC, adjusted_er):
"""
Wrapper function to process each line (pair of reads)
"""
mut_parser = locate_mut.MutParser(row, seq, cds_seq, seq_lookup, tile_begins, tile_ends... | 19547caddd84c1eb54b32525babf4d8b624aea70 | 35,285 |
def default_cfg():
"""
Set parameter defaults.
"""
# Simulation specification
cfg_spec = dict( nfreq=20,
start_freq=1.e8,
bandwidth=0.2e8,
start_time=2458902.33333,
integration_time=40.,
ntimes=4... | 0b76e2166ce17d6ab42e4f72d7003ba6c03b11f6 | 35,286 |
def merge_outputs(*streams: Stream) -> OutputStream:
"""Include all given outputs in one ffmpeg command line."""
return MergeOutputsNode(streams).stream() | bd6dee8b54843556426a01f691f87f28a62c1a99 | 35,287 |
def softmax(vector, theta=1.0):
"""Takes an vector w of S N-element and returns a vectors where each column
of the vector sums to 1, with elements exponentially proportional to the
respective elements in N.
Parameters
----------
vector : array of shape = [N, M]
theta : float (defa... | 06b4df32e5a04b49e3eaa1626638dad845c4b4a0 | 35,288 |
def scaled_elementary_effect_i(
model, i_python, init_input_pars, stepsize, sd_i, sd_model
):
"""Scales EE by (SD_i / SD_M)"""
ee_i = elementary_effect_i(model, i_python, init_input_pars, stepsize)
return ee_i * (sd_i / sd_model) | c345c4e40a58b0ac9228edb0cd9e96a05d28e1db | 35,289 |
def arch_mnasnet_b1(variant, feat_multiplier=1.0, **kwargs):
"""Creates a mnasnet-b1 model.
Ref impl: https://github.com/tensorflow/tpu/tree/master/models/official/mnasnet
Paper: https://arxiv.org/pdf/1807.11626.pdf.
Args:
feat_multiplier: multiplier to number of channels per layer.
"""
... | 25a9a0c0f4a026f122c73139cb8464c47fae299a | 35,290 |
def accession(data, location):
"""
Generate an accession for the given location in data.
"""
return "{ac}:{gene}".format(
ac=parent_accession(location),
gene=data["gene"],
) | a8023857b812b510990c6161194b8f85832df14a | 35,291 |
def poly_oval(x0,y0, x1,y1, steps=20, rotation=0):
"""return an oval as coordinates suitable for create_polygon"""
# x0,y0,x1,y1 are as create_oval
# rotation is in degrees anti-clockwise, convert to radians
rotation = rotation * pi / 180.0
# major and minor axes
a = (x1 - x0) / 2.0
b = (... | 7a188676654ca47a53da33df40ac16387ecaa490 | 35,292 |
def not_found(request):
"""Error page for 404."""
response = render(request, "projectile/404.html")
response.status_code = 404
return response | fb17b8f1cdcdfa530adb569abc9b006ed2868492 | 35,293 |
def reset_universe_id():
"""
reset_universe_id()
Resets the auto-generated unique Universe ID counter to 10000.
"""
return _openmoc.reset_universe_id() | bd7815a749e4d89c8d3a78aea1b24046db9c78bf | 35,295 |
from typing import Union
def native_mean(data: Union[list, np.ndarray, pd.Series]) -> float:
"""
Calculate Mean of a list.
:param data: Input data.
:type data: list, np.ndarray, or pd.Series
:return: Returns the mean.
:rtype: float
:example: *None*
:note: *None*
"""
data = _... | 3d62a3fdbb77ae0dbc8b19eaefee40abe96d3888 | 35,296 |
import json
def dataset_info_4_biogps(request, ds_id):
"""
get information about a dataset
"""
ds = adopt_dataset(ds_id)
if ds is None:
return general_json_response(GENERAL_ERRORS.ERROR_NOT_FOUND,
"dataset with this id not found")
s = json.dump... | d38f3bde125cb20a48a2842bdc8021f3eb032c8c | 35,297 |
def _set_reducemax_attrs(desc_d, attrs):
"""Add addition attributes for ReduceMax."""
backend = desc_d['process']
if backend == 'cuda' and _reducemax_pattern(desc_d)[0]:
attrs['enable_tile_c0'] = True
elem_per_thread = 4
blockdim_x = 64
blockdim_y = 16
griddim_x = 1
... | d5b50da5b3097690a0cc2ab27bbac47448f35bb7 | 35,298 |
def getTail(compiler,version):
"""
Function which generates the Tail of a
Compiler module file.
@input compiler :: compiler name ('intel','pgi',..)
@input version :: version of the compiler
@return :: list of Lua lines
"""
strA = 'local version = "{0}"'.format(version)
... | 46df63461d05b26fbc5e5a45e6162a2794f92ed1 | 35,299 |
def make_attr_string(attr):
"""Returns an attribute string in the form key="val"."""
attr_string = ' '.join('%s="%s"' % (k, v) for k, v in attr.items())
return '%s%s' % (' ' if attr_string != '' else '', attr_string) | 7185a6e725349313a4cc67ae643a18d9ab63c871 | 35,300 |
def optimize_weights(instrument, sample):
"""Optimize the weights on a particular sample"""
guess = [1.0] * sample.shape[1]
bounds = [(0.0,5.0)] * sample.shape[1]
def function(w, instrument, sample):
"""This is the function that is minimized iteratively using scipy.optimize.minimize to find the ... | f5070a76a7cb2a3210caee01928e9ae5b83055a3 | 35,301 |
from datetime import date
def voto(ano):
"""
FUNÇÃO QUE VALIDA A IDADE DO ELEITOR
:param ano: ano de nascimento
:return: idade menor que 16 anos: NÃO VOTA
idade entre 16 e 17 anos e acima de 65 anos: VOTO OPCIONAL
idade entre 18 e 65: APTO A VOTAR
"""
idade = date.tod... | ccd103a7fcd31d021c1b563df3c883d8ea81d668 | 35,303 |
import curses
def new_border_and_win(ws):
"""
Returns two curses windows, one serving as the border, the other as the
inside from these *_FRAME tuples above.
"""
return (
curses.newwin(ws[1][1], ws[1][0], ws[0][1], ws[0][0]),
curses.newwin(ws[1][1] - 2, ws[1][0] - 2, ws[0][1] + 1, ws[0][0] + 1),
) | cec302bda38ba5fa9d0c88dbfac1c501984a96a0 | 35,304 |
import socket
def mk_sock(mcast_host, mcast_ip, mcast_port):
"""
multicast socket setup
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setsockopt(
socket.IPPROTO_IP,
socket.IP_ADD_M... | 702a95e5baec4ecf54206f8f16cfa22d8365f8a0 | 35,307 |
def next_line_start_or_here(text, pos):
"""Find next line start, or `pos` if `pos` is already a line start
"""
if pos == 0 or (pos-1 < len(text) and text[pos-1] == "\n"):
return pos
return next_line_start(text, pos) | 623be9a39064e2a67fc79ca0a12e95477071fc35 | 35,309 |
def getimdata(cubenm, verbose=False):
"""Get fits image data
"""
if verbose:
print(f'Getting image data from {cubenm}')
with fits.open(cubenm, memmap=True, mode='denywrite') as hdu:
dxas = hdu[0].header['CDELT1']*-1*u.deg
dyas = hdu[0].header['CDELT2']*u.deg
nx, ny = hd... | 6ea45ba1dbbf46d9d6518a28e643bb67d3a6d627 | 35,310 |
import math
def N(latitude):
"""
Transverse radius of curvature.
Returns radius of curvature in east-west direction.
latitude: Latitude in radians.
"""
return a/math.sqrt(1-e2*pow(math.sin(latitude),2.0)) | ac1bbf3c7f6aa28251d25a584ec283a09b9e01b5 | 35,311 |
def cmd(command_id):
"""
A helper function for identifying command functions
"""
def decorator(func):
func.__COMMAND_ID__ = command_id
return func
return decorator | cff8664ad18c78629bb3c1b4946be592142711e0 | 35,312 |
import json
def getBatchExperiments():
"""
return the information related to the experiments of a batch
:return: informations of the experiment
:rtype: Dict
"""
data = request.json['data']
experiments = []
for key in data:
batch_experiments = queueManager.getBatchExperiments(k... | 1762c7449800ce38f0ffc867aa0962827b561a5b | 35,313 |
def noiseProb(ksStat, Ntot):
"""pvalue = noiseProb(ksStat, Ntot)
Returns probability of being in same distribution for given K-S statistic"""
s = Ntot*pow(ksStat, 2)
# For d values that are in the far tail of the distribution (i.e.
# p-values > .999), the following lines will speed up the computatio... | 2e4a99c631ef8ba7225aa8e328dfa03de68c18ed | 35,314 |
def _check_nmant(np_type, nmant):
""" True if fp type `np_type` seems to have `nmant` significand digits
Note 'digits' does not include implicit digits. And in fact if there are
no implicit digits, the `nmant` number is one less than the actual digits.
Assumes base 2 representation.
Parameters
... | 9e1905d6efb1f2c5dcdc668128a614a48ef6c7f3 | 35,315 |
import json
import uuid
import time
def timeboard_send_steps_list(self, steps, scenario_name, timeout):
"""
Change all steps in timeboard
:param steps: The list of steps extracted from the scenario json file
:type steps: list
:param scenario_name: name of the scenario to which the steps belong
... | 8d3cbbd2f61b1f6c4169737f72972c52ebc14fe1 | 35,316 |
from typing import Union
from typing import Dict
def get_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]:
""" Retrieve a dict of characters and escape codes with their real index
into the string as the key.
"""
codeindices = get_code_indices(s)
if not codeindices:
# This functi... | 813c1b23a55400a645f6f79208b86d8c9e9d3905 | 35,317 |
import re
def parse_shortcodes(post_body):
"""
I stole this shortcode regex from Wordpress's source. It is very confusing.
"""
tagregexp = '|'.join([re.escape(t) for t in TAGS_WE_CAN_PARSE.keys()])
pattern = re.compile(
'\\[(\\[?)(' + tagregexp +
')\\b([^\\]\\/]*(?:\\/(?!\\])[^\\]... | 2a8a76e7b34a4e176a0236740886d4e7dc89bb20 | 35,318 |
from typing import Callable
def on_start(func: Callable) -> FunctionCallback:
"""Decorator for creating a callback from a function. The function will be
executed when the `Events.START` is triggered. The function should take
:class:`argus.engine.State` as the first argument.
Example:
.. code... | d3e6fbad2932b88d9545c0368b75488b21f5f798 | 35,319 |
def conditional_entropy(cond_counts):
"""
Compute the conditional entropy of a conditional multinomial distribution
given a list of lists of counts or Counters for x given each y:
H(x|y) = \sum_y p(y) \sum_x p(x|y) \log (1 / p(x|y))
"""
if isinstance(cond_counts, dict):
cond_counts =... | 9695e282f59a6eefe6f83217c554f734d8bdbafb | 35,320 |
def xover_selection(snakes, survivors, opts, num_survivors):
""" Picks parents from the current generation of snakes for crossover
params:
snakes: list, current generation of snakes of class Snake
survivors: list, snakes of class Snake that survived
opts: dict, contains hyperparamters
... | 990e65aac637abe8c4c6c8a661f4a039b0900ca4 | 35,321 |
def rgb2hsv(image):
"""
Convert RGB image to HSV.
Parameters
----------
image : af.Array
- A 3 D arrayfire array representing an 3 channel image, or
- A multi dimensional array representing batch of images.
Returns
--------
output : af.Array
- A RGB image... | 72b76e200e1ff1fba05fe7f3211b19b34b1ef982 | 35,322 |
def make_colormap(seq,cmapname='CustomMap'):
"""Return a LinearSegmentedColormap
seq: a sequence of floats and RGB-tuples. The floats should be increasing
and in the interval (0,1).
"""
seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
cdict = {'red': [], 'green': [], 'blue': []}
for... | 44dd4b40c4519244a857aa1e6d62b5be974f42d0 | 35,323 |
def _interp_fit(y0, y1, y_mid, f0, f1, dt):
"""Fit coefficients for 4th order polynomial interpolation.
Args:
y0 (Tensor) : Function value at the start of the interval.
y1 (Tensor) : Function value at the end of the interval.
y_mid (Tensor) : Function value at th... | 021b045ca7635471cde1c3e3f6a887d093666bb4 | 35,324 |
def interleave_value(t0,series,begin=False,end=False):
"""Add t0 between every element of *series*"""
T = []
if begin: T += [t0]
if len(series) > 0: T += [series[0]]
for t in series[1:]: T += [t0,t]
if end: T += [t0]
return T | 33e3d8562a482e897bb3fd8d49f33a1dfed9bfb9 | 35,325 |
def menu():
"""Menu grafico testuale per programma di gestione Immobili """
x = 1
while x !=0 :
print (" Menu'")
print(" Gestione Immobiliare")
print(" INSERIMENTO IMMOBILE .........digita 1 --> ")
print(" MODIFICA IMMOBILE .........digita 2 --> ")
print(" CAN... | bfb16f3a50339b6e9ed672e1002e727b10f7cc39 | 35,326 |
def named(new_name):
"""
Sets given string as command name instead of the function name.
The string is used verbatim without further processing.
Usage::
@named('load')
def do_load_some_stuff_and_keep_the_original_function_name(args):
...
The resulting command will be a... | c47d71c4d622fdfcba5854d4f01f2148a07c36ff | 35,327 |
def remove_junk_chars(bucket_name):
"""Remove characters that shouldn't or won't be in a bucket name"""
name = bucket_name
names = []
#Remove junk chars
junk_chars = ["'", '"', "'", "!"]
for junk_char in junk_chars:
name = name.replace(junk_char, "")
#Remove domains (this can b... | cd2a3076215a3a8bb94903e1015391abc00ecfaa | 35,328 |
def create_2x2_arrays(num_arrays):
"""This creates a multi-dimensional array of n 2x2 arrays
Arguments:
num_var {[int]} -- [this is the number of desired arrays]
Returns:
[numpy array] -- [a zero filled n dimensional array with n 2x2 arrays]
"""
temp_list = [2]
for temp in rang... | 26994d64e0dde46083481fd9f1594c9c102065f3 | 35,329 |
def calculate_gr(fr_pattern, density, composition):
"""
Calculates a g(r) pattern from a given F(r) pattern, the material density and composition.
:param fr_pattern: F(r) pattern
:param density: density in g/cm^3
:param composition: composition as a dictionary with the elements as k... | ac2ad0de0a01e9c629a2affa0a943bb6948e014c | 35,330 |
import random
def get_batch(data_bucket, bucket_id, batch_size=1):
""" Return one batch to feed into the model """
# only pad to the max length of the bucket
encoder_size, decoder_size = config.BUCKETS[bucket_id]
encoder_inputs, decoder_inputs = [], []
for _ in range(batch_size):
encoder_... | 81c17c41021509a82d9fe08f8614997bee937a3b | 35,333 |
import html
import json
def get_report_formatter(format_name):
"""
Get the correct report table output function for a named format
Args:
format_name (str): Name of the desired format
Returns:
A formatting output function if the format is recognized, or None if it
is not.
... | cbb8f623715d3c272e745d3e454053e419e42960 | 35,334 |
from typing import Set
def print_rule_tree(rt: Set['FlowRule']):
"""
Recursively explore rt-contained rules' parents.
"""
rt = rt.copy()
res = []
seen = set()
while rt:
rule = rt.pop()
if rule in seen:
continue
seen.add(rule)
res.insert(0, rule... | 05b67cda248753042f9f6fbd05dd0b84797a73a3 | 35,335 |
def sort(request):
"""
Valid values for the 'sort' parameter used in the Index
setops methods (intersection, union, etc.)
Caution:
Don't confuse this one with the "sort" fixture used
for DataFrame.append or concat. That one has
parameters [True, False].
We can't combine... | 0f1e7bb570b6f8f617a7564695c1a20d71cfbe80 | 35,336 |
from datetime import datetime
import pytz
def date_string_to_utc_float_string(date_string, timezone=None):
"""Return a utc_float_string for a given date_string
- date_string: string form between 'YYYY' and 'YYYY-MM-DD HH:MM:SS.f'
"""
dt = None
s = None
for fmt in [
'%Y-%m-%d %H:%M:%S'... | cd1b1db88d6b9add6dcd252c58877030a31038a8 | 35,337 |
import pathlib
def _find_nested(d1, d2):
"""
Find paths in d1 that are nested inside paths in d2.
Returns tuples with keys `(d1_key, d2_key)` where `d1_path` was a subdirectory of `d2_path`.
"""
# Copy to ensure we don't alter
# original dicts in parent scope
d1 = d1.copy()
d2 = d2.co... | 21b8a9deab9b4ce57987916e98d8ec8c321fd533 | 35,338 |
def safe(method):
"""
Decorator to return safe in case of error.
"""
def ret(*args, **kw):
try:
return method(*args, **kw)
except Exception as e:
log.exception(e)
# return result
return ret | 9d3d99fec1f2e7e53a35858ad3d5d94d10e443c8 | 35,339 |
def flashpoint_alert_list_command(client: Client, args: dict) -> CommandResults:
"""
List alerts from Flashpoint.
:param client: Client object
:param args: The command arguments
:return: Standard command result or no records found message.
"""
args = validate_alert_list_args(args)
respo... | 703f14150c3ac1bce3d70bbe32e2e49f617295e2 | 35,340 |
def create_user(db, django_user_model: AbstractUser, test_password: str):
""" factory for creating users """
def make_user(username, email, first_name, last_name) -> AbstractUser:
new_user: AbstractUser = User.objects.create(username=username, email=email,
... | 81390a58e4a30b83515c6fa22cb0d42e16a816e6 | 35,341 |
def _read_network_data_from_h5(fname):
"""Read the network stored by the write_network_to_h5 function"""
bias_accumulator = []
weight_accumulator = []
with h5py.File(fname, "r") as hdf:
n_dense_layers = hdf["n_dense_layers"][...][0]
activation = list(hdf["activation"].keys())[0] # Extra... | e78a0966d9ed30cb1c9d35447f91c5c22009fd40 | 35,342 |
import json
def credentials_from_file(file):
"""Load credentials corresponding to an evaluation from file"""
with open(file) as file:
return json.load(file) | 8f73c595b4e61757ae454b1674a7177ab4d05059 | 35,343 |
import requests
def get_workspace_vars(auth, workspace_id):
"""
Function to get variables created in a workspace
"""
headers = {"Content-Type": "application/json"}
url = f"https://intersight.com/tfc/api/v2/workspaces/{workspace_id}/vars"
response = requests.get(url, headers=headers, auth=auth)... | ed05bc7fee86d0303e25fe6ea0b0fd898a08e347 | 35,344 |
def locate_btn(game, team_name, mkt_type, verbose=False):
"""
given selenium game, team_name, and mkt_type
returns find the specific bet button for the givens
game: selenium obj
team_name: str
mkt_type: 0 is point spread, 1 is moneyline, and 2 is over/under
"""
bet_buttons = get_bet_but... | 641412d41a1a90153bac456ed56702a3a5abc09c | 35,345 |
def mailchimp_get_endpoint(**kwargs):
"""Endpoint that the mailchimp webhook hits to check that the OSF is responding"""
return {}, http_status.HTTP_200_OK | 6e46145b976dae5c77d5b8049da91464669aab40 | 35,346 |
def format_date(value, format='%Y-%m-%d'):
"""Returns a formatted time string
:param value: The datetime object that should be formatted
:param format: How the result should look like. A full list of available
directives is here: http://goo.gl/gNxMHE
"""
return value.strftime(fo... | 3f094918610617e644db69415d987fa770a06014 | 35,347 |
def Transpose(node):
"""(Simple) transpose
>>> print(matlab2cpp.qscript("a = [1,2,3]; b = a.'"))
sword _a [] = {1, 2, 3} ;
a = irowvec(_a, 3, false) ;
b = arma::strans(a) ;
"""
# unknown datatype
if not node.num:
return "arma::strans(%(0)s)"
"""
# colvec -> rowvec
... | 16f4eb901ee59c424474b5f55264109dc47e6958 | 35,348 |
import numbers
import collections
def get_xml_type(val):
"""Returns the data type for the xml type attribute"""
if type(val).__name__ in ('str', 'unicode'):
return 'str'
if type(val).__name__ in ('int', 'long'):
return 'int'
if type(val).__name__ == 'float':
return 'float'
... | 95a93523d0c982ed2bbd81bba528198915a7eff3 | 35,349 |
def DatetimeToWmiTime(dt):
"""Take a datetime tuple and return it as yyyymmddHHMMSS.mmmmmm+UUU string.
Args:
dt: A datetime object.
Returns:
A string in CMI_DATETIME format.
http://www.dmtf.org/sites/default/files/standards/documents/DSP0004_2.5.0.pdf
"""
td = dt.utcoffset()
if td:
offset =... | 706faec64a116ad4dc255b6ff9b87b4a8488bcff | 35,350 |
def _add_suffix(params, model):
"""Add derivative suffixes to a list of parameters."""
params_full = params.copy()
suffix = {
"basic": {},
"derivatives": {"derivative1"},
"power2": {"power2"},
"full": {"derivative1", "power2", "derivative1_power2"},
}
for par in param... | 178b71bb24dde36c262d115e485b568fe0bef503 | 35,351 |
def _random_covariance_matrix(batch_size):
"""Generate a batch of random covariance matrices.
Args:
batch_size: Number of elements in the first dimension returned.
Returns:
A tensor with dimensions [batch_size, 2, 2].
"""
# Make a random covariance matrix by taking the outer product of 10 random
#... | 19ab668bc43e4213ed5b4a042730f9953424b37f | 35,353 |
def parse_ranges_highlight(ranges_string):
"""Process ranges highlight string.
Args:
ranges_string: (str) A string representing a numerical range of a list of
numerical ranges. See the help info of the -r flag of the print_tensor
command for more details.
Returns:
An instance of tensor_forma... | 263c6b11d123277e6a2636c482ba045751a8863d | 35,354 |
def have_instance(nova_connection: NovaConnection, instance_name: str):
"""
Check if the instance_name is in the same region that nova_connection
:param nova_connection: NovaConnection
:param instance_name: str content the instance name
:return: bool
"""
for server in nova_connection.conne... | 4174a3817301007f3cb5eaab02bfc8c14b7526fd | 35,355 |
import torch
def torchify_dict(data: dict):
"""
Transform np.ndarrays to torch.tensors.
Parameters
----------
data : dict
property data of np.ndarrays.
References
----------
.. [1] https://github.com/ken2403/schnetpack/blob/6617dbf4edd1fc4d4aae0c984bc7a747a4fe9c0c/src/schnetp... | fbfc2a05e6e6710bae1aee8487c277f463b58225 | 35,356 |
def select_black_ou(board):
"""
手番側の有効な王の利きを求めるために使う
:param board:
:return:
"""
# 桂馬で王手されているかを調べるために、擬似的に王から桂馬の効きを計算する
# 王の通常の動きの計算もある
# 2回使うので、collectionに登録する
name = 'black_short_ou'
collection = tf.get_collection_ref(name)
if len(collection) == 0:
selected = tf.to_... | 7b30d104b6fb916b7b70025f7812dc2fd26a4bad | 35,358 |
def bytes_to_decimal_bytes(bytes_decimal_str, is_little_endian=False):
"""
:param bytes_decimal_str:
:param is_little_endian:
:return:
"""
if not bytes_decimal_str.isdigit():
raise Exception('bytes_decimal_str 不是数字字符串!')
return
length = len(bytes_decimal_str)
tmp_list = ... | 2a5dbbfe643919c20e764268ca4046151d80eaf2 | 35,359 |
from .. import sim
from ..support.morlet import MorletSpec, index2ms
from scipy import signal as spsig
def prepareSpectrogram(
sim=None,
timeRange=None,
electrodes=['avg', 'all'],
pop=None,
LFPData=None,
NFFT=256,
noverlap=128,
nperseg=256,
minFreq=1,
maxFreq=100,
st... | 209f0f58878a36184d93824d84e07fa4e00a146b | 35,361 |
def mock_func_call(*args, **kwargs):
"""
Mock function to be used instead of benchmark
"""
options = Options()
cost_func = make_cost_function()
results = []
result_args = {'options': options,
'cost_func': cost_func,
'jac': 'jac',
'hes... | 9dd8c1e928f649f8acea70e423f08df29fb9c59c | 35,362 |
def _full_gauss_den(x, mu, va, log):
""" This function is the actual implementation
of gaussian pdf in full matrix case.
It assumes all args are conformant, so it should
not be used directly Call gauss_den instead
Does not check if va is definite positive (on inversible
for that mat... | 6828755f0dc526009babe48ec31b14977e1187eb | 35,363 |
def load_texture_pair(filename):
""" Handles textures """
return[
arcade.load_texture(filename),
arcade.load_texture(filename, mirrored=True)
] | 20cd31cc09dfc6a503e678135b1de406263c8719 | 35,364 |
def set_field_value(context, field_value):
"""populates variable into a context"""
if field_value:
context['field_value'] = field_value
else:
context['field_value'] = ''
return '' | 68110380f244b78550a04d08ad9bda5df193211e | 35,365 |
def get_bbox(src_bbox, offset):
"""src_bboxにoffsetを適用し、元の領域を復元する。
RPNから得たoffset予測値をアンカーボックスに適用して提案領域を得る。といったケースで利用する。
Args:
src_bbox (tensor / ndarray): オフセットを適用するBoudingBox。
Its shape is :math:`(R, 4)`.
2軸目に以下の順でBBoxの座標を保持する。
:math:`p_{ymin}, p_{xmin}, p_{ymax},... | 3afc2cacbd86a6b507c14b7623a1759148ca71fc | 35,366 |
def show_books(object_list):
"""
加载指定书籍列表的模板。
:param object_list: Book模型实例的列表
:return: 返回一个字典作为模板的上下文
"""
if len(object_list) > 0:
try:
getattr(object_list[0], 'object')
except AttributeError:
pass
else:
object_list = map(lambda ele: e... | 034707460c73eed6e69578726c860ee55a070ac6 | 35,367 |
def load_mesh_from_file(filepath, color=None, alpha=None):
"""
Load a a mesh or volume from files like .obj, .stl, ...
:param filepath: path to file
:param **kwargs:
"""
actor = load(str(filepath))
actor.c(color).alpha(alpha)
return actor | 49d4a1aa576d2df3d18647f0b48cd84662f9f713 | 35,368 |
import six
def find_html_form(forms, form_match):
# type: (Dict[AnyKey, Form], FormSearch) -> Optional[Form]
"""
Searches for the specified form amongst a group of multiple forms.
:param forms: Possible forms to distinguish and look for a specific one.
:param form_match:
Search criteria t... | 7168a9b2734a7f67bb0e490700689c5e92f18b6e | 35,369 |
import re
from typing import OrderedDict
def parse_dict(s, sep=None):
"""
parser for (ordered) dicts
:s: the input string to parse, which should be of the format
key1 := value1,
key2 := value2,
key3 := value3,
... | dcfdec6dcc68661f5d27f49a280326bec6cfd90b | 35,370 |
def compute_pdi(value_matrix, slice_list):
"""
Computes a 'preference' discordance index
:param value_matrix:
:param slice_list:
:return:
"""
pdi = ['x']
pdimax = ['x']
for i in slice_list:
incident = compute_incident(value_matrix, i)
complement = invert_matrix(incide... | e4dafa4259a0d8ecdd496a18cca6dc7cd44c69ad | 35,371 |
def sublist_search(array1, array2):
"""
:param array1: sublist
:param array2: list
:return: Whether list contains sublist
Time complexity: O(n * m)
"""
# Empty array
if len(array1) == 0:
return True
for start_idx in range(len(array2)):
if check_is_contained(array1, a... | 905d89b1a831e5f3d0ae2ee3c7fdbe6956bbd507 | 35,372 |
def get_instance_names(node: AST) -> list[str]:
"""Extract names from an assignment node, only for instance attributes.
Parameters:
node: The node to extract names from.
Returns:
A list of names.
"""
return [name.split(".", 1)[1] for name in get_names(node) if name.startswith("self... | c96d4e0b5a79845f695e8ee6c48a1db544670692 | 35,374 |
def is_geq_than(x,y):
""" x is not None and greater than or equal to y """
if x != None:
if x>=y: return True
return False | 706e801cb23673ed094e330ee8582aaf14fe85c3 | 35,375 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.