content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def wrap_deepmind(env, reward_clip=True, frame_stack=4, scale=False):
"""Configure environment for DeepMind-style Atari.
"""
env = WarpFrame(env)
if scale:
env = ScaledFloatFrame(env)
if reward_clip:
env = ClipRewardEnv(env)
if frame_stack:
env = FrameStack(env, frame_sta... | 00ec97ea2b4ddcca27ae8a38f03e29f841785027 | 64,300 |
import torch
def receive_generate_info():
"""
Needs to be synced up with send_generate_info
"""
input_info_tensor = torch.empty(10, dtype=torch.float32, device=torch.cuda.current_device())
torch.distributed.broadcast(input_info_tensor, 0)
batch_size = int(input_info_tensor[0].item())
seq_l... | 36d64aba0509bf3a898239687b1dc96f88d40b0e | 64,301 |
def create_repo(path):
"""
Give the full path to then new repo with .git ending included.
"""
repo = Repo.init(path, bare=True)
return repo | 175cf64ad85ccade67cb50b066104326045bd5d1 | 64,302 |
def kis(verts_in, faces_in, height=0.0):
"""
each n-face is divided into n triangles which extend to the face centroid
existing vertices retained
equivalent to Blender poke operator
"""
flags_kis = {}
verts_kis = verts_in[:]
vert_tags = {'v{}'.format(i): i for i, v in enumerate(verts_kis... | ce66d178d317bd470367edd7c67a9e6811c84a04 | 64,303 |
import warnings
def combine_batches(
data, batch_labels, append_to_cell_names=None, common_columns_only=True
):
"""Combine data matrices from multiple batches and store a batch label.
Parameters
----------
data : list of array-like, shape=[n_batch]
All matrices must be of the same format ... | e202257a323e534584d87dadee41557835efce51 | 64,304 |
import torch
def create_data_loader(inputs, tags, masks, batch_size: int, mode: str = 'train') -> DataLoader:
"""
Create data loader from inputs, tags and masks
:param inputs:
:param tags:
:param masks:
:param batch_size:
:param mode: train and val
:return:
"""
inputs = torch.t... | afd82b4198a5c8e376c88fcf4b64cccfa7b663ce | 64,305 |
def file_name_to_multiline_readable(
file: str, two_rows_only: bool = False, net_only: bool = False
) -> str:
"""Returns a stylised file_name to be human readable across multiple lines, e.g. for titling a plot.
Args:
file: Processed results filename with or without path.
"""
# remove path i... | 8d00ddf7764a6458a28bbd9f5bb1317b392f64cd | 64,306 |
from pathlib import Path
from datetime import datetime
def mediainfo(fp_in):
"""Returns abbreviated video/audio metadata for video files
:param fp_in: filepath"""
# extension and media type
ext = file_utils.get_ext(fp_in)
if ext in app_cfg.VALID_PIPE_IMAGE_EXTS:
media_type = 'image'
elif ext in app... | f8991fd9275806bf0e0617bf5ee72cc8bb9eae03 | 64,307 |
from typing import Any
def build_post_double_headers_final_azure_header_get_request(**kwargs: Any) -> HttpRequest:
"""Long running post request, service returns a 202 to the initial request with both Location and
Azure-Async header. Poll Azure-Async and it's success. Should NOT poll Location to get the
fi... | 1aea0fb2d79edd926fb079d3a9002b9a7759839e | 64,308 |
def a_star(grid_map: GridTransitionMap, start: IntVector2D, end: IntVector2D,
a_star_distance_function: IntVector2DDistance = Vec2d.get_manhattan_distance, avoid_rails=False,
respect_transition_validity=True, forbidden_cells: IntVector2DArray = None) -> IntVector2DArray:
"""
:param avoid_... | c56e02fbd0cd094cc1e94e9a44ca048a252459fe | 64,309 |
def sun_rot_elements_at_epoch(T, d):
"""Calculate rotational elements for Sun.
Parameters
----------
T: float
Interval from the standard epoch, in Julian centuries i.e. 36525 days.
d: float
Interval in days from the standard epoch.
Returns
-------
ra, dec, W: tuple (flo... | 9a74edc686869eebd851200687fe4d10d38d550a | 64,310 |
from scipy import integrate
def Network_solve_RosslerSystem(args):
"""Returns a 2D-array of the trajectories of the coupled systems in the form
[X1...n, Y1...n, Z1...n]
Y0, 1D array of DOUBLE or INT: inital state of the form
Y0 = [x1,x2, ...,xn, y1,y2, ...,yn, z1,z2,...,zn]
d... | e6bc19e66d0e70bcc1a0bdbc767e43e11616c52a | 64,311 |
def as_delayed_signal(arg, **kwargs):
"""Make sure that the given argument can be used as a signal.
Parameters
----------
arg : sequence of 1 array_like followed by 1 or 2 scalars
The first element is converted to a NumPy array, the second
element is used as the sampling rate (in Hertz)... | 9bfc25644cd859c39bcd46f39e7e39b5474401e5 | 64,312 |
def mejor_aerolinea(vuelos: dict) -> str:
""" La mejor aerolínea
Parámetros:
vuelos (dict): Es un diccionario de diccionarios con la información de los vuelos.
Retorno:
str: El nombre de la mejor aerolínea (la que tenga menor retraso promedio)
"""
aero_con_promedioretraso = {}
# vuel... | 68816ae69bc3b7189e06f690c635739b6933eb17 | 64,313 |
from typing import Dict
from typing import Any
from typing import Optional
import logging
from pathlib import Path
def upload_py_modules_if_needed(
runtime_env: Dict[str, Any],
scratch_dir: str,
logger: Optional[logging.Logger] = default_logger,
upload_fn=None,
) -> Dict[str, Any]:
"""Uploads the ... | 68db8c2f6eaf2ee63a4af372c275e232d92a3553 | 64,314 |
def subexpd(global_step, start_step, end_step, start_val, end_val,
warmup=True, stair=True):
"""Sub-exponential decay function. Duration decay is sqrt(decay)."""
if warmup and start_step == 0:
return lerp(global_step, start_step, end_step, start_val, end_val)
decay_steps = tf.cast(end_step - start... | ea9fa39d46b32d29eddf2e8e0451054fd8c3a045 | 64,315 |
def _get_all_polylines_pm(edges):
""" [pm] edges で指定したエッジ列を連続するエッジ列の集まりに分割してリストを返す
get_all_polylines() から呼ばれる Pymel 版の実装。基本的には直接呼ばず get_all_polylines() を使う。
Args:
edges (list[MeshEdge]):
Returns:
list[list[MeshEdge]]:
"""
polylines = []
rest_edges = edges
intersectio... | ddb587e42a79837499986d84c4db127acbb62e8a | 64,316 |
def register():
"""
function to render registration form
:return:
"""
form = RegistrationForm()
if form.validate_on_submit():
user = User(username=form.username.data, email=form.email.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.com... | 857082c6b7d7c885f2dc33abf859bf9458c44010 | 64,317 |
import os
import pytz
from datetime import datetime
def jr6_txt(mag_file, dir_path=".", input_dir_path="",
meas_file="measurements.txt", spec_file="specimens.txt",
samp_file="samples.txt", site_file="sites.txt", loc_file="locations.txt",
user="", specnum=1, samp_con='1', location='... | 586818c2bc9a457b47b5d3e0db7ac58f0b7e8660 | 64,318 |
def android_devices(prefix, parsed_args, **kwargs):
"""
Returns all connected Android devices.
:param prefix: The prefix text of the last word before the cursor on the command line.
:param parsed_args: The result of argument parsing so far.
:param kwargs: keyword arguments.
:returns list: list ... | 075a8addf0740ff5a4a8147244393323440cc6d8 | 64,319 |
def subsong_replaceext(filepath, subsongformat_type):
"""replace extension of subsong filepath with another extension
will properly replace subsong extensions like .sub.imc
filepath: a file path
subsongformat_type: a key from extutils.SUBSONG_FORMATS. Pass the one corresponding
to the extension ... | a655be08ffd81a03ebcceb1d33243cd24ddb5f39 | 64,320 |
def write_positions(positions):
"""parse float tuples of a text string
return string
"""
result = ""
if positions is not None:
for x,y in positions:
result = "%s %s,%s" % (result, x, y)
return result | 0587272400c2e835bcf2ebd3e55f65e2daa7ee1f | 64,321 |
def NameAndAttribute(line):
"""
Split name and attribute.
:param line: DOT file name
:return: name string and attribute string
"""
split_index = line.index("[")
name = line[:split_index]
attr = line[split_index:]
return name, attr | 7595f51d728c5527f76f3b67a99eccd82fb9e8b7 | 64,322 |
def siteCallWrap(seq, orient, seqLen):
"""
Wraps kmerMatch, findConsArrays, and findCenter together
Input: sequence, orientation, sequence length
Output: list of called sites
"""
return(findCenter(findConsArrays(kmerMatch(seq)), orient, seqLen)) | b7ee0855f92173bc816de16aa37814f8cbeae15d | 64,323 |
import string
def english_like(s: str) -> float:
"""higher is better"""
if any(c not in string.printable for c in s):
return -1
return sum(letter_frequencies.get(c, 0) for c in s) | 52c1de13805bc6fa50193b08bc169e11e621c23f | 64,324 |
def _datastore_wait_ready(popen):
"""Wait until the datastore emulator is ready to use.
:type popen: :class:`subprocess.Popen`
:param popen: An open subprocess to interact with.
"""
envs = {}
emulator_ready = False
while not emulator_ready:
line = popen.stderr.readline()
if l... | 05f12bfbf77a95c0a2732cf606ba44fa3bf4b769 | 64,325 |
from typing import Sequence
def order_certificate(
minion_id,
common_name,
organization_id,
validity_years,
cert_key_passphrase=None,
signature_hash=None,
key_len=2048,
dns_names=None,
organization_units=None,
server_platform=None,
custom_expiration_date=None,
comments=... | babc3f1f9090d34e7c334d44d3dd97d50c3e6eeb | 64,326 |
def test(data, goal, net):
""" Test the model. """
correct = 0
print("Testing...")
for i in range(len(data)):
classification = np.argmax(net.test(data[i][:]))
answer = np.argmax(goal[i])
if(answer == classification):
correct += 1
print("Score: " + str(correct *... | 977ccdf1a61d6d667244e8a8cd59fbf8eafe4551 | 64,327 |
import sys
def get_bpyobj_by_name(name_key: str):
"""
Using the name key to retrieve the object
:param name_key: The key assigned using import_obj_model
:return: bpy.data.objects[name_key]
"""
obj_collect = bpy.context.scene.objects
if name_key in obj_collect:
return obj_collect[na... | b4a13c8cde3f388f290a70638088e5d0c61fcf27 | 64,328 |
from datetime import datetime
def sitemap():
"""
Renders a sitemap.
"""
context = make_context()
context['pages'] = []
now = datetime.date.today().isoformat()
context['pages'].append(('/', now))
context['pages'].append(('/methodology/', now))
context['pages'].append(('/legislator... | 98c788f7404e5b5b9c837c7061e8ea2261456491 | 64,329 |
import os
def read_requirements():
"""Parse requirements from requirements.txt."""
reqs_path = os.path.join('.', 'requirements.txt')
with open(reqs_path, 'r') as f:
requirements = [line.rstrip() for line in f]
return requirements | c391a98c1428febe4fe523c3ddc8c8fec3f18370 | 64,330 |
def pre_process_features(observation):
"""Takes the raw observation vector of the environment and amends it to our needs.
:param observation: The observation of the environment
:return: A vector which contains the features which we want.
"""
IDX_SUC_NODES = 12
features = np.array(observation[:I... | 94dd97adbb3c2bb54d64e5a669aae6062eae2adc | 64,331 |
def calculate_accuracy(accepted_scores, accepted_labels):
"""This function calculates the gain of the second classifier, based on the true
training instances accepted by the first classifier.
Args:
accepted_scores ([int]): Positive scores obtained from
the second classifier ... | 5845eb2d55500e007c633c280ef8963850805a82 | 64,332 |
def uuid():
"""UUID for Test."""
return uuid4() | 46085befe6d7365492ab3981a09e0ee29bccc264 | 64,333 |
def compute_mse(actual, forecast):
"""
Computes the Mean Squared Error between the tensors 'actual' and
'forecast', representing the ground truth outcomes and model outcomes,
respectively.
Args:
actual (ndarray): Ground truth outcome
forecast (ndarray): Model outcome
Returns:
... | ff74d57e578869de27ceed9a478e49113a23a9f1 | 64,334 |
import crypt
def _get_pem_key(credentials):
"""Gets private key for a PEM payload from a credentials object.
:type credentials: :class:`service_account.ServiceAccountCredentials`,
:param credentials: The credentials used to create a private key
for signing text.
:rtype: :clas... | b186381f17742b5f30a91fd766b0fc682db2dd3f | 64,335 |
def bsplclib_Resolution(*args):
"""
* given a tolerance in 3D space returns a tolerance in U parameter space such that all u1 and u0 in the domain of the curve f(u) | u1 - u0 | < UTolerance and we have |f (u1) - f (u0)| < Tolerance3D
:param PolesArray:
:type PolesArray: float &
:param ArrayDimension:... | 65475a9a99ad27c75886f3c2348bac896c958d09 | 64,336 |
def transverse_width(Lambda, theta_s):
"""
Transverse Coherence Width (Zernike-Van Cittert Theorem).
Params:
Lambda: electron wavelength in Å.
theta_s: convergence semi-angle of source (or image of source) in radians.
Returns:
transverse coherence width in Å.
"""
return Lambda / (2 ... | c822d9f3e0d493c40bac6e968b111b48915ede4a | 64,337 |
import os
def get_game_bypath(root, path):
""" Search and get game-element from an ElementTree XML root.
First matching game element will be read. Comparison is done at
basename level of path, which means ignoring its directory part
and comparing filenames only.
Parameters
----------
ro... | 1b1317476836c6a2049130393a9578c65873d374 | 64,338 |
def create_relationship_query(entity_map: dict, rel_name: str, rel_map: dict) -> str:
"""
Purpose:
Create relationship definition query
Args:
entity_map: Entities map
rel_name: The name of the relationship
rel_map: Relationship Map
Returns:
graql_insert_query: The... | 683a0a316c132db7ec5ee0f01c302c06c2a45d77 | 64,339 |
def leave_one_out(learner, dataset, size=None):
"""Leave one out cross-validation over the dataset."""
return cross_validation(learner, size, dataset, k=len(dataset.examples)) | b215e552af9f9f8c7dd0bc64cc8b65adb6c16ad7 | 64,340 |
def unsigned(value, size):
"""
Make a value unsigned based on it's size.
"""
return value & u_maxes[size] | e2dd53c804acd6a7fe8150b275d1921b978167aa | 64,341 |
def convert_data(inp, outp, data):
"""
Return data converted to the output format ... over-simplistic implementation for the moment ...
@param inp,outp: input/output format like "cbfimage"
@param data(ndarray): the actual dataset to be transformed
"""
return CONVERSION_DATA.get((inp, outp), lamb... | d4db6b4ec460b6239ea25471edbd6e9497d3f79e | 64,342 |
import os
def manifestPath(service, manifest=ACTIVE_MANIFEST):
""" compute the path to a __service manifest """
return os.path.join(manifestRootPath(service), manifest) | 1e0da2791d5de266dbf1ac2b54ec9ed91829ea52 | 64,343 |
import queue
def kruskal(graph: UndirectedGraph) -> UndirectedGraph:
"""Kruskal algorithm.
:param graph: an undirected graph with weighted edges
:return: the minimal spanning tree"""
mst = UndirectedSimpleGraph([v.id for v in graph.vertices])
edge_queue = queue.PriorityQueue()
vertex_sets = D... | 3ddffbe23513bdcfa9d9162841a5c219cd11d4f0 | 64,344 |
import torch
import copy
def clones(module: torch.nn.Module, n: int):
"""
Produce N identical copies of module in a ModuleList
:param module: The module to be copied.
The module itself is not part of the output module list
:param n: Number of copies
"""
return torch.nn.ModuleList([cop... | e4807cda87c90af415555606e3308f07ff9ddf49 | 64,345 |
def convert_kwargs_to_str(kwargs, max_len=None):
""" Convert kwargs to a string, allowing for some arguments to raise
exceptions during conversion and ignoring them.
"""
length = 0
strs = ["" for i in range(len(kwargs))]
for i, (argname, arg) in enumerate(kwargs.items()):
try:
... | 11e0d1defd9d8b90b530c1d011c4f9a315492311 | 64,346 |
def get_autodetected_TEST_SPEC(mbeds_list,
use_default_toolchain=True,
use_supported_toolchains=False,
toolchain_filter=None,
platform_name_filter=None):
""" Function detects all connected to ... | c59e4b744b57595a742bd31eed297e10f39d184e | 64,347 |
def build_copy_labels(config, example, emb_dicts, related_words_ids_mat):
"""
Get example question generation features.
NOTICE: we can add different strategies for divide copy and non-copy part from tgt
"""
tgt, switch, copy_position, switch_oov, copy_position_oov, switch_soft, copy_position_soft, i... | 70e63a2a80b090cd980ca323ab71573224f8692c | 64,348 |
def filter_current_user_queryset(modelRelatedFieldObj):
"""
This handy method will allow you to limit
the choices of modelRelatedFieldObj based on
the current request user.
"""
if 'request' in modelRelatedFieldObj.context:
user = modelRelatedFieldObj.context['request'].user
if 'user'... | 6c3a570cce171fac348ad50ab08d2b5890f52918 | 64,349 |
def append_age_banding(df):
"""
Method that appends a banding of the age field, which is consistent with the method `band_age`.
**Note**: This method assumes that the DataFrame `df` include the (int) field named 'age', which is
:param pandas.DataFrame df: DataFrame of transformed marathon data
:re... | bf6a5dab84c952069da3a1c12ff39c5844cf1e28 | 64,350 |
def is_sorted(array):
""" Check if array of numbers is sorted
:param array: [list] of numbers
:return: [boolean] - True if array is sorted and False otherwise
"""
for i in range(len(array) - 1):
if array[i] > array[i + 1]:
return False
return True | 8542e162aa96f7035d33f1eb7b7159031a8a41b8 | 64,351 |
def downsample_linearring(points,density,factor=None,closed_ring=1):
""" Makes sure that points aren't *too* close together
Allow them to be 0.3*density apart, but any edges shorter than that will
lose one of their endpoints.
"""
if factor is not None:
density = density * factor # should giv... | 8e0f80fa5fc80038466266d1f092d12f9f1167e0 | 64,352 |
def get_test_stat(name):
"""
Get the test statistic function by name. The following test statistics are supported:
- :func:`~pyhf.infer.test_statistics.q0`
- :func:`~pyhf.infer.test_statistics.qmu`
- :func:`~pyhf.infer.test_statistics.qmu_tilde`
Example:
>>> from pyhf.infer import uti... | 763d018d78b52fd7219be7dc82c3c3d3c6360786 | 64,353 |
def avg_last_k_value(energies, k):
"""
Compute the average of the last k absolute differences between the values of a list.
"""
diff = []
L = len(energies)
for i in range(L - 1,L - (k+1),-1):
diff.append(abs(energies[i]-energies[i-1]))
return np.mean(diff) | 6051dcd659e6166593078fdbc9e7b43f931a1ce3 | 64,354 |
def get_slave_list(bus = "wishbone", user_paths = [], debug = False):
"""Gets a list of slaves
Args:
bus: a string declaring the bus type, this can be
\"wishbone\" or \"axie\"
user_cbuider_paths: besides the normal paths to search for, also search
these paths for cbuilder slave projec... | 0bb6996d67c2d41175bf1f40925f9b2dea5e9e56 | 64,355 |
def FormatDescriptorToPython(i):
"""
Format a descriptor into a form which can be used as a python attribute
example::
>>> FormatDescriptorToPython('(Ljava/lang/Long; Ljava/lang/Long; Z Z)V')
'Ljava_lang_LongLjava_lang_LongZZV
:param i: name to transform
:rtype: str
"""
i... | 8d217883603ae9e9c8f282985b456aa97494beba | 64,356 |
def convert_input_data(d):
"""
Checks if the input data are a astropy.table.Table and if not it converts it to a Table.
:param d: The input data
:type d: numpy.ndarray, astropy.table.Table
:return: The input data as an astropy.table.Table
:rtype: astropy.table.Table
"""
if type(d) is no... | 1ae0ed2837f4ea7f620bb9cda77e676ffb1eeccf | 64,357 |
def recode_rangesig(rsig, encode=True, copy=False):
"""
In - place rsig recoding
:param rsig:
:param encode: if true encodes to byte representation, otherwise decodes from byte representation
:param copy:
:return:
"""
recode_int = crypto.encodeint if encode else crypto.decodeint
reco... | 581d6a7ac08f9ac5c3d5fab35f6299404300755b | 64,358 |
def sif_view(file, layout_name='fcose'):
"""
Read graph stored in SIF format using NetworkX and render a visualization of it
Parameters
----------
file : str
Path to file in sif format
layout_name : str
Name of layout to use
Returns
-------
"""
return Viz(data=... | 3867735c1e0e51461f425268eb627c421a546c7c | 64,359 |
import numpy as np
import xarray as xr
from ds21grl.misc import month_to_dayofyear,leap_year_test
def read_yt_zm_ml_daily(var,level,dir_in,dim):
"""
read daily zonal-mean yt data on a given model level
acro... | ddf02cfb5233bdb981a1cc1497e6fd174bd8589a | 64,360 |
def quantize_evecs(evecs, odf_vertices=None):
""" Find the closest orientation of an evenly distributed sphere
Parameters
----------
evecs : ndarray
odf_vertices : None or ndarray
If None, then set vertices from symmetric362 sphere. Otherwise use
passed ndarray as vertices
Ret... | 4138b6bcace476b9f3edc15265953b03c15a657b | 64,361 |
def _get_features(coord, properties, projection, layer, clipped, projected, spacing, id_property, skip_empty_fields=False):
""" Return a list of features in an OGR layer with properties in GeoJSON form.
Optionally clip features to coordinate bounding box, and optionally
limit returned features ... | 70ae6255ceffa18ab2f53c99aece1bedaba33d23 | 64,362 |
def touche_pressee(keysym):
"""
Renvoie `True` si ``keysym`` est actuellement pressée.
:param keysym: symbole associé à la touche à tester.
:return: `True` si ``keysym`` est actuellement pressée, `False` sinon.
"""
return keysym in __canevas.pressed_keys | d7ef068efcf30c3e30625aab1cc6eb5188564597 | 64,363 |
def factoring_visitor(state, primes):
"""Use with multiset_partitions_taocp to enumerate the ways a
number can be expressed as a product of factors. For this usage,
the exponents of the prime factors of a number are arguments to
the partition enumerator, while the corresponding prime factors
are in... | 0692d5c2260ca6c98ab874b4a44dc10f3630c57b | 64,364 |
def shortestPath(G, start, end):
"""
Find a single shortest path from the given start vertex to the given
end vertex. The input has the same conventions as Dijkstra(). The
output is a list of the vertices in order along the shortest path.
"""
D, P = Dijkstra(G, start, end)
Path = []
whi... | c9adae6620e585b88e48077138af989e6fe545d5 | 64,365 |
def impute_values(X_train, X_test, col_names, missing_val, impute_strategy, impute_val=None):
"""
Impute missing values with either a constant value or
statistics using the scikit learn SimpleImputer
Parameters
- X_train: (pandas dataframe) dataframe with 1 - test_percentage of entries
... | c0a0bfdca7013ebbc361c8600fd1656062bcfaf4 | 64,366 |
def delete_get(u_id):
"""Render a delete form for the logged in user.
Login required.
Arguments:
u_id (int): the id of the desired user.
"""
return render_template('delete_user.html') | f58217f1c46ae277dffa28bd6c1b888f3a91cce9 | 64,367 |
def typed_struct(cls: type[_CSU]) -> type[_CSU]:
"""A decorator to allow declaring ctypes.Structure subclasses with type
annotations instead of _fields_.
To use, decorate a Structure subclass with your fields as class-level
attributes, using CField annotations or CStr. Omit the _fields_ attribute
e... | 513c5b84f3466ab1f742e17279cf20e02643afca | 64,368 |
def predict(master, input, center, centers, map_reader = reader):
"""
Predict the closest clusters for the datapoints in input.
"""
job = master.new_job(name = 'kcluster_predict',
input = input,
map_reader = map_reader,
map = pre... | 6d23915882c1b988134b27d77e837ff37014c9bd | 64,369 |
def start():
""" Display the WebGUI """
return render_template('index.html') | ba34063f338136c5d7ddef40aa77c9df8c3c62dc | 64,370 |
def layer_severity(layers, layer):
"""Return severity of layer in layers."""
return layers[layer]['severity'] | e8a7a95268ddd2d4aa6b5f7fa66d5828016517eb | 64,371 |
def central_difference(x, y):
"""
Compute the derivative of y with respect to x via central difference.
Parameters
----------
x : np.ndarray
Array of x values
y : np.ndarray
Array of y values
Returns
-------
Tuple containing x values and corresponding y ... | a97e1d6cfac44eb89b7158974d6df5f1017c23d3 | 64,372 |
import logging
def get_upstream_coords(uSite, uLen, seqlen, feat, children_list, gffdb):
"""
Subroutine takes upstream site, length, reference sequence length,
parent mRNA feature (GffLine object), list of child feature types
and a GFFutils.GFFDB object as the input
If upstream of TSS is requeste... | 30dd59f7a52533804cba9ca4e6307b8d9ed396f0 | 64,373 |
import inspect
def get_recent_readings(start_datetime_utc, table=LocalData, engine=ENGINE):
"""
Get all readings since startdate from the local DB
returns an iterator containing the results or None
"""
session = sessionmaker(bind=engine)()
LOG.debug("Querying db for data since %s", start_datet... | d90bf723826986a20e56310d00fc156f8431716e | 64,374 |
def generate_x_y():
"""
generates FAKE_SAMPLE_SIZE number of rows of fake images
:return: input, vectorized labels, scalar labels
"""
x_dim = (conf.FAKE_SAMPLE_SIZE, conf.IMAGE_SIZE)
y_dim = (10, conf.FAKE_SAMPLE_SIZE)
x = np.random.rand(x_dim[0], x_dim[1])
labels = np.random.choice(a=[0, 1, 2, 3, 4, 5... | 5023ce089877613dd65479e054492ab18d885fcb | 64,375 |
import myplotlib.tools.lic as lic
import matplotlib
import matplotlib.pyplot as plt
def plotVectorField(ax, x, y, fx, fy, background=None,
texture_seed=None,
kernel_len=31, kernel_pow=1,
lic_alphamin=0.5, lic_alphamax=0.75,
lic_contrast=0... | d78ab48d95ec5a9b942808d8607b026835a5b186 | 64,376 |
def bootstrap_se_ci(data, seed, num_samples, statistic, alpha):
"""
Return bootstrap estimate of standard error of statistic and
bootstrap estimate of 100*(1-2*alpha)% confidence interval for statistic
in a dictionary along with specified seed and nun_samples (B) and alpha.
"""
assert isinstance... | 206a82efbd99ab81b132ee83da38c27ea5e0db22 | 64,377 |
import pathlib
import typing
def generate_container_command(
target: BuildTarget, cwd: pathlib.Path
) -> typing.List[str]:
"""Generate a Docker command to prepend the build command.
Args:
target: the target to compile for.
cwd: the path to the codebase.
Returns:
List represen... | 9c92bb9c5013f36dc589d633b94008f1466c4fc3 | 64,378 |
def is_same_res(instance: Instance, result: bool = False, message: str = None) -> bool:
"""
Return True if solving an instance returns
the expected result and False otherwise.
"""
try:
same_res = result == check_satis(instance, get_stats=False)
instance.check_model()
if inst... | ace142a7e0df4453b6193c76418122bbc2d8bf1a | 64,379 |
from typing import List
import argparse
def parse_args_for_monitoring(
args_list: List[str], unit_name: str) -> argparse.Namespace:
"""
CLI useful to monitoring scripts. The beauty is in what said scripts do
with this info.
:param args_list: command line arguments
:param unit_name: so far... | 87fde80171c31c6bcea4ab6a82e9834fe7f61e00 | 64,380 |
from typing import Any
from typing import Type
import numpy
def get_type_uint(obj: Any) -> Type[UInt]:
"""
Return the NPType that corresponds to obj.
:param obj: an uint compatible object.
:return: an UInt type.
"""
return _get_type_of_number(UInt, obj, {
numpy.uint8: 8,
numpy.... | 37ea7d91600786fcd1c65ce97768888961ed0995 | 64,381 |
def order_verts_by_edge_connection(connected_verts, results=[]):
"""
Orders connected verts by edge connection.
"""
next_verts = list(
set(results[-1].connectedVertices()) & set(connected_verts)
)
for vert in next_verts:
if vert not in results:
results.append(vert)
... | 9f6b8cc6dc4816c4136da234e90924d2a8d2eae5 | 64,382 |
def pad(tensor, paddings, mode='CONSTANT', constant_values=0, name=None):
"""Pads a tensor.
This operation pads a `tensor` according to the `paddings` you specify.
`paddings` is a list of integers with shape `[n, 2]`, where n is the rank of
`tensor`. For each dimension D of `input`, `paddings[D, 0]` in... | 6350af57b042a221c3e4dc6be47d40b402d3b834 | 64,383 |
def make_gax_metrics_api(client):
"""Create an instance of the GAX Metrics API.
:type client: :class:`~google.cloud.logging.client.Client`
:param client: The client that holds configuration details.
:rtype: :class:`_MetricsAPI`
:returns: A metrics API instance with the proper credentials.
"""
... | e23cf70547cbc3a583b0fe2f5cf8dcfd480ded3e | 64,384 |
def create_optimizers(α=0.002, β1=0.0, β2=0.99, ε=K.epsilon()):
"""
Create n adam optimizers with given hyper-paramaters
:param α: alpha / learning rate, default=0.002, paper range (0.0015 - 0.003)
:param β1: beta1 for adam optimizer, default = 0.0
:param β2: beta2 for adam optimizer, default = 0.99... | 0d7e28a73557a46b912f3070f0850ad9425e2614 | 64,385 |
def compute_kth_distance(coords, k=15):
"""Find the (Euclidean) distance to the `k` th nearest neighbour.
:param coords: An array of shape (n,N) of N points in n dimensional space;
if n=1 then input is an array of shape (N).
:param k: The nearest neighbour to use, defaults to 15, if N is too small
... | 9c1b96994ca16cb8f777d2ecfc72e6931cc68f2a | 64,386 |
def get_operating_system_info(**options):
"""
gets the current operating system info.
:returns: dict(str name: os name,
str release: os release,
str version: os version)
:rtype: dict
"""
return get_component(AuditPackage.COMPONENT_NAME).get_operating_syste... | edcf90205c2e411a653ac80310b05f0543a16536 | 64,387 |
def _parse_alt_title(html_chunk):
"""
Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title.
"""
title = html_chunk.find(
"input",
{"src": ... | bd5df0edfc174653731256d50e0a8f84a6f84880 | 64,388 |
def rebin(wl, f, r, bin_siz=15):
"""
To rebin my flux spectra
Parameters
----------
wl : array
1D array containing the wavelengths to be rebinned
f : array
1D array containing the fluxes to be rebinned
r : array
1D array containing the errors on the fluxes to be rebi... | 052221bc28ba1381503ce0e617b48b6b20ae6bd1 | 64,389 |
def np2qi(array):
"""
Convert numpy array to Qt Image.
source from: https://kogs-www.informatik.uni-hamburg.de/~meine/software/vigraqt/qimage2ndarray.py
:param array:
:return:
"""
if np.ndim(array) == 2:
return gray2qi(array)
elif np.ndim(array) == 3:
return rgb2qi(arra... | c25a11af485b019548ccc6b3ff429dadde63f831 | 64,390 |
def load_sxs_waveform(file_name, modes=None, extraction="OutermostExtraction.dir"):
"""
Load the spherical harmonic modes of an SXS numerical relativity waveform.
Parameters
----------
file_name: str
Name of file to be loaded.
modes: dict
Dictionary of spherical harmonic modes t... | f763e562b46022a49273a0c648aec1f48d751e86 | 64,391 |
def getChargeURL(request):
"""
팝빌 연동회원 포인트 충전 URL을 반환합니다.
- 보안정책에 따라 반환된 URL은 30초의 유효시간을 갖습니다.
- https://docs.popbill.com/kakao/python/api#GetChargeURL
"""
try:
# 팝빌회원 사업자번호
CorpNum = settings.testCorpNum
# 팝빌회원 아이디
UserID = settings.testUserID
url = kak... | 8bd572814cf285a8de55b614e0d30e7b857ed9c2 | 64,392 |
import copy
def simulating_y_from_clinical(
clinical_sim,
var = 'creatinine',
simulate_y = False,
rep = 30):
"""Simulate the outcome Y from clinical or mu(x,t).
Args:
clinical_sim: pd.DataFrame with simulated pi() and mu(). Colnames: 'eid',
'image_id', 'sim_0_pi','sim_0_mu0','sim_0_mu1',
... | 9b952e1db32b2ffe5f66cd8d103ec08b144b88d7 | 64,393 |
def prompt_worker_amount(cpu_cores: int):
"""Prompt the user for the amount of Celery workers they want to run.
Start 2 less workers than amount of CPU cores by default."""
answer = 0
safe_cores_suggestion = cpu_cores - 2
def invalid_answer():
"""Restart prompt if answer invalid"""
... | 2f2e4d423eb94d0bf709feda09c5c45ca8cc481a | 64,394 |
import os
import sys
import subprocess
def pw_convert(filename, bit=64, compression=True, gzip=True, verbose=True):
"""
Runs msconvert.exe from ProteoWizard to convert Waters .RAW format to .mzXML
which can then be parsed by python.
module requirements: os, subprocess, sys
ProteoWizard must be i... | 09973f0c12f63c485b8947c57591791b51e10752 | 64,395 |
from typing import Union
def mach_strlen(code_chunk: Union[bytes, MachineCodeBuilder]) -> MachineCodeBuilder:
"""
push ecx
xor ecx, ecx
@@:
cmp byte [eax+ecx], 0 ; assume that eax contains a string address
jz success
cmp ecx, 100h
jg skip
inc ecx
... | 15f769f7f60a678204d95590cdbdee0c74d7f77e | 64,396 |
def get_quartiles(df, column_name, df_project, units):
"""Get the ensemble quartiles"""
assert len(df) == len(df_project)
quartiles = ['# ' + column_name + ' quartiles']
for project in ['cmip6', 'cmip5']:
df_subset = df[df_project == project]
upper_quartile = df_subset[column_... | 191cfa94ab780172e44892647a7c1f3bdeda8be0 | 64,397 |
import threading
import functools
def glib_idle_add_wait(function, *args, **kwargs):
"""
Execute *function* in the main GTK loop using :py:func:`GLib.idle_add`
and block until it has completed. This is useful for threads that need
to update GUI data.
:param function function: The function to call.
:param args:... | 55ad7afe92906f211af3b6e2c8525068178ac83c | 64,398 |
import os
def fix_cufflinks_attributes(ref_gtf, merged_gtf, data, out_file=None):
"""
replace the cufflinks gene_id and transcript_id with the
gene_id and transcript_id from ref_gtf, where available
"""
base, ext = os.path.splitext(merged_gtf)
fixed = out_file if out_file else base + ".clean.... | cc851dea74e2d5534145995b77ea94db8bc8af86 | 64,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.