content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def tensordot(x, y, axis=2):
""" Compute tensor dot product along specified axes.
axes : int or (2,) array_like
integer_like If an int N, sum over the last N axes of a and the first N axes
of b in order. The sizes of the corresponding axes must match.
(2,) array_like Or, a list of axes t... | c833140019247602643166e3527cd8c506efd794 | 46,754 |
def _is_tarfile(filename):
"""Returns true if 'filename' is TAR file."""
return (filename.endswith(".tar") or filename.endswith(".tar.gz") or
filename.endswith(".tgz")) | 761b776e0e8078ddd4bee694e0a9d853dd2e31fd | 46,755 |
def deleteAnonMsgs(key, dbn='anon', env=None):
"""
Deletes messages at key uid
Parameters:
key is anon uid
dbn is name str of named sub database, Default is 'anon'
env is main LMDB database environment
If env is not provided then use global gDbEnv
"""
global gDbE... | 054645e2267f6add970b5b44ad13825e8a739f3b | 46,756 |
def get_rho(w):
"""
:param w: 対象の値
最小位から数えて最初の1ビットの位置(1-indexed)
"""
return libc.ffs(w) | 6b05211eb86eff1a1473e1f42681063ef8878cc0 | 46,758 |
import tqdm
import torch
def data_collection(env: gym.Env,
num_episodes: int = 10,
epsilon: float = 0.2,
use_gt_states: bool = False,
use_tqdm: bool = False):
""" Collect demonstration dataset """
train_inputs = []
train_actio... | 7d8967934526bb1ef56e4097a3da9f9c099402e7 | 46,759 |
from typing import Optional
import asyncio
import contextlib
from typing import cast
def get_running_loop() -> Optional[asyncio.AbstractEventLoop]:
"""Check if an event loop is already running."""
with contextlib.suppress(RuntimeError):
if hasattr(asyncio, "get_running_loop"):
return cast(... | 48750bc03be5d8cd17da20a3ca01d02149d471f5 | 46,760 |
def distance_diff_catl(ra, dist, gap):
"""
Computes the necessary distance between catalogues
Parameters
-----------
ra: float
1st distance
dist: float
2nd distance
Returns
-----------
dist_diff: float
amount of distance necessary between mocks
"""
... | 2a523d1c9c132dc8fcb65bd8d633bf24fcf46f42 | 46,761 |
def calculate_degree(network):
"""Calculates the degree of the nodes from the from and to ids. It
is not wise to call this method after removing nodes or edges
without first resetting the ids
Args:
network (class): A network composed of nodes (points in space) and edges (lines)
Returns:
... | 11e1d0ad1d02f1e32c89688a368e359c278c1581 | 46,762 |
def parse_token(filehandle, token):
"""Iterates through filehandle until token found. If value found after
token, returns it."""
for line in filehandle:
line = line.strip()
if line.startswith(token):
if len(line) > len(token):
return line.rsplit('\t', 1)[1]
... | 9f65ec378b33903250173aaa3f97cd058de13d2b | 46,763 |
def logsumexp(matrix, dim=None):
"""
Compute log(sum(exp(matrix), dim)) in a numerically stable way.
:param matrix: input ndarray
:type matrix: ndarray
:param dim: integer indicating which dimension to sum along
:type dim: int
:return: numerically stable equivalent of np.log(np.sum(np.e... | 2fefc6e4a88d5dfa006d8e587ee18845960689c9 | 46,765 |
def _run_adb(adbcommand):
"""Run the adb binary."""
cmd = [ADB]
cmd.extend(adbcommand.split())
return process.check_output(cmd) | 72e718f77e0d23055dcc9ba3e83ad547bfac26f2 | 46,767 |
def _label_constraint(key, value):
"""
Returns a label constraint for host limit 1
:param key: The key fo the label
:param value: The value of the label
"""
return task_pb2.Constraint(
type=1,
labelConstraint=task_pb2.LabelConstraint(
kind=1,
condition=2,
... | 6c18e9a852b0bd924cf3ac70669acb7cc8676e57 | 46,769 |
def trim(infile, outfile):
"""Trim video with ffmpeg. Returns tuple of filename and dict of trim times"""
if not pyask.yes_no("Does the video need to be trimmed?", default="yes"):
return (infile, {"start": 0, "end": None})
start, end = get_trim_times()
run(
[
"ffmpeg",
... | a21e8515cbf5e03b5e68493279a021bf0bd41c12 | 46,770 |
def u3u2(u3):
"""
feet&inch to inch
"""
f = u3[0]
if f == '': f = 0
else: f = int(f)
i = u3[1]
if i == '': i = 0
else: i = round(convert_to_float(u3[1]), 2)
u2 = f*12 + i
return str(u2) | 271bec37281a89e4add68828e437ae909d8cbbd6 | 46,771 |
from pydantic_factories import ModelFactory
def create(policy_backbone: ModelFactory, value_backbone: ModelFactory):
""" Vel creation function """
return DeterministicPolicyModelFactory(
policy_backbone=policy_backbone, value_backbone=value_backbone
) | 05970ef98baec267a33629c0eb13da1dd807db12 | 46,773 |
def main(args: Namespace) -> bool:
"""
The Function to process the data at the given path using the given transformation rules
and store them at given destination path. if any file fails at transformation level,
it will be stored in error path
Args:
args (Namespace): Argument Namespace con... | 96a3098f9df10b58fdc55b894ff3901d80ab7eeb | 46,774 |
def alt(*args: Pat) -> Pat:
"""Matches one of the given choices.
>>> alt() # will never match
alt()
>>> alt('a')
'a'
>>> alt(alt('b', 'c'), 'd')
alt('b', 'c', 'd')
"""
choices = []
for a in args:
if isinstance(a, Alt):
choices.extend(a.choices)
else... | 88f8490cb800d80315ad81aac7b9a62f6055fe56 | 46,776 |
def batch_get_value(ops):
"""Returns the value of more than one tensor variable.
# Arguments
ops: list of ops to run.
# Returns
A list of Numpy arrays.
"""
if ops:
return get_session().run(ops)
else:
return [] | ef3018db0f3640c13910cc9d1b7af848499d4e51 | 46,777 |
def calculate_interest_years(starting_amount, requested_amount, interest_rate, stipend_rate):
"""
If I want X in the bank, how long will it take?
:param starting_amount: The amount of money the bank has to start with.
:type starting_amount: double
:param requested_amount: The amount requested in the... | 9af2d7917d4b7184d09467a1a996bdb86adcbd21 | 46,778 |
def short_information(title, index=0):
"""
Takes in track information and returns everything as a short formatted String.
Args:
title (str): track title string
index (str): optional track number string
Returns:
A short formatted string of all track information.
"""
if ... | 6754af1f2327eb5d9f37f4d25aa4f808d4793553 | 46,779 |
from typing import List
from typing import Dict
from typing import Callable
def post_processor(provider: str = None, parser: str = None,
provider_parser_list: List[Dict] = None) -> Callable:
"""
Decorator that register function for post processing. You can insert provider and parser or
... | a0a4a27d405c130547c0c83908133e4a882804e6 | 46,781 |
def AddAttachedCertificatesFlagsToParser(parser):
"""Adds flags describing certificate update without resource args."""
is_clear_certificates = base.Argument(
'--clear-certificates',
help='Removes all certificates from the entry',
action='store_true')
group = base.ArgumentGroup(
help='Arg... | 5b5cbea6f5b18db1ea4b04bd45c1693e8c78d2f0 | 46,782 |
def vmaddrelu(x, y, z):
"""
calculate relu(x * z + y), only support float16, float32.
Args:
x (tvm.tensor.Tensor): input.
y (tvm.tensor.Tensor): input.
z (tvm.tensor.Tensor): input.
Returns:
tvm.tensor.Tensor, relu(X * Z + Y).
"""
return multiple_elewise_op(x,... | c1f10e19208ba43c60f98832a99f4aad20792202 | 46,783 |
def setup(hass, config):
"""Set up the keyboard_remote."""
config = config.get(DOMAIN)
keyboard_remote = KeyboardRemote(hass, config)
def _start_keyboard_remote(_event):
keyboard_remote.run()
def _stop_keyboard_remote(_event):
keyboard_remote.stop()
hass.bus.listen_once(EVENT... | 2b519b4a7ce979e3c74e9f299f4b8d54bc6dd7d2 | 46,784 |
def _compute_taylor(data_input):
"""Algorithm: atanh(x) = x + x^3/3 + x^5/5 + x^7/7"""
taylor_para = [0, 1.0, 0, 1/3.0, 0, 1.0/5, 0, 1.0/7]
# x^2
data_mul_2 = topi.multiply(data_input, data_input)
# 1/5 + x^2/7
data_mul_2_7 = topi.multiply(data_mul_2, tvm.const(taylor_para[7], "float32"))
... | a4e96d647ddc8531c8ba1a4c1d878922881a13e1 | 46,786 |
def infer_feature_types(data, feature_types=None):
"""Create a Woodwork structure from the given list, pandas, or numpy input, with specified types for columns.
If a column's type is not specified, it will be inferred by Woodwork.
Arguments:
data (pd.DataFrame): Input data to convert to a Woodw... | f584d5d6d8c4034a547af0e75d46a4ed9edd377d | 46,787 |
def apply_token_replay(log, net, initial_marking, final_marking, parameters=None):
"""
Calculates all metrics based on token-based replay and returns a unified dictionary
Parameters
-----------
log
Trace log
net
Petri net
initial_marking
Initial marking
final_mar... | 3712011039921d88bfd0026fd824dd84148353cd | 46,788 |
def add_css_file_extension(name):
"""
Appends the CSS file extension to a string.
:return: name with '.css' append at the end append at the end
:rType: string
"""
return '%s.css' % name | fbe4569e4660cc4145bac36a5ea88ae87ec4c319 | 46,789 |
import collections
import numpy
def get_data_hlsp_everest(obsid):
"""
Given a EVEREST observation ID, returns the lightcurve data.
:param obsid: The EVEREST observation ID to retrieve the data from.
:type obsid: str
:returns: JSON -- The lightcurve data for this observation ID.
Error codes... | 1a3ff1f4421fc1b6ca0ccdd83aa69c6c684b83f3 | 46,790 |
def try_protection(var, target, attacker, attacker_role, reason):
"""Attempt to protect the player, and return a list of messages or None."""
prots = []
for protector, entries in PROTECTIONS.get(target, {}).items():
for scope, protector_role in entries:
if attacker_role in scope:
... | 2e226135a222a887ce39bda8a61c146fd7dfeade | 46,791 |
def _get_position(a, n):
""" returns position of substring :n: as "start", "end" or "middle" """
position = a.index(n)
if position == 0:
return ("start", position)
elif position+len(n) == len(a):
return ("end", position)
else:
return ("middle", position) | f7a18c540542f117df822c18396e3e554d1eba45 | 46,792 |
import six
import uuid
def data_factory(value, encoding='UTF-8'):
"""Wrap a Python type in the equivalent C AMQP type.
If the Python type has already been wrapped in a ~uamqp.types.AMQPType
object - then this will be used to select the appropriate C type.
- bool => c_uamqp.BoolValue
- int => c_uam... | 47021c6afb22bee803c36ba1b4eb3ab4b8a3687c | 46,793 |
def AllTokens():
"""Retrieves all descendants of pygments.token.Token."""
def Traverse(token):
for tok in token.subtypes:
yield tok
for sub_token in Traverse(tok):
yield sub_token
return sorted(Traverse(pygments.token.Token)) | 86686f691a3023477ce9c1892641de1d4a6e509a | 46,794 |
def previous(values, elements, scope=None, strict=True):
"""Return closest previous (index, elem) of values withing scope.
Assumption:
values and elements are sorted
"""
# Init iterator on elements
elem_indexes = enumerate(elements)
index, elem = next(elem_indexes)
try:
nin... | 36b83dc2665539a3a9cb8b50419cd15410a8969c | 46,795 |
from typing import Dict
from typing import Any
import toml
def _load_prefs() -> Dict[str, Any]:
"""Load user preferences from TOML and return as a dict
:return: dict containing user preferences
"""
try:
return dict(toml.load(PREFERENCES))
except (IOError, toml.TomlDecodeError):
l... | 369296b7292b02cec01503462ed5bf6a54c949c9 | 46,796 |
def slice(from_index, to_index, list_or_string):
"""Returns the elements of the given list or string (or object with a slice
method) from fromIndex (inclusive) to toIndex (exclusive).
Dispatches to the slice method of the third argument, if present"""
return list_or_string[from_index:to_index] | 130692bad6f7de87a07786afe0ea3d6d30902ba7 | 46,797 |
def accuracy(output, target):
"""Computes the precision@k for the specified values of k"""
# batch_size = target.size(0) * target.size(1) * target.size(2)
_, pred = output.max(1)
pred = pred.view(1, -1)
target = target.view(1, -1)
correct = pred.eq(target)
# correct = correct[target != 255]
... | 4f6f25311f1579d8d638a684d40bd80d99387eae | 46,799 |
def parse_identification_method(tag, type):
"""
parses id_marc_tag tag attrib for proper handling in pymarc obj
args:
tag str (marc tag)
type str (standard, control field)
return:
(tag, subfield) tuple
"""
if type == 'standard':
tag_to_check = tag[:3]
subf... | 0b7dca44196ccfabdca102e7a966d4bd7987eef0 | 46,800 |
from typing import List
def entropy_from_indexes(indexes: List[int], lang: str) -> Entropy:
"""Return the entropy from a list of word-list indexes.
Return the entropy from a list of integer indexes into
a given language word-list.
"""
n = _wordlists.language_length(lang)
entropy = 0
... | 4f996eaa49a1719195ed866da3ab6e56aaaa2bae | 46,801 |
def decompress_G2(p: G2Compressed) -> G2Uncompressed:
"""
Recovers x and y coordinates from the compressed point (z1, z2).
"""
z1, z2 = p
c_flag1, b_flag1, a_flag1 = get_flags(z1)
# c_flag == 1 indicates the compressed form
# MSB should be 1
if not c_flag1:
raise ValueError("c_f... | 77d5bb816fdf8a1a5c9bbce7b9fb3da65c29b7f8 | 46,802 |
def lnprob(lnparams, *args):
""" The ln-probability function.
Calculates the logarithmic posterior probability (likelihood times prior)
of the model given the data.
Args:
lnparams (array): The parameter array containing Equivalent
Evolutionary Point (EEP), age in log10(yrs), metall... | bf369647abce998ff9ec7d74f933b4bf221b5c5b | 46,803 |
def VerifyCbiEepromWpStatus(dut, cbi_eeprom_wp_status,
ec_bypass_cbi_eeprom_wp_check):
"""Verify CBI EEPROM status.
If cbi_eeprom_wp_status is Absent, CBI EEPROM must be absent. If
cbi_eeprom_wp_status is Locked, write protection must be on. Otherwise, write
protection must be off.
... | 34aad3d8c73174d2b1f5ef20d3925a59ca9f4227 | 46,804 |
def coding_strand_to_rna(strand):
"""returns the coding strand to the rna strand (T --> U)"""
strand = strand.upper().replace("T","U")
return strand | 5c3420e921c10376b33b17dfc34e7301414bc6ef | 46,805 |
def _process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (Dictionary of Lists) raw structured data to process
Returns:
List of Dictionaries. Structured data to conform to the schema.
"""
for entry in proc_data:
# add timestamps
... | 7ba6283bf8aaf89f144d3584c8c260ce4a70bc73 | 46,807 |
def load_rsa_key(filename):
"""
Function to get an RSA key from the specified file for Paramiko.
"""
return paramiko.RSAKey.from_private_key_file(prepend_home_dir(filename)) | 291df80fe2623d801dce9ffe71472a09a93ad303 | 46,808 |
def F_score(xs, ys, beta=0.01):
"""
Returns the F score described here: http://en.wikipedia.org/wiki/F1_score
for list `xs` against to the list `ys`.
Make beta smaller to give more weight to the precision.
"""
p = precision(xs, ys)
r = recall(xs, ys)
if (p + r) == 0:
return 0, 0... | 7e4a7267b793449490103fef509a9324940d592d | 46,810 |
def get_db_len(session_id):
"""
Args:
session_id (int): id of a user's session
Returns:
int: how many songs the user has rated in a specific session
"""
cursor, connection = open_db_connection()
try:
cursor.execute(
f"""select count(*)
fro... | f072bfd4d62e388e0630428de4fdf6dcd76bbc38 | 46,811 |
from pathlib import Path
def create_addr_record(addr_file: Path) -> clusterlib.AddressRecord:
"""Return a `clusterlib.AddressRecord`."""
f_name = addr_file.name.replace(".addr", "")
basedir = addr_file.parent
vkey_file = basedir / f"{f_name}.vkey"
skey_file = basedir / f"{f_name}.skey"
if not... | d61667b57c15c8df3688e934251cc2e83d9f0449 | 46,812 |
def graph_to_entities_json(g):
"""
Converts the given graph to entities JSON.
:param g: a graph
:return: an array of JSON
"""
entities = []
for u, v in g.edges():
entity = {
"Device": "",
"IP": "",
"Identity": "",
"Location": "",
... | ef790764c9e6ff4f652c41a5af1d5da3e4d98733 | 46,813 |
def create_annotation_ce_target(creator: str, field: str = None, fragment: str = None):
"""Return a mutation for making an AnnotationCETarget.
An AnnotationCETarget is a node that can be used for a
web Annotation (https://www.w3.org/TR/annotation-model)
as the target field, when the target refers to a n... | dc7219cc02f22dcb8e230c7e376becf8712f71bc | 46,814 |
def sg_put(gid, chid, value):
"""perform a `put` within a synchronous group.
This `put` cannot wait for completion or for a a callback to complete.
"""
if not isinstance(chid, dbr.chid_t):
raise ChannelAccessException("not a valid chid!")
ftype = field_type(chid)
count = element_count(... | 479f5750871a76b676c3868fe9ae094c8b7eb748 | 46,815 |
def do0(*items):
"""Like do, but return the value of the first item.
Examples::
y = do0(17,
assign(x=42),
lambda e: print(e.x),
print("hello from 'do0'"))
assert y == 17
y = do0(assign(x=17), # the first item can be an assignment, too
... | 7491eae056ecb9f32d0dfc5f7cac6a4b13074917 | 46,816 |
def TransformScope(r, *args):
"""Gets the /args/ suffix from a URI.
Args:
r: A URI.
*args: Optional URI segment names. If not specified then 'regions', 'zones'
is assumed.
Returns:
The URI segment after the first /*args/ in r, the last /-separated
component in r if none found.
Example... | f3521519d8beb4863e843799a468e1a339b7a947 | 46,817 |
def variational_mfvi_sample(n_sample, qf_mean, qf_sdev,
mfvi_mixture=False, mixture_par_list=None,
**kwargs):
"""Generates f samples from GPR mean-field variational family.
Args:
n_sample: (int) number of samples to draw
qf_mean: (tf.Tenso... | c643f737541654c200dda2ba784a4168bd3f8e0e | 46,818 |
def recode_mark(mark, mark_shouldbe, no_mark="XX"):
"""A little helper function to remap clips to standard values that can
then be parsed.
Replaces BP with LPRP so ADBP becomes ADLPRP.
Arguments:
- `mark`: A mark string returned by the glfc database.
- `mark_shouldbe`: a dictionary mapping va... | ea31126d8b3d6e519a1f376f4ef58bfdbc24914a | 46,819 |
def select_copy_number(query, query_id):
"""
Execute copy-number query and return results
"""
cur = connection.cursor()
cur.execute(query, (query_id,))
rows = cur.fetchall()
values = []
for row in rows:
value = CopyNumberValue(entrez_gene_id=row[0], depmap_id=row[1], value=r... | 57049e1bccbd8685fca2a8ac488337b7fb47c9ea | 46,821 |
def read_single_camera_description(filename, camera_name):
"""
Read a specific camera description from a DL1 file
Parameters
----------
filename: str
camera_name: str
Returns
-------
`ctapipe.instrument.camera.description.CameraDescription`
"""
geom = read_single_camera_geo... | ecf0b89bd2f9815af4b695d9dea1d059746c1fa5 | 46,823 |
def _get_remains(courses):
""":param courses: list of (id, num) pair"""
return map(int, [i[u'课余量'] for i in val]) | 83a1c7596ff9594e3615bd7e7ffada6a675d3b4d | 46,824 |
from textwrap import wrap
def _update_doc(doc):
"""Add a list of plugins to the module docstring, formatted as
a ReStructuredText table.
"""
info = [(p, plugin_info(p)) for p in plugins() if not p == 'test']
col_1_len = max([len(n) for (n, _) in info])
wrap_len = 73
col_2_len = wrap_len... | ccba1a92ed5c7e0a62f31f020ccb3d2f2ef2f157 | 46,825 |
def IDO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2017-11-03", **kwargs
) -> Graph:
"""Ret... | 58c2f1886290390a3895de4fc946d5bf97bf9001 | 46,827 |
def scrape_detail(url):
"""
scrape detail page and return its html
:param page: page of detail page
:return: html of detail page
"""
return scrape_page(url) | 65a5bf44eef3da76b09f8b69f1d20fa59e31d569 | 46,828 |
def build_phone_encoder(features, speaker_labels, feature_length, params, endpoints, reuse_variables, is_training=False):
"""Build encoder for phone latent variable.
Use the tdnn and share the same structure in the lower layers.
Args:
features: the input features.
speaker_labels: the speake... | 950ed3fdb25531f8fd9542235cd2d18279c5d70a | 46,830 |
def from_probit(func):
"""
Evaluate a function that samples points in probit space and return these points after transforming them to natural space
"""
def f_transf(ref, *args, **kwargs):
y = func(ref, *args)
return transform_from_probit(y, ref.bounds)
return f_transf | 30c6b28829369b67869b91536dda356cb37c7cdd | 46,831 |
def token_is_valid(token):
"""Validate a checkout token."""
if token is None:
return False
if isinstance(token, UUID):
return True
try:
UUID(token)
except ValueError:
return False
return True | deceee5b33eddec2f80bff5de73bf13864b61e4b | 46,832 |
def shortest_path(map, dest, default_value = 0, block_value = 1):
""" Find shortest-path field
:param map: the proposed map (2-d)
:param dest: the goal, a point
:param default_value: the identifier for default cell
:param block_value: the identifier for block cell
:return: floor field and a dis... | fadcddd9cbccc88e21939515e8d31fe0755b8854 | 46,833 |
import ast
def _ast_eval(node):
"""
Performs an algebraic syntax tree evaluation of a unit.
"""
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
ast.USub: op.neg}
if isinstance(node, ast.Num): # <number>
... | b0eb1763aa17bca01350f5a6f65bc52894533682 | 46,834 |
from typing import Iterable
from typing import Any
def getWriteOutColour(
colour: Iterable[Any], convertType: type = int, multiplier: int = 255
) -> list[Any]:
"""getWriteOutColour"""
return [convertType(col * multiplier) for col in colour] | b81784b8e6fcce6a1479b710bc59b0db9c94241c | 46,835 |
from typing import Dict
from typing import Any
def create_tsmp_placeholders(
name: str,
model_start_time: pd.Timestamp,
end_time: pd.Timestamp,
run_dir: str,
tsmp_config: Dict[str, Any],
cycle_config: Dict[str, Any]
) -> Dict[str, Any]:
"""
This function creates... | 4e0920228bbae25f3c81e0433e8352962b7a180e | 46,837 |
import re
import json
def getIdsOfCities(session, all=False):
"""Gets the user's cities
Parameters
----------
session : ikabot.web.session.Session
Session object
all : bool
boolean indicating whether all cities should be returned, or only those that belong to the current user
... | 30dde3974095cd4ef037371dc06194c6bc9ffb46 | 46,838 |
def tx_collector():
"""A helper to deduplicate transactions"""
def snowflake():
txids = set()
txs = []
while True:
tx = yield txs
if tx:
if tx.id not in txids:
txids.add(tx.id)
txs.append(tx)
... | d164db9f30c8458a17d3e9d929f2e76d3b19154d | 46,839 |
def initialize_model_from_run(run_id):
"""
Initialized a model based on a run_id (i.e., using the exact
same parameter settings)
Parameters
----------
run_id : int
The Openml run_id
Returns
-------
model : sklearn model
the scikitlearn mo... | 1b766d94e1db90cb35717aed433e113b116b044b | 46,840 |
def get_block_header_by_hash(block_hash, db):
"""
Returns the header for the parent block.
"""
return db.get_block_header_by_hash(block_hash) | 96b5ec740e6286baa55140dd6467bfcc6a8e035b | 46,842 |
def extract_meta_lang(html):
"""
Returns the meta_lang of the HTML provided or None if unsuccessful
:param html:
:return: meta_lang | None
"""
meta_lang = None
try:
goose_config = {'enable_image_fetching': False}
goose = Goose(goose_config)
article = goose.extract(r... | aa0aa7454394107abb9ce52c16219969b06179a3 | 46,843 |
import time
import requests
def collect_data(post_id, duration):
"""
Collects data every 30 secs for {duration} hours on post with {post_id}.
Stores data as a list of objects. Each object contains the number of likes
the post has and the time in secs.
Args:
post_id: String -- id of the post t... | e08376cb710ff8f0e050e992ebdf84a47ce05da5 | 46,845 |
def filter_tags(tags: dict, tag_filter: dict) -> bool:
"""filter tags based on a tag filter"""
including = False
includes = tag_filter['includes']
if 'tag-keys' in includes:
including = any(key in tags for key in includes['tag-keys'])
if not including:
if 'tag-key-values' in include... | 74141ec75ab5551765589411f8746bd448038262 | 46,846 |
def load_ls(ls_path,px_size=1.):
"""Loads a linescan file
Args:
ls_path (str): path of the average linescan file to be loaded
px_size (float): pixel size in microns
Returns:
x (numpy array): the positions (in microns)
i (numpy array): the intensities
"""
ls_data =... | b9c984d020741c373f89c3cb0236fe5a8c2029f6 | 46,847 |
def add_frame_div_parent(cell_info):
"""
Adds the frame a cells parent divides on to cell info.
Args:
cell_info (dict): dict that maps cells to cell info
Returns:
dict: cell info with added frame_div_parent
"""
new_info = cell_info.copy()
for info in new_info.values():
... | 585feeaaf2a353ea2481cda41d547a004ecb8adc | 46,848 |
def _binary_search(alloc, p, d):
"""Compute step length using the binary search long step from BGKL.
Parameters
----------
alloc: AllocationProblem
Allocation problem instance
p: np.ndarray
Price vector.
d: np.ndarray
direction vector s.t. d in {0,1}^n.
Retu... | a1a43651f799f0734296b3ef4fc065a684f5efad | 46,849 |
def feature_engg(df: pd.DataFrame) -> pd.DataFrame:
"""Feature engineering function"""
numeric_feats = df.dtypes[df.dtypes != "object"].index
skewed_feats = df[numeric_feats].apply(
lambda x: skew(x.dropna())
) # compute skewness
skewed_feats = skewed_feats[skewed_feats > 0.75]
skewed_f... | 685c8ba7f6a72ab4912caa19a1024d77b29290c8 | 46,850 |
def upsample(layer, k, s, layer_name):
""" Return the output of transpose convolution given kernel_size k and strides s """
return tf.layers.conv2d_transpose(inputs = layer,
filters = NUMBER_OF_CLASSES,
kernel_size = (k, k),
... | 4f30af47b7665f353bfbd40b2a577f708081eac9 | 46,851 |
def get_data_size_recursively(data) -> int:
"""
Deprecated (Only for revision 2 and below).
Returns size of data(input data or deploying content) by recursive traversal
:param data: input data or deploying content
:return: size of data
"""
size = 0
if data:
if isinstance(data, d... | 0717fcae7377f56da069696e5b6b73ff5ba518eb | 46,852 |
def _to_array_1d(scalar_or_array, arrlen, dtype=float):
"""
A helper function for writing forces that can accept either a single parameter,
or an array of per-particle parameters.
If passed a scalar, it converts it to an array of the length arrlen.
If passed an iterable, it verifies that its leng... | 1107af19f882778a179d9ce40d6bab15d618f0f8 | 46,853 |
def add_datafile2session(db_session, date_obs, data_provider, data_type, fname_raw,
fname_hdf="", flag=0):
"""
:param db_session: sqlalchemy.orm.session.Session
SQLAlchemy session object
:param date_obs: datetime.datetime
The observation ... | 72bbfabd870eeb015f2f5ad166f7def5fadbd062 | 46,855 |
import numba
def gingerbreadman(n_points: int = 10**6, x_0: float = 1.5, y_0: float = 2.6) -> PlotData:
"""
Calculates a list of (x, y) points according to the Gingerbreadman Map
https://en.wikipedia.org/wiki/Gingerbreadman_map
:param n_points: The number of (x, y) plot points to calculate
:param... | bbbdac680975c88fe3d054f0ab2de002d36c51b8 | 46,856 |
def focal_starting_points(
recording_meta: dict,
seizure_types: list = None):
"""Return a list of dictionaries which contain the focal events.
Here the interest is only on the starting points.
Args:
recording_meta: a dictionary which contains the metadata
of the recording.
... | 5fe79d5be10bfb65f32e1c2305f4b228f752ca61 | 46,857 |
import torch
def nanmean(arr, dim=None, keepdim=False):
"""
Compute the mean of an array ignoring any NaNs.
RH 2021
"""
if dim is None:
kwargs = {}
else:
kwargs = {
'dim': dim,
'keepdim': keepdim,
}
nan_mask = torch.isnan(arr)
arr_no... | b7ca5d59b1f3a43893511433acc7fd5611584beb | 46,858 |
def max_area_index(labels, num=None):
"""
Return index of maxmum labeled area
"""
mx = 0
mxi = -1
un = np.unique(labels)
# kick out zero
un = un[un != 0]
for l in un:
mxtmp = np.sum(labels == l)
if mxtmp > mx:
mx = mxtmp
mxi = l
return mxi | 8bdd3309604689c7a4102b92530b0e4595673f77 | 46,859 |
def basic_cell(args, i, unit_mul):
""" Construct the basic cell. """
c = tf.contrib.rnn.LSTMCell(
args['num_units']*unit_mul,
# dropout_keep_prob=args['dropout']
)
c = tf.contrib.rnn.DropoutWrapper(
cell=c, input_keep_prob=(1.0 - args['dropout']))
if i > 1:
c = ... | b7cb3cfe3ca4531ec5ae61a1dbe4353cb64c9184 | 46,860 |
import json
def getAuditLogsWithDecision(decisionUuid, user):
"""
expected: decisionUuid(string), user(object)
result: all audit logs objects that attached to a decision \
would be returned in a json.
"""
data = dict()
if decisionUuid == '' or not user:
msg = "checklistUuid or user... | 01a9d5584702d965ff3a65de6c5217e107c8a816 | 46,863 |
import sqlite3
def db_create(db_path="main.db"): # noqa: D205, D400
"""Check that the database doesn't exist, create the database, create the
tables, finally connect to the database.
Use os.path.isfile() on the database path to check if the file exists.
Connect to the database. Set the conn.isol... | 2d96696d3589e4c438a80070164126274bc5c8ba | 46,864 |
import functools
import traceback
def signal_wrapper(func):
"""
Signal fail-safe wrapper
:param func: original signal
:return: fail-safe signal function
"""
@functools.wraps(func)
def _signal_wrapper(*args, **kwargs):
"""
Wraps original signal wrapper with try
"""
... | cef6369828636ba704b4c3675c33f5242019baaa | 46,865 |
def kml_to_dict(kml_file):
"""
Reads the supplied KML file and returns a dictionary with datetime
keys and descriptions/coordinates (lists of (lon,lat,ele) tuples) as
values. Can contain one level of subfolders as subdictionaries.
"""
print(f"Reading KML from \"{kml_file}\"...")
def placema... | 6d4e735732e8b8fdea87248b1e1b3aecf6fbc9ad | 46,866 |
def load_intron_vector(table, session):
"""
load intron vector entries for this gene. Wrapper for generic_gene_query.
:param table: One of the intron vector tables
:param session: Active sqlalchemy session.
:return: DataFrame
"""
assert any(table == cls for cls in (TmIntronSupport, AugCgpInt... | 4034002b2c3d9cd42a250adaf6f8beff5042cef1 | 46,869 |
def polar_err(r, phi, r_e, phi_e):
"""polar errors for r and phi"""
# print(r, phi, r_e, phi_e)
dxdr = np.cos(phi)
dxdphi = r * np.sin(phi)
dydr = np.sin(phi)
dydphi = -r * np.cos(phi)
x_e = np.sqrt((dxdr * r_e) ** 2 + (dxdphi * phi_e) ** 2)
y_e = np.sqrt((dydr * r_e) ** 2 + (dydphi * ph... | 2cf7f68bcd5d3a09dd8442a23f904bba9828cc06 | 46,871 |
async def get_textchannel_chatlog(text_channel: discord.TextChannel, limit: int = None):
"""
Returns a TextChannel chatlog
:param text_channel: The text channel for the data to be gathered from
:param limit: An integer to limit the amount of messages retrieved.
:return: String
"""
all_messa... | dfde857bca4d5ba086c194423e65f9a57f0f3bb4 | 46,872 |
import string
def clean_sort(words):
"""A function for cleaning and prepping words for techniques.
Args:
words (list): The list of words
Returns:
list: An updated word list with words cleaned and sorted.
"""
if isinstance(words, basestring):
return words
chars = '!"#$... | 353c1b9ec0b6a29c627dee33b0833e83e4318f59 | 46,873 |
def source_to_neutrino_direction(azimuth, zenith, radian=True):
"""Flip the direction.
Parameters
----------
zenith : float
neutrino origin
azimuth: float
neutrino origin
radian: bool [default=True]
receive + return angles in radian? (if false, use degree)
"""
a... | fca46e24e93ee996542c8ca5c3b6f553daa8068a | 46,875 |
from typing import Optional
from typing import Tuple
def preprocess(
x: np.ndarray, y: np.ndarray, nb_classes: int = 10, clip_values: Optional["CLIP_VALUES_TYPE"] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Scales `x` to [0, 1] and converts `y` to class categorical confidences.
:param x: Data ins... | 541c3d27b48c017aa23ca7ca08522b8371ad42ee | 46,878 |
from typing import Optional
def partition_softmax(logits: ArrayTree,
partitions: jnp.ndarray,
sum_partitions: Optional[int] = None):
"""Compute a softmax within partitions of an array.
For example::
logits = jnp.ndarray([1.0, 2.0, 3.0, 1.0, 2.0])
partitio... | 89704d75fb147129364b1d555857c1bb1bb2355c | 46,879 |
def split_pem_chain(pem_text):
"""
splits a PEM chain into multiple certs
"""
_certs = CERT_PEM_REGEX.findall(pem_text.encode())
certs = [cleanup_pem_text(i.decode("utf8")) for i in _certs]
return certs | 95a96aa569bc0d768d0dada85d913f593cd732f4 | 46,880 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.