content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def df(n):
"""Gives the double factorial of *n*"""
return 1.0 if n <= 0 else 1.0 * n * df(n - 2) | 71fcc2445db94b5686d4c9b8d85e9bdc1dc2bbb4 | 3,620,800 |
def cli(ctx, job_id):
"""Resume a job if it is paused.
Output:
dict containing output dataset associations
.. note::
This method is only supported by Galaxy 18.09 or later.
"""
return ctx.gi.jobs.resume_job(job_id) | 956ee7cbc0b251718311fae88b2bf53482d88b23 | 3,620,801 |
def queue_exists(queue_id):
"""Returns true if the queue ID belongs to a valid queue."""
return True | 24bb477842cedb5443eb06217374deec49f99398 | 3,620,802 |
def arrays(
fn, arrays_dict, _batch_size=None, _stack=False, _limit_slice=None, **kwargs,
):
"""
Split an array by its first dimension and send each row to fn.
The array_dict is one or more parallel arrays that will
be passed to fn(). **kwargs will end up as (constant) kwargs
to fn().
Examp... | f78f4d05f8423119c96e563c89e3c972e134b4f9 | 3,620,803 |
import re
def track_num_to_int(track_num_str):
""" Convert a track number tag value to an int.
This function exists because the track number may be
something like 01/12, i.e. first of 12 tracks,
so we need to strip off the / and everything after.
If the string can't be parsed as a ... | af6e878bad7c3e26c61ad2ad4a759cb8c1dc4224 | 3,620,804 |
def get_choices_as_case_expression(model, field_name, lookup_field=None):
"""
Gets an SQL expression that returns the display name for a field with choices.
Usage example:
InvestmentProject.objects.annotate(
status_name=get_choices_as_case_expression(InvestmentProject, 'status'),
... | 54f1680231f38323d1fefb7c47184f7bbd15f75a | 3,620,805 |
def elt1(list, context):
"""return second member"""
return list[1] | 40d59eaac5b9eeb86b511ef2a4df4b68893a6248 | 3,620,806 |
from typing import Optional
import os
async def take_screen_shot(
video_file: str, duration: int, path: str = ""
) -> Optional[str]:
""" take a screenshot """
print(
"[[[Extracting a frame from %s ||| Video duration => %s]]]",
video_file,
duration,
)
ttl = duration // 2
... | b955f5f25bbe8fa8c539161add93d9c3abe852da | 3,620,807 |
def gather_PIM_data_leakage(x) :
"""
@param x : a VMAnalysis instance
@rtype : a list strings for the concerned category, for exemple [ 'This application makes phone calls', "This application sends an SMS message 'Premium SMS' to the '12345' phone number" ]
"""
result = []
result.extend( detect_ContactAcces... | f6695054558fabb9b7cdb5a233779114bf3fba0e | 3,620,808 |
def node_ping(node, timeout=True, count=2, all_workers=True, all_up=True):
"""Ping all relevant node workers to check if node is UP"""
up = 0
queues = [node.fast_queue, node.image_queue] # Base workers
if all_workers: # Additional workers depend on node capabilities
if node.is_compute:
... | 61271259c15384a7cff0820324cc3367a3b567b6 | 3,620,809 |
def clustermap(df, ax=None, **kwargs):
"""Plot a clustermap by pivoting the last 3 columns of `df`.
The `df` is typically returned from an ESTIMATE PAIRWISE query in BQL.
"""
if len(df.columns) < 3:
raise ValueError('At least three columns requried: %s' % (df.columns,))
# Pivot the matrix.
... | f1de48bd26a94d13c995a82444e80f38ac304125 | 3,620,810 |
from typing import Union
from typing import List
def _get_detail(exc, exception_key: Union[str, List[str]] = "") -> str:
"""
Returns the human-friendly detail text for a specific insight exception.
"""
if hasattr(exc, "detail"):
# Get exception details if explicitly set. We don't obtain excep... | 6b98744e09825b9ab873f1c6a99bed4f6506b081 | 3,620,811 |
from typing import Iterable
import hashlib
def seed_to_entropy(seed: Iterable[str], wordlist: Wordlist) -> bytes:
"""Derive entropy from seed phrase.
Algorithm is specified in BIP-0039:
https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
>>> wordlist = Wordlist()
If the checksum is w... | b509c4302851c1797410a92aa64780228316904e | 3,620,812 |
def sort_list(player_data_list):
"""Sort list based on qualifer.
Args:
player_data_list: player data list
Returns:
player data list properly sorted
"""
return sorted(player_data_list, key=lambda x: x[-1]) | 7164d2851ca6c7557e8a9e10c45a25243254180d | 3,620,813 |
def AddLabelsFlag(parser, resource_type):
"""Adds labels flags for service-directory commands."""
return base.Argument(
'--labels',
metavar='KEY=VALUE',
type=arg_parsers.ArgDict(),
help="""\
Resource labels associated with the {}.
""".format(resource_type)).AddToParser(... | 82fc665ff77cb8df8e0d434e5690a9ce4d9e831d | 3,620,814 |
def _newton_soft_erf_kernel(rmax, r_soft, npts=500, rsmult=4.5):
"""
Newtonian force modified with the error function to match at r=rmax, i.e.
d/dr [ -erfc(r/2r_s) / r ] term rather than the Newtonian 1/r^2.
d/dr -> erfc(r/2r_s)/r^2 + exp(-(r/2r_s)^2) / sqrt(pi) r r_s
Optional short-range softenin... | 40b099dc43cc1a1e3b15b9e031cfbc2cea1bb72a | 3,620,815 |
def is_alive(worker_dict):
""" Test if worker is alive and running | None --> Bool """
return worker_dict['worker'].is_alive() | c3979d4722d27c8a3ceefe38b141313f4cdef881 | 3,620,816 |
def plotWav(wav, f, ratio, start, end, title, mode='t'):
"""
This function will plot a segment of wav data
if mode is 't', by default, the start& end means second
if mode is 'i', they means index
ratio & title is the params for plotting
"""
width, height = plt.figaspect(ratio)
fig = plt.... | ca5bdad357ec4cfcbfa459fb1a6b91afe3e800a9 | 3,620,817 |
def categorical_type_transformer(df: pd.DataFrame, ordered: bool = None):
"""
COnverts all objects dtypes into categorical dtypes and returns its
dataframe with the corresponding categorical codes
:params df: pd.DataFrame
:params ordered: bool
:return: pd.DataFrame
"""
df = df.copy()
for cols in df... | 7f2caef67dfa3f701bd82a942f061556983af002 | 3,620,818 |
def transform_cylindrical_to_cartesian(radial, axial, theta):
"""Assumes that axial direction coincides with the z-axis"""
x = radial*np.cos(theta)
y = radial*np.sin(theta)
z = axial
return [x, y, z] | 335e817d3eb2f7c558ec9f5cfa7570e3bb3997ff | 3,620,819 |
from typing import Dict
import torch
def sample_decode(
model,
size: int,
encoder_output,
masks: Dict[str, Tensor],
max_output_length: int,
labels: dict = None):
"""
Sample size sequences from the model
In each decoding step, find the k most likely partial ... | 7c66cb7d54cd5e3ee8f2f795a88d40d391fffb4f | 3,620,820 |
import sqlite3
import copy
def modify_patch_info(
input_info_db="patch_info.db",
slide_labels=pd.DataFrame(),
pos_annotation_class="",
patch_size=224,
segmentation=False,
other_annotations=[],
target_segmentation_class=-1,
target_threshold=0.0,
classify_annotations=False,
):
""... | 31deab62165b1e0735be58ceef17adebcd4e38d4 | 3,620,821 |
def sort(array: list[int]) -> list[int]:
"""Naive bubble sort implementation.
"""
for i in range(len(array)):
for j in range(len(array) - 1, i, -1):
if array[j] < array[j - 1]:
array[j], array[j - 1] = array[j - 1], array[j]
return array | f3121f84b238d82ea3cc7d87bfa993c2a9339786 | 3,620,822 |
import logging
import sys
def get_console_handler(logging_formatter=LOGGING_FORMATTER):
"""
Return a logging handler that sends logging output to the system's
standard output.
:param logging_formatter: An object `Formatter` to set for this handler.
:return: An instance of the `StreamHandler` c... | 6481207a0031c61cebd313f188debe94489f20e6 | 3,620,823 |
def organizar(exp, lista=False, dentro=False):
"""
Função responsável por adaptar o input do usuário, que é em formato de string para uma lista de cláusulas,
assim como aceita pela função "resolução".
:param exp: expressão a ser organizada
:param lista: se é ou não uma lista a ser organizada mais u... | e9aafd382200e12e9ffb8867b8cc79d7a8300d3f | 3,620,824 |
import logging
def delete_tasks(
client: GMPClient, task_name=None, states=['obsolete'], ultimate=False):
"""
Deletes a set of tasks.
:param task_name: name of the task to delete.
:param states: the tasks in `states` will be deleted.
:param ultimate: move to trash or delete permanently.
... | eaafdcdad9f166d218d399f1d222b2f65219b64b | 3,620,825 |
def box_teamnames(page):
"""
A @ H always
"""
teams = page.find_all("span", {"class": "short-name"})
destinations = page.find_all("span", {"class": "long-name"})
names = [team.text for team in teams]
cities = [destination.text for destination in destinations]
if not names or not cities:
... | f116fdb86fa347c5dcbaef40771b3f49d2b67f7a | 3,620,826 |
def login():
"""Logging in user"""
email = str(request.get_json().get('email'))
password = str(request.get_json().get('password'))
if not (email and password):
response = jsonify({
"message": "Enter required details correctly"
})
response.status_code = 400
ret... | 148c9837907def563556e3b253911242db73a979 | 3,620,827 |
def quadvgk(feval, fmin, fmax, tol1=1e-5, tol2=1e-5):
"""
numpy implementation makes use of the code here: http://se.mathworks.com/matlabcentral/fileexchange/18801-quadvgk
We here use gaussian kronrod integration already used in gpstuff for evaluating one dimensional integrals.
This is vectorised quadra... | d84a07ba9d5c4c96c65dffd6f8e710e4e2a73482 | 3,620,828 |
def exploreAMDBins(experiment, elec_bin=None):
"""
"""
cluster_results = readResults()
if elec_bin is None:
exc = cluster_results[['experiment_name','som_dim','n_clust','elec_bin',
'dbi','mia','silhouette','score','total_sample']]
else:
exc = clust... | 073b9dda10720144e1fe6921c1e689214ac99c5f | 3,620,829 |
import os
def collect_artifact_metrics(data):
"""Run CollectSequencingArtifacts to collect pre-adapter ligation artifact metrics
https://gatk.broadinstitute.org/hc/en-us/articles/360037429491-CollectSequencingArtifactMetrics-Picard-
"""
OUT_SUFFIXES = [".bait_bias_detail_metrics", ".error_summary_metr... | 9ac10376e76d9bb5007fdf729c0162071fa70ebf | 3,620,830 |
import struct
def prepare_packed_data(radius_packet, packed_req_authenticator):
"""
Pack RADIUS data prior computing the authentication MAC
"""
packed_hdr = struct.pack("!B", radius_packet.code)
packed_hdr += struct.pack("!B", radius_packet.id)
packed_hdr += struct.pack("!H", radius_packet.le... | 98e1235373f9c6992898920d54dbc8b9b14556c0 | 3,620,831 |
def _call_bool_filter(context, value):
"""Pass a value through the 'bool' filter.
:param context: Jinja2 Context object.
:param value: Value to pass through bool filter.
:returns: A boolean.
"""
return context.environment.call_filter("bool", value, context=context) | 181a51d7d436cf0eaf2c0fe9d2f04ab4030f010c | 3,620,832 |
def getNormalMask(coco, imageObj, filterClasses):
"""
iscrowd is set to None, therefore it only works for single
mask : (height, width)
Parameters
------------------------------------
"""
# Load categorical ids for filterclasses
catIds = coco.getCatIds(catNms=filterClasses)
input_im... | 42ba2eec70d10e3ad5fb8b2699119367cd799685 | 3,620,833 |
def lbp_cmp(f, g, O):
"""
Compare two labeled polynomials.
f < g iff
- Sign(f) < Sign(g)
or
- Sign(f) == Sign(g) and Num(f) > Num(g)
f > g otherwise
"""
if sig_cmp(Sign(f), Sign(g), O) == -1:
return -1
if Sign(f) == Sign(g):
if Num(f) > Num(g):
... | a9e1461d267f44fcb02f12180888d188eacfcd28 | 3,620,834 |
import copy
def findpatterns(spec, points, segments):
""" Method to search for patterns in the peaks. Specifically it is
looking for pairs of peaks that are the same distance apart (within
the tolerance). These can be an indicator of rotation/infall/etc.
Only two patterns are allowed to ov... | 46322f634698722e5d89d86651e29440b48270bb | 3,620,835 |
def delete_user_group(connection, id, error_msg=None):
"""Delete user group for specific user group id.
Args:
connection: MicroStrategy REST API connection object
id (string): ID of user group containing your required privileges
error_msg (string, optional): Custom Error Message for Err... | 8220525d2ee7d75483c1064dbe08955904864d37 | 3,620,836 |
def hmean(a, axis=0, dtype=None):
"""
Calculate the harmonic mean along the specified axis.
That is: n / (1/x1 + 1/x2 + ... + 1/xn)
Parameters
----------
a : array_like
Input array, masked array or object that can be converted to an array.
axis : int or None, optional
Axis... | e60c86a7add5e90d84e66532cc3d59a992665be7 | 3,620,837 |
def filepath():
""" ask for file path"""
filepath = hou.ui.selectFile()
return filepath | 70d6e514381d95f300ef651a94f6cb7b9611d123 | 3,620,838 |
def is_all_pass_testharness_result(content_text):
"""Returns whether |content_text| is a testharness result that only contains PASS lines."""
return (is_testharness_output(content_text) and
is_testharness_output_passing(content_text) and
not has_console_errors_or_warnings(content_text)) | 8f30159bd5c329c7821739c12e8e04b6842d2452 | 3,620,839 |
import re
def _getDefaultSlurmAccount():
"""Returns the default Slurm account for the current user.
"""
if system.existsExecutable("sacctmgr"):
user = system.run_output("whoami")
result = system.run_output("sacctmgr show User "+user + " -p")
s = re.search(user+r"\|((\S)+?)\|",... | 79eff1aff242c103d64526df4c46a0524604a311 | 3,620,840 |
def source_slice(request_data) -> str:
"""Write an entry source slice and return the updated sha256sum."""
return g.ledger.file.save_entry_slice(
request_data.get("entry_hash"),
request_data.get("source"),
request_data.get("sha256sum"),
) | 82fdf2c307cb7aabd1adb0cfd0afadb88be5c6d5 | 3,620,841 |
import pkg_resources
import sys
def create_dependencies_tree_by_req_file(
requirements_file,
allow_missing=False,
only_provenance=False
):
"""Create dist dependencies tree from file
:param str requirements_file: path to the dependencies file (e.g. requirements.txt)
:param bool a... | 3aa37747d053f29c4fbeefccb7b3f58755e2e485 | 3,620,842 |
from typing import cast
def send_super(receiver, selName, *args, **kwargs):
"""Send a message named selName to the super of the receiver.
This is the equivalent of [super selname:args].
"""
try:
receiver = receiver._as_parameter_
except AttributeError:
pass
if isinstance(rece... | c83fae1762868ac17c0e2f2ccbdee7c8c7d83560 | 3,620,843 |
import tqdm
import os
def preprocess_fundus(fundus_dir, manual_dir, mask_dir, all_filenames) :
"""
Load fundus images and return the followings:
inputImages = raw green channel of the fundus images
histEnhancedImages = green channel enhanced by CLAHE
stdImages = local standard deviation images
... | 9f5d07d7c6ef28602dd1831dfed0da00544a20be | 3,620,844 |
def discontinuous_match(biluov, sentence):
"""
>>> discontinuous_match(['B','V','L'],['la', 'enfermedad', 'renal'])
[['la', 'enfermedad', 'renal'], ['enfermedad']]
>>> discontinuous_match(['O','V','I','L','O','I','L'],['el','cancer','de','pulmon','y','de','mama'])
[['cancer', 'de', 'pulmon'], ['canc... | dba52c331e2ee5b8f76bed96e78cc911fa65c0ec | 3,620,845 |
def metric_transpose_theorem(model):
"""
Metric for how close encoder and decoder.T are
:param model: LinearAE model
:return: ||W1 - W2^T||_F^2 / hidden_dim
"""
# encoder_weight = get_weight_tensor_from_seq(model.encoder)
# decoder_weight = get_weight_tensor_from_seq(model.decoder)
encod... | 4522c134641df06f1f3528a8800f9d8ebcc2e431 | 3,620,846 |
def find_performance_space_price(package, size):
"""Find the price in the given package with the specified size
:param package: The product package of the performance storage type
:param size: The size for which a price is desired
:return: Returns the price for the given size, or an error if not found
... | db3b34b4903877c07011e70968b4129d83ece968 | 3,620,847 |
def find_region_pos(regions, pos):
"""Find the first region that starts after 'pos' in sorted 'regions'"""
low, top = util.binsearch(regions, pos-1, lambda a, b: cmp(a.start, b))
return top | 02dd297c30da90466d245eb6d765f030873ea7de | 3,620,848 |
import logging
import os
def runCommand(userhome, userconfig, argv):
"""
Run program with supplied configuration base directory,
configuration directory and command arguments.
This is called by main function (below), and also by test suite routines.
Returns exit status.
"""
options = pa... | 40fb89a4c0d5d8eda0cd8b7052eafeccff9752bb | 3,620,849 |
import json
import requests
def commands_post(cmd, base_url=DEFAULT_BASE_URL):
"""Commands POST.
Using the same syntax as Cytoscape's Command Line Dialog, this function converts a command string into a CyREST
query URL, executes a POST request, and parses the result content into a dict object.
Args:... | b24c07ee18aec63b568c187a5d772e36983756d5 | 3,620,850 |
from typing import Dict
from typing import Any
from typing import List
import six
def rowify(columns: Dict[Any, Any]) -> List[Dict[str, Any]]:
"""Converts columnar input to row data.
We treat the first dimension of each input tensor as `batch` dimension and
and break into single instance based on the `batch` d... | 9bb216beba9b0cfb9428e43cc5e18441587b3d74 | 3,620,851 |
def get_attr(attrs, key):
""" Get the attribute that corresponds to the given key"""
path = key.split('.')
d = attrs
for p in path:
if p.isdigit():
p = int(p)
# Let it raise the appropriate exception
d = d[p]
return d | eec6878b19413c54008eb930af21cd40decff2cc | 3,620,852 |
def constant(n):
""" Return the constant random variable *n*. """
return DiscreteRandomVariable(name=str(n), xs=[n], ps=[1.0]) | 63d1f0af4f7b41320b1802fa48796f170aba64c9 | 3,620,853 |
from typing import Union
from typing import Type
from typing import Callable
from typing import Any
from typing import cast
def reduce_(
accumulator: Accumulator[_TState, _T], seed: Union[_TState, Type[NotSet]] = NotSet
) -> Callable[[Observable[_T]], Observable[Any]]:
"""Applies an accumulator function over ... | ad876a70cd4be7426507912a4482b390be75ef41 | 3,620,854 |
def ch(i, A):
"""The children of i in A.
Parameters
----------
A : np.array
the adjacency matrix of the graph, where A[i,j] != 0 => i -> j
and A[i,j] != 0 & A[j,i] != 0 => i - j.
Returns
-------
nodes : set of ints
the children nodes
"""
return set(np.where... | 07544a2dab3be1254f2ead127912aa6f0dab5e26 | 3,620,855 |
def get_rays(H, W, focal, c2w):
"""Get ray origins, directions from a pinhole camera."""
# Tensorflow version
i, j = tf.meshgrid(tf.range(W, dtype=tf.float32),
tf.range(H, dtype=tf.float32), indexing='xy')
dirs = tf.stack([(i-W*.5)/focal, -(j-H*.5)/focal, -tf.ones_like(i)], -1)
... | 6dab0962c459e84b6cc2119e412b515d538cee39 | 3,620,856 |
def get_wbo(offmol, dihedrals):
"""
Returns the specific wbo of the dihedral bonds
Parameters
----------
offmol: openforcefield molecule
dihedrals: list of atom indices in dihedral
Returns
-------
bond.fractional_bond_order: wiberg bond order calculated using openforcefield toolkit ... | 82aa84036d3078826fedaec40e599ffd783a422c | 3,620,857 |
import ctypes
def MCFG(val):
"""Create class based on decode of an MCFG table from address or filename."""
addr = val
if isinstance(val, str):
data = open(val).read()
buf = ctypes.create_string_buffer(data, len(data))
addr = ctypes.addressof(buf)
hdr = TableHeader.from_address(... | c164bbc8c357b69b7561ce554bf5e5d78e37e846 | 3,620,858 |
from typing import Optional
def get_iot_connector_fhir_destination(fhir_destination_name: Optional[str] = None,
iot_connector_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
work... | df6605719074e25e1aa71d3f887fc2947580c27d | 3,620,859 |
def script(script, infiles = []):
"""Run a Yosys script given a path to the script
Inputs
-------
script : path to Yosys script to run
infiles : list of input files
"""
params = ["-q", "-s", script] + infiles
return get_output(params) | c2e5a063ac9febb304c2975ccd1b1da1b05dc9ff | 3,620,860 |
def sample_histogram(histogram, sample_fraction=0.05):
"""Sample a sample_fraction of colors from histogram"""
colors = np.fromiter(histogram.keys(), dtype='i8,i8,i8', count=-1)
counts = np.fromiter(histogram.values(), dtype=np.float32, count=-1)
size = counts.sum()
samples = (k * v for k, v in hist... | 69da30b9304afe3a5218ed7317cf25adf3b262eb | 3,620,861 |
def rename_volume(session, volume_id, display_name, return_type=None,
**kwargs):
"""
Sets the "display_name" volume parameter to a new value.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type volume_id: str
:para... | 99a62f72a8979a34e024e58381517851129ffe27 | 3,620,862 |
import sys
def updateLink(soup, url, session):
"""
update all relative url path in <a> tag in the html to absolute url path
Example:
Update href="/codegame/index.html" to href="https://www.w3schools.com/codegame/index.html"
"""
for res in soup.findAll('a'):
try:
if not... | 2a6f7c3702f7b8a39dbb8b30bcb5880485a80bf7 | 3,620,863 |
import random
def RandomJavascriptValue():
"""Generates code for a random javascript expression.
Returns:
Code for a javascript expression.
"""
roll = random.random()
if roll < 0.3:
return '"' + RandomIdentifier() + '"'
elif roll < 0.6:
return str(random.randint(-10000000, 10000000))
elif... | 2d64257038095d1f4c47bbdd50faca8078686e1d | 3,620,864 |
def add_hydrogen(mol):
"""Add hydrogens to saturate atomic valences.
Args:
mol (moldesign.Molecule): Molecule to saturate
Returns:
moldesign.Molecule: New molecule with all valences saturated
"""
pbmol = mol_to_pybel(mol)
pbmol.OBMol.AddHydrogens()
newmol = pybel_to_mol(pbm... | 34efbd18cc5fda30ea87e3824d5239c789a89a20 | 3,620,865 |
import sys
def typelogged_module(md):
"""Works like typelogged, but is only applicable to modules by explicit call).
md must be a module or a module name contained in sys.modules.
"""
if not pytypes.typelogging_enabled:
return md
if isinstance(md, str):
if md in sys.modules:
... | 6bdc94a03858e7492270388d91f543cd1dff192f | 3,620,866 |
def ler_blockchain(index=None, hash_bloco=None, origem=None, destino=None):
"""Retorna um bloco se especificado seu index ou hash.
Caso contrário, retorna todo o bloco"""
blockchain = ler_arquivo()
if index is not None:
for bloco in blockchain['blocks']:
if bloco['index'] == int(inde... | 288791c4e8f4384a9d6843fdfffd462d37ead9eb | 3,620,867 |
import re
def _GetLogTag(filename):
"""Get the tag of a log."""
regex = re.compile(r'\d+\-\d+(:?\-(?P<tag>.+))?.h5')
match = regex.search(filename)
if match and match.group('tag'):
return match.group('tag')
elif filename.endswith('.h5'):
return filename[:-3]
else:
return '' | 4be40e744478d4f0b8c5ffc7ea866537802b1f25 | 3,620,868 |
def sphere4(x: np.ndarray) -> float:
"""
Translated sphere function.
The most classical continuous optimization testbed.
If you do not solve that one then you have a bug.
"""
return float(np.sum((x - 4.)**2)) | 6da10be9a641155cf0c0a844e390548dcfc0b923 | 3,620,869 |
def Event_pick_graph_point(graph, vol, label, nodesOnly=False, axes=None, vis=True):
""" As snap_picked_point_to_graph but bound to axes with key control
Use p key to get picked point
"""
if axes is None:
axes = vv.gca()
point = dict()
# Define callback function
@axes.eventKeyDown.Bi... | 012cf33a9766b60dd63a4a41b7451f6497c8cf08 | 3,620,870 |
def get_relation_field_related_name(model, field_name):
"""获取关系字段的 related_name"""
field = get_relation_field(model, field_name)
if not field:
return
related_name = field.remote_field.related_name
if field.one_to_one:
return field.remote_field.name, field
if related_name is Non... | 3e76f63bf8a170a9c197749b7bfe6a7708f6236d | 3,620,871 |
def positional_encoding(position, d_model):
"""
Positional encoding is used to take into account the order of tokens in a sentence.
The output of this function will be added to the embeddings.
"""
angle_rads = get_angles(
np.arange(position)[:, np.newaxis], np.arange(d_model)[np.newaxis, :],... | a22faf3ef075d027050f0ca8ae75b5eb162d0ee6 | 3,620,872 |
import numpy
def l2_norm(x: numpy.ndarray, y: numpy.ndarray) -> numpy.ndarray:
"""Euclidean distance between two batches of points stacked across the first dimension."""
return numpy.linalg.norm(x - y, axis=1) | 248f004276d5459e7b6ce8906abc7bf950a9b1a3 | 3,620,873 |
import os
def extract_features_wotarget_14_dlstream(inifile):
"""Adapted version of extract_features_wotargat_14bp to work with fast feature extraction code within DLStream
Reduced feature selection based on recursive feature elimination for social behavior between 2 mice (anogenital approach, attack, etc.)
... | 78eb7fe23f86d9b522dc28a7c6e9c26b600de391 | 3,620,874 |
def get_maximisation(model_filename, max_epoch=3, learning_rate=0.1):
"""
Get a maximisation instance for the given model and set the max epoch and learning rate.
:param model_filename: The filepath to the model.
:param max_epoch: The maximum amount of epochs, gradient ascent parameter.
:param learn... | af0e0433c5514417c977def40a93d6b9e35d085e | 3,620,875 |
import random
def applydownsample(summary_occurrences, downsample):
"""
Downsample a categorized collection of systems according to a ruleset.
Arguments:
- summary_occurrences: dict produced by categorizeattractors
- downsample: system ruleset where the values are the number of each system type t... | 3974d7bcbb1f6f2443b0f3a183f5e180e15f8770 | 3,620,876 |
def lpi(
experiment,
with_evc_tree=True,
model="RandomForestRegressor",
model_kwargs=None,
n_points=20,
n_runs=10,
**kwargs,
):
"""
Make a bar plot to visualize the local parameter importance metric.
For more information on the metric, see original paper at
https://ml.inform... | f35accc0dcee7430b7d4d56771851c5de73c0bd6 | 3,620,877 |
def get_queue(queue_id): # noqa: E501
"""Get a queue by its ID
Returns the queue for a given ID # noqa: E501
:param queue_id: The ID of the queue
:type queue_id: str
:rtype: Queue
"""
return 'do some magic!' | 318c832e60d8f7e874948bf295935d3f243da14f | 3,620,878 |
def ilarisHitProb(at,vt):
"""
at: AT of attacking character
vt: VT of defending character
return: probability that attacking character will hit defending character
"""
# 47.5 is the chance without any bonus
# 47.5-((y-41)*y)/8 is the added chance per bonus
# (at>vt) is extra if at>vt bec... | 488668075154a509ed87345a17fac31b88c86d69 | 3,620,879 |
def create_eval_loaders(options, eval_type, keyframes,
total_batch_size = 8,
trajectory = ''):
""" create the evaluation loader at different keyframes set-up
"""
eval_loaders = {}
if trajectory == '':
trajectories = eval_trajectories(options.dataset)
else:
trajectories ... | 0cc19a2533b263f723e7975dc037fc5cfa98ccb7 | 3,620,880 |
def rec2gtk(r, formatd=None, rownum=0, autowin=True):
"""
formatd is a dictionary mapping dtype name -> mlab.Format instances
This function creates a SortedStringsScrolledWindow (derived
from gtk.ScrolledWindow) and returns it. if autowin is True,
a gtk.Window is created, attached to the
Sorte... | 98eee9eb9824e65c2bba9996f8aadbd724fb2eb5 | 3,620,881 |
def edges2d(Z):
"""
Like `edges` but for 2d arrays.
The size of both axes are increased by one. This is used
internally to calculate graitule edges when you supply centers to
`~matplotlib.axes.Axes.pcolor` or `~matplotlib.axes.Axes.pcolormesh`.
Parameters
----------
Z : array-like
... | 7e26f3ea9cfd52cc2db8c1a1103a92975817c0dd | 3,620,882 |
def GetGerritPatchInfoWithPatchQueries(patches):
"""Query Gerrit server for patch information using PatchQuery objects.
Args:
patches: A list of PatchQuery objects to query.
Returns:
A list of GerritPatch objects describing each patch. Only the first
instance of a requested patch is returned.
Ra... | 913dcd9e4b45da886f39ba1b7d8c193d41d1ab4d | 3,620,883 |
import string
import random
def random_string() -> str:
"""Return a random string of characters."""
letters = string.ascii_letters
return "".join(random.choice(letters) for i in range(32)) | dc828f6f89f1e20ee6cea5ebcbbecb38b0b07aa6 | 3,620,884 |
def universal_path(path: str) -> str:
"""
Converts a path name from its operating system-specific format to a
universal path notation. Universal path notation always uses a Unix-style
"/" to separate path elements. A universal path can be converted to a
native (operating system-specific) path via th... | 902235e97464dee43c88ac90c39f3e04ffe744de | 3,620,885 |
def build_fhir_profile(request,context={},
template="",
extn="json.html",
):
"""
Build a FHIR Profile in JSON
Use to submit to FHIR Server
:param template:
:param extn: json.html or json.xml (use .html to enable
... | 12054e9bb247c509f7e2a8b22907ca03d2618311 | 3,620,886 |
import requests
def notify_via_one_signal(access_token, title, message):
"""
Send a push notification to the user via OneSignal.
Arguments:
access_token (str): Access token for the API request.
title (str): Notification title.
message (str): Notification body.
"""
try:
... | 6b4261be6a66224f55bd1f6b9afd18741a7da729 | 3,620,887 |
import torch
def one_mask_generation(tokenizer, model, sentence, num_select=5, masked_sentence=None, ending="."):
"""
Function to get the most likely word (post softmax) to fill in the end of the sentence.
Example usage: one_mask_generation(BERT tokenizer, BERT model, "The apple is ")
"""
if maske... | ae411dd799591824a75680b8e510d20cf9b82c40 | 3,620,888 |
def create_control_in_program_scope(selenium, program):
"""Create control via UI."""
controls_service = webui_service.ControlsService(selenium)
controls_service.open_widget_of_mapped_objs(
program).tree_view.open_map().click_create_and_map_obj()
control = entities_factory.ControlsFactory().create()
cont... | ac40dff405e7b9d410c522d3aac0b22e5ba08f86 | 3,620,889 |
import time
import warnings
def run_test(**kwargs):
"""
runs a single test
:param kwargs:
:return: time, accuracy result
"""
ppc = kwargs['hog']
b = fetch_sw_orl()
tic = time.time()
# split the data in
X_train, X_test, y_train, y_true = train_test_split(b.data, b.target, test_... | d470ad2f4e9d30ac8e665d210ece5052c1dc444f | 3,620,890 |
import math
def zac(waves, calcs, lenght, sigma, flat, decay, wfin="waveform", wfout="wf_zac", test=False):
"""
ZAC filter.
inputs are in microsec (lenght, sigma, flat, decay)
"""
wfs = waves[wfin]
clk = waves["settings"]["clk"] # Hz
nwfs, nbin = wfs.shape[0], wfs.shape[1]
# conve... | 1c56c1644b0ba97ec7f496e065c411ac5c7b083d | 3,620,891 |
def label_image_to_one_hot_stack(
label: np.ndarray,
num_classes: int = -1,
channels_first: bool = False,
dtype: np.dtype = np.uint8
) -> np.ndarray:
"""Converts a label image into a stack of binary images (one-hot).
The binary image at index 'i' in the stack contains the pixels... | ff07e1c5a6a2be224a885094ae0f25dc100522ca | 3,620,892 |
def pacing_rhythm_detector(raw_sig:np.ndarray, fs:Real, sig_fmt:str="channel_first", ret_prob:bool=True, verbose:int=0) -> Real:
""" finished, checked, to be improved (fine-tuning hyper-parameters in cfg.py),
Parameters:
-----------
raw_sig: ndarray,
the raw 12-lead ecg signal, with units in mV... | de86759f1af0a0069172775cbdaa6beb717e7c38 | 3,620,893 |
import sys
def tfrecord_dataset(tfr_data_files_pattern,
batch_size,
seq_length,
seq_depth,
target_length,
num_targets,
mode,
use_static_batch_size=False,
... | afcd95b662a8460be1b28ccc6c0651f7750df1b2 | 3,620,894 |
def bbox_structure_to_square(bbox):
"""Function to turn from bbox coco struture to square.
[x,y,width,height] -> [min_height, min_width, max_height, max_width]
"""
x,y,width,height = bbox
sq = [y,x,y+height,x+width]
return sq | ff3147c89ad6d14ad22126bdc0cf119883d82db9 | 3,620,895 |
from typing import Pattern
def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
"""Replace `regex` with `replacement` twice on `original`.
This is used by string normalization to perform replaces on
overlapping matches.
"""
return regex.sub(replacement, regex.sub(replacemen... | 6bada9c7b349ba3a5da840e131577dd354f0b9eb | 3,620,896 |
import base64
def tobase64(x):
"""
python2/3 compatible conversion to urlsafe base64 encoding
"""
return tostr(base64.urlsafe_b64encode(tobytes(x))).replace('=', '') | 50b22c594709795861a4a92daa21cc980e944f2a | 3,620,897 |
def retrieve_tags_for_picture(picture):
"""Retrieve all tags for picture."""
database = get_db()
return database.retrieve_tags_for_picture(picture) | ea8c8970709007c96cc33357829066180e97f693 | 3,620,898 |
def _make_serving_input_fn(tf_transform_output):
"""Creates an input function reading from raw data.
Args:
tf_transform_output: Wrapper around output of tf.Transform.
Returns:
The serving input function.
"""
raw_feature_spec = common.RAW_DATA_FEATURE_SPEC.copy()
# Remove label since it is not avai... | 166c61eeecf79c59598f1155b33b6b2c219e4acd | 3,620,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.