content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def string_to_datetime(date_time_string):
"""
transform the datetime string to object
:param date_time_string: datetime in string format
:return: datetime in datetime format
"""
return parse(date_time_string) | 0684cc0cb2482b1de0a3c13d1a76c78236fe0d8b | 66,565 |
import collections
def flatten_feature_dict(metapath_to_metric_dict):
"""
Processed the nested dictionaries returned by features_for_metapaths()
into a single dimension dictionary with keys representing metapath and
metric combinations.
"""
feature_dict = collections.OrderedDict()
for meta... | 5f92c9bb1b51fa130e9306b0740490d9fcc93e14 | 66,566 |
def decode_text(encoded_text: str, reverse_mapping: dict):
"""
This function returns the decoded text from the text file.
Uses for loops and if statement to obtain the decoded text.
"""
decoded_text = ""
current_code = ""
# iterates over dictionaries using for loops
reverse_mapping = ... | 58fbff9e00b691919537b40a765f437a566fc730 | 66,568 |
from typing import Mapping
def _get_stix_version(data):
"""
Bit of factored out functionality for getting/detecting the STIX version
of the given value.
:param data: An object, e.g. _STIXBase instance or dict
:return: The STIX version as a string in "X.Y" notation, or None if the
version ... | 5f94549d038789c837530bb97fc49651f173659b | 66,569 |
def zk_runner():
"""A runner of shell commands with a mocked zk client"""
zkcli = mock.MagicMock(read_only=True)
return izk.runner.ZkCommandRunner(zkcli) | 18cedc8ff1f12d27c2dfcc0e246b39eee5601cc0 | 66,570 |
from pathlib import Path
import pandas
def parse_vcf_file(filename: Path, set_index: bool = True) -> pandas.DataFrame:
"""
Converts the VCF file generated by breseq into a pandas Dataframe.
Parameters
----------
filename: Path
Either a folder containing a single breseq run or a path to the vcf file itself.
s... | 290fb561bbf7e2682fc8994ad58897ea27088775 | 66,571 |
def recurrent_unit_bilateral(input_dim, hidden_dim, scope_name, i):
""" Define the recurrent cell in the LSTM. """
params=[]
with tf.name_scope(scope_name+str(i)):
Wi = tf.Variable(init_matrix([input_dim, hidden_dim]), name='Wi_'+str(i)) # weight for input
Ui = tf.Variable(init_matrix([h... | e0ffb715c8dbf82a633e6480a2721aabb8c9874f | 66,572 |
from typing import Union
from pathlib import Path
import platform
def make(
dist_dir: Union[str, Path],
layer: LayerConfig,
silent: bool = False
) -> Path:
"""
Make a layer.
:param dist_dir: the path to the distribution directory
:param layer: the layer configuration
:para... | 48550934af1368d3360b1677ebabedd628af6c7f | 66,573 |
def check_repos(repo_configs: list[RepoInfo], tag: str = None) -> bool:
"""
Check a list of repos to verify that the given tag exists for each repo
:param repo_configs: list of RepoInfo to check
:param tag: Name of the tag to check
:return: True if all of the repos have the requested tag
"""
for repo in r... | df8258c86d43b7ff2678580b8dd1bf09f227809d | 66,574 |
def apply_withdraw(account, amount):
"""Apply atomic transaction for withdraw"""
assert isinstance(account, Account)
assert amount > 0.0
if (account.balance - amount) < 0:
return False
else:
account.balance -= amount
account.save()
return True | 4b34f3ba2e7ef56981334ede442784fa38cc3f3f | 66,575 |
import functools
def compose(*fns):
"""Compose functions."""
def _compose(*args, **kwargs):
return functools.reduce(lambda v, g: g(v),
fns[1:],
fns[0](*args, **kwargs))
return _compose | 118c05955584cb7dd494e0615cccb82c3ccd8142 | 66,576 |
def buy():
"""Buy shares of stock"""
#>>>>>>Distribution code end<<<<<<
# User reacher route via POST
if request.method == "POST":
# Store user input
shares = request.form.get("shares")
symbol = request.form.get("symbol")
# Store current stock information
stock = l... | 9b6f010b77de34a132b2fd08aba95620e60a16eb | 66,577 |
def freeze(module: Module) -> Module:
"""Freeze
Freeze module's parameters (grad to False).
Parameters
----------
module: Module
module to freeze
Returns
-------
module: Module
module with freezed parameters
"""
for param in module.parameters():
par... | a8ed78de299667772b2dae7b947be203aa7751fa | 66,578 |
def command(func, _funcs={}):
"""Decorate functions with this to register them as commands"""
# register the command
func_name = func.__name__.lower()
if func_name in _funcs:
raise Exception('Duplicate definition for command {}'.format(func_name))
_funcs[func_name] = func
# play nice a... | d408b459335e0cfbb7e261e551c429489ca8dcfb | 66,579 |
def expected_sequence(red_on, green_on, blue_on):
"""Generates clock and data sequence expected by the Pimoroni Blinkt! for the colour specified"""
zero = [(1, 0), (0, 0)] # Clock and data sequence representing a zero (0)
one = [(1, 1), (0, 1)] # Clock and data sequence representing a zero (1)
brigh... | b38e222a7b605b4c94332b00bab319761a5a6d30 | 66,580 |
def get_featuretypes(name):
"""
Get the dataset featuretypes.
Parameters
----------
name : str
The dataset name to look for in our object storage.
Returns
-------
bytes
The dataset featuretypes encoded.
Raises
------
NotFound
When the dataset does n... | fe2ab6d64b9d2dbc67ec12289b41a63e5cc247b0 | 66,581 |
import shutil
def cut_paste(src_path, dst_path):
"""Cut paste functionality just copied from shutil. Works on files or dirs.
Args:
src_path (string): Source path to be cut
dst_path (string): Destination path to paste to
"""
shutil.move(src_path, dst_path)
return True | 295eee15f8e31f510333967a45c683ff99c25efb | 66,582 |
from operator import index
def __randUTV_workforjit(A, b, q, p):
"""
Performs the "optimized" randUTV in Figure4 of the paper.
Arguments
---------
A: (m x n) matrix to be factorized.
Gwork: (m x b) matrix that will be used as a work space for the
randomized range finder.
b (in... | f1cc837666b8ba7f0f48b14cad4c05d0e0944bfc | 66,583 |
def get_rot_dir(src_point, rot_rad):
"""Get rotation direction.
Parameters
----------
src_point : tuple of float
Original point.
rot_rad : float
Rotation radian.
Returns
-------
tuple of float
Rotation.
"""
sn, cs = np.sin(rot_rad), np.cos(rot_rad)
... | f5da7e41bf88b6c9016320d49227d95ce411e37f | 66,584 |
def getBase(path):
"""
:param str path:
:return: Base
:rtype: str
"""
return path.split("|")[-1] | a7dd2364531c5e1bea528dae738f60e2c2985d4c | 66,585 |
def get_vectors(x_array, y_array):
"""This function is for calculating vectors of bones from the openpose skelleton"""
vector_joint_idx = [[0,1],[1,2],[2,3],[3,4],[1,5],[5,6],[6,7],[1,8],[8,9],[9,10],[1,11],[11,12],[12,13]]
vectors = []
for i in range(len(vector_joint_idx)):
vectors.append(get_v... | 181433627cae3994594f0f1a9f0fc84271fdde9e | 66,586 |
import re
def parse_and_replace(instring):
""" Parse the input string for tokens, run replacers as needed. """
# Replace the token and command with the command return
instring = re.sub(r"!MyCmd\((.+)\)",
mycmd_replace,
instring)
return instring | dad749f0404c7c780ae201b18dab0d0ac166ab6e | 66,590 |
def get_predicted_points(gameweek, tag, position="all", team="all",
season=CURRENT_SEASON, dbsession=None):
"""
Query the player_prediction table with selections, return
list of tuples (player_id, predicted_points) ordered by predicted_points
"gameweek" argument can either be a ... | 301e69837426c200c16e2a069f2fcc0460c8e92d | 66,591 |
def average_one_rdm(filename, estimator='back_propagated', eqlb=1, skip=1, ix=None):
"""Average AFQMC 1RDM.
Returns P_{sij} = <c_{is}^+ c_{js}^> as a (nspin, M, M) dimensional array.
Parameters
----------
filename : string
QMCPACK output containing density matrix (*.h5 file).
estimator... | 8d83f2235d31edfac9e0f7d46c6c6601035e5adb | 66,592 |
from typing import Dict
from typing import Any
from typing import List
def get_all_external_files(filter_by: Dict[str, Any] = None) -> List[ExternalFile]:
"""
Get information about all external files in the system (note: no user access control)
:return: ExternalFile records
"""
if filter_by:
... | ae96240bd7af26de16f6135a1ad139fb26d91847 | 66,593 |
def data_entry_fields(fields,project,event):
"""
Gets the dataframe containing a specific arm from REDCap
"""
# Get a dataframe of fields
data_entry_raw = project.export_records(fields=fields, forms = forms, format='df', events=event)
return data_entry_raw | 42b562a65609cfc81f7584f86dfced0efcb8aab1 | 66,595 |
import torch
def to_device(m, x):
"""Send tensor into the device of the module.
Args:
m (torch.nn.Module): Torch module.
x (Tensor): Torch tensor.
Returns:
Tensor: Torch tensor located in the same place as torch module.
"""
assert isinstance(m, torch.nn.Module)
devic... | 13d1b9316222ee3f1d03eaca51fd3ab4fc15a0de | 66,596 |
def df_reindex(ts, index = None, method = None, limit = None):
"""
A slightly more general version of df.reindex(index)
:Parameters:
----------------
ts : dataframe or numpy array (or list/dict of theses)
timeseries to be reindexed
index : str, timeseries, pd.Index.
The new inde... | 342847321e1489a6c6aa760fafd1b4756f911ed3 | 66,597 |
def metadata_from_context_data(data):
""" Utility function transforming a `data` dictionary into metadata suitable
for a GRPC stream.
"""
metadata = []
for key, value in data.items():
name = "{}{}".format(METADATA_PREFIX, key)
value = encode_value(value)
metadata.append((name... | f6d5be9768d3a6b830cf31246a6546a21051e88b | 66,598 |
def encodePixel(px):
"""Given an RGB value, convert it to the nearest usable colour, and encode it as a character."""
r, g, b = px[0], px[1], px[2]
rgb = getNearestColour(r, g, b)
wsrgb = list(chars.keys())[list(chars.values()).index(rgb)]
return wsrgb | 59d6ba71638548fb12eb498d26b31a8c4091a275 | 66,599 |
from typing import Union
import torch
from typing import Sequence
from typing import Mapping
def collect_tensors(collection: Union[torch.Tensor, Sequence, Mapping]):
"""
Collect all the tensors in the sequence/mapping
"""
if isinstance(collection, torch.Tensor):
return [collection]
if isi... | 162a28d40f1aaa9b742877bd19ca769dbbf3c7c5 | 66,600 |
def separate_cell_nmt(src_input, tgt_input, unroll=True, **kwargs):
"""Returns a NMT network."""
hparams = create_nmt_hparams(**kwargs)
assert unroll
return SeparateCellNMT(hparams).build_graph(src_input, tgt_input) | 1a9611bd23c52ccf7a49f30836df8c36ec793ac0 | 66,602 |
def random_xffffffff(shape=(40,60), dtype=np.uint32, add=0xff000000) :
"""Returns numpy array of requested shape and type
filled with random numbers in the range [0,0xffffff] with bits 0xff000000 for alpha mask.
"""
a = 0xffffff*np.random.random(shape) + add
return np.require(a, dtype) | 40709c00e862adc255ac4f245c0c94af43e5085f | 66,603 |
def printSeq(startChar, endChar, seq, maxdepth):
"""
>>> printSeq('(', ')', (1, 2, 3), 4)
['(', '1', '2', '3', ')']
>>> printSeq('(', ')', (), 4)
['(', ')']
"""
if maxdepth < 1: return '&'
maxdepth -= 1
return [startChar] + [cprint2(x, maxdepth) for x in seq] + [endCh... | 9a5d1fa447928cb5769b238516d41a96c5c0ffef | 66,604 |
import six
def across_data_formats(func):
"""Function wrapper to run tests on multiple keras data_format and clean up after TensorFlow tests.
Args:
func: test function to clean up after.
Returns:
A function wrapping the input function.
"""
@six.wraps(func)
def wrapper(*args, ... | 224d5ede2a32518569513ce7dfb27bf2a8ab0f0f | 66,606 |
def process_data_arguments(data=None,
single_plot=False,
use_column_source=False,
flatten_np=False,
forbid_split_up=None,
same_length=False,
copy_data=False,
... | 98c2de34510632d2de17515c63c1ed1b81bc1c47 | 66,607 |
def create_stack(nodes):
"""helper function to create a stack"""
test_stack = Stack()
for el in nodes:
test_stack.push(el)
return test_stack | 5a902b693366346cbfd379b0b9d5ebf22feb0396 | 66,608 |
def mae(data: DatapointList) -> float:
"""
Computes the mean squared error.
:param data:
:param targets: A list of targets.
:param preds: A list of predictions.
:return: The computed mse.
"""
targets = [d.targets for d in data.get_data()]
preds = [d.predictions for d in data.get_dat... | d442ab67cdcf0439844f8a71dc576098c7a14128 | 66,609 |
def expand_on_basis_of_basic_representation(mappings):
""" Expansion using Basic Representation
:param response: Response obtained after hitting the base_url of collection
:param mappings: Mappings of variables and values provided by the user to expand template
:return: Expanded URL on the basis of Bas... | fae0ec69922f3be5f25a561c5bba9f602dc3bba6 | 66,610 |
def compile(mod, target=None, target_host=None, params=None):
"""Compile the module to VM executable. A helper function for VMCompiler.
Parameters
----------
mod : tvm.IRModule
The Relay module to build.
target : any multi-target like object, see Target.canon_multi_target
For homog... | 9f0bfb05339c4f122f36582ab7f922aa4e00ae08 | 66,611 |
import sqlite3
def get_multiple_data(table_name):
"""
get document data by document ID
:return:
"""
conn = sqlite3.connect(DATBASE_LOCATION)
cur = conn.cursor()
sql = '''SELECT rowid,* FROM {0}'''.format(table_name)
cur.execute(sql)
data = cur.fetchall()
conn.commit()
conn.... | 7c12261e016abdb779d2f997674cbad7d54d3126 | 66,612 |
def posterior(kalman, problem):
"""Kalman smoothing posterior."""
*_, obs, times, states = problem
return kalman.filtsmooth(obs, times) | 724a80cd69efa499cbc62f79ab611de30c10ac26 | 66,613 |
def get_cache_key_counter(bound_method, *args, **kwargs):
""" Return the cache, key and stat counter for the given call. """
model = bound_method.__self__
ormcache = bound_method.clear_cache.__self__
cache, key0, counter = ormcache.lru(model)
key = key0 + ormcache.key(model, *args, **kwargs)
ret... | 241b13b29b3dce0888f2eeb40361dfa03d5f8389 | 66,614 |
from typing import Callable
def fixed_step(f:Callable)->Callable:
"""
Decorator which fills in the missing time step parameters
:param t0: Initial time
:param t1: Final time
:param n_step: Number of time steps to take
:param dt: Time between steps
:param fps: Number of steps per time unit... | ed72b3fe50bbe70b8a539bcee93fde44be738a0c | 66,615 |
def get_HI_surface_density(
h1_intensity: np.array, major: float, minor: float, inclination: int
) -> np.array:
"""Calculate the HI surface density from the THINGS maps
Args:
h1_intensity (np.array): intensity of the HI emission in [Jy/beam km/s]
major (float): FWHM of the major axis of the... | d336eb66015e70788abc4956016280ec21ac7ac0 | 66,616 |
def shufflenet_block(scope, base_depth, num_units, stride, groups, groups_in=None):
"""Helper function for creating a shufflenet bottleneck block.
Args:
scope: The scope of the block.
base_depth: The depth of the bottleneck layer for each unit.
num_units: The number of units in the block.
... | 97a70194db1b30a7956cf058212ec2f33d7ad5fb | 66,617 |
import array
def read_feature(filename):
"""Read feature dump by C3D
Parameters
----------
filename : str
Fullpath of file to read
Outputs
-------
x : ndarray
numpy array of features
Note: It accomplishes the same purpose of this code:
C3D/examples/c3d_featur... | 5f79e850b629dac1bc1ced22d85d1be9e0131254 | 66,619 |
from datetime import datetime
def set_qos(s_url, s_qos):
"""
Sets a new QoS to the site if existing
:param s_url: str - URL/name of the site
:param s_qos: float - QoS value
:return: Site - The updated site or None if not existing.
"""
assert isinstance(s_qos, float), 'QoS value must be f... | 4a5cfda19b4e34dabba79a2adab41219e35c1c2a | 66,620 |
def extract(mod, models):
""" Returns models with mod removed. """
if mod == {}:
# No mod to delete, return models as it is.
return models
return [model for model in models if model != mod] | 5aa24ccaa238fe85f4f037c8af318e95a77b7b55 | 66,621 |
def extract_labels(all_samples):
"""
this function extracts the labels and speaker from the dataset
"""
labels = []
speakers = []
print("Extracting Labels")
for i in range(len(all_samples)):
temp = all_samples[i]
temp = (temp[0:-3].split("_"))
labels.append(float(temp[0]))
speakers.append(temp[1])
if i... | 65b2a07a709881f5d3c72931949673ee797ba1f3 | 66,622 |
import requests
def bond_spot_deal() -> pd.DataFrame:
"""
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-债券市场行情-现券市场成交行情
http://www.chinamoney.com.cn/chinese/mkdatabond/
"""
url = "http://www.chinamoney.com.cn/ags/ms/cm-u-md-bond/CbtPri"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... | 5f4355d54b476d47d86ae4d69e8aceef82ecf83f | 66,623 |
def get_mega_info_dict(samples):
"""Read mega info of all samples,
return a dict {(o_prefix, pbid) --> MergeGroupOperation(pbid, group1, group2)}
ex:
{('tmp_1009', 'PB.1.1'): MergeGroupOperation('PB.1.1', 'PB.2.1', None)}
"""
mega_info = {} # ex: (tmp_1009, PB.1.1) --> MergeGroupOperation(...)... | 9f9c3283633cdcc65dca4751fe65baa5b988d201 | 66,625 |
def write_xyz(tgt_geo, bath_geo):
""" Write the geom strings
"""
tgt_str = automol.geom.string(tgt_geo)
bath_str = automol.geom.string(bath_geo)
return tgt_str, bath_str | 9503e97dbad2621c5841ce6ad53ed86b8a1aa9e5 | 66,626 |
def get_prop(prop, default=None):
"""First order function which can be used to extract property of nodes"""
def get(n: Node):
return default if prop not in n else n[prop]
return get | 509602b279e6ee47128acaa84e788cab18024289 | 66,627 |
def _is_no_cache(request):
"""Returns True if the request should skip the cache."""
cache_control = request.headers.get('Cache-Control') or ''
return 'no-cache' in cache_control or 'max-age=0' in cache_control | bf8421a3f9a654a877cdf518aa9a4de532098f89 | 66,628 |
def scanner_config():
"""
读取配置文件
:return: dict
"""
with open("config.inf", "r") as f:
lines = f.readlines()
lines = [line for line in lines if cmp(line.strip(), "") != 0]
lines = [line for line in lines if not line.startswith("#")]
kv_dict = {}
for line in lines:
kv =... | 219003bac6d7b4dd7efa498ef58ba003f2f6a01d | 66,629 |
def get_missing(array, first=True):
"""
returns the ids of similar looking images that we haven't collected yet
array is
| ID | row | col | filename | lat | lon | X_1 | ... | X_n |
where
ID is the image id
row is the row pixel index of top left corner of subimage
col is the ... | 323a2b88a02fafe6f06f2e65be1be625a0ace29b | 66,630 |
def open_text(fname, **kwargs):
"""On Python 3 opens a file in text mode by using fs encoding and
a proper en/decoding errors handler.
On Python 2 this is just an alias for open(name, 'rt').
"""
if PY3:
# See:
# https://github.com/giampaolo/psutil/issues/675
# https://github.... | 56e4c364fa915a3b75eccfbd69fa91180612585b | 66,632 |
def plot_timeseries(server, e, dataset_id):
"""This defines the initial bqplot time series plot"""
dt_x = bq.DateScale()
sc_y = bq.LinearScale()
constraints = {"time>=": server.get("min_time"), "time<=": server.get("max_time")}
df, var = get_timeseries(
e=e,
dataset=dataset_id,
... | e6f12533716a33e2ef84a547d1ed471cd9b9ff31 | 66,633 |
def tf_idf(text):
"""
Compute the TF-IDF scores for each word in each document. The collection
of documents must be in bag-of-words format.
.. math::
\mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w))
where :math:`tf(w, d)` is the number of times word :math:`w` appeared in
document :math:`... | e008b666b58206ceb195ef84960eccadcef0b854 | 66,634 |
def get_chassis_serial(self):
""" Returns the serial number of the chassis
"""
output = self._vchannel.cmd('show inventory rack | inc "^ 0"')
line = output.split('\n')[0] # first line
tmp = line.split()
if len(tmp) > 2:
result = tmp[2]
else:
result = ''
BuiltIn().log... | ccbc69baaa0d093f50c6d49c3f68eb7a5a9c82c0 | 66,635 |
def create_resnet_encoder(
backbone_options: config_pb2.ModelOptions.BackboneOptions,
bn_layer: tf.keras.layers.Layer,
conv_kernel_weight_decay: float = 0.0) -> tf.keras.Model:
"""Creates a ResNet encoder specified by name.
Args:
backbone_options: A proto config of type
config_pb2.ModelOption... | f98c1bda75614c284fc8d7255b8e693aa6253a47 | 66,636 |
def group_function(table_columns, table_row, tree):
"""True if resultset should be grouped
:return: Grouping function or None and its position.
:rtype: tuple(EtcdbFunction, int)"""
try:
group_position = 0
for select_item in tree.expressions:
expr = select_item[0]
... | 68d6d27bb61499f191ed74b6e6e586e227aaff48 | 66,637 |
import numpy
import itertools
def stratify_irregular_dimension(storage_units, dimension):
"""
Creates a new series of storage units for every index along an irregular dimension that must be merged together
:param storage_units:
:param dimension:
:return: storage_units: list of storage_unit-like ob... | 331a0acbe670ce71341cc6fa3dd3ac4ae51e29b5 | 66,638 |
def _var_get_id(self, vname):
""" Lookup var value by name or ID
returns ISY Id or None
"""
if not self._vardict:
self.load_vars()
if isinstance(vname, IsyVar):
return vname["id"]
else:
v = str(vname)
if (v).upper() in self._vardict:
# print("_get_var_id : " ... | 17b3a47524cba6ff338ee830a820173ab942c34a | 66,639 |
from re import T
def sgd(cost, params, lr=1.0, alpha=0.1):
"""SGD with Momentum (and Langevin Dynamics)"""
grads = T.grad(cost=cost, wrt=params)
updates = []
for p, g in zip(params, grads):
v = shared(p.get_value() * 0.)
v_new = v * (1.0 - alpha) - alpha * lr * g
updates.append... | a4eae61be3ca192553adda9ea829bd5997d4e900 | 66,640 |
def get_or_else(data, key, default_value = None):
"""
Tries to get a value from data with key. Returns default_value in case of key
not found.
"""
if not data:
return default_value
try:
return data[key]
except:
return default_value | 53bc769a3331684c46127b08976fd62ca1ab47df | 66,641 |
def update_rl_veh(env,
rl_queue,
rl_veh,
removed_veh,
control_range,
num_rl,
rl_ids):
"""Update the RL lists of controllable, entering, and exiting vehicles.
Used by the open environments.
Parameter... | 616be730420795755d5b628284517572b0c2248f | 66,642 |
def tree_BFS(root_node):
"""
My Python implementation of BFS for a tree
Traverses a binary tree from its root and returns an array of the nodes in traversal order
Time complexity: O(n), n = Number of nodes
Space complexity: O(n)
"""
# Track BFS traversal
bfs_traversal = []
# Queue for next nodes to explore... | 349f4df805dee0c13bc3c58865b2fc3543528a53 | 66,643 |
import functools
def DeletionTest(f):
"""This indicates a test that uses deletion."""
@functools.wraps(f)
def Decorator(testinstance):
if testinstance.TEST_DELETION:
return f(testinstance)
else:
return testinstance.skipTest("Tests that use deletion are disabled "
... | 2f27803408a4a92e3f29def203845f27dfd0a113 | 66,645 |
def get_hyponyms(synset):
"""
Get the WordNet hyponyms that are in the model
Params
synset: nltk WordNet synset
"""
hyponyms = synset.hyponyms()
# hyponym_terms = [hyponym.lemmas()[0].name() for hyponym in hyponyms]
# hyponym_terms = [term for term in hyponym_terms if term in diction... | a0e28825869240868e0d48a02481d93b57aeee6a | 66,646 |
def calc_frac(x, func, total=None):
"""
calculate the fraction of entries in *x* that satisfy *func*
"""
total = total or len(x)
return np.count_nonzero(func(x)) / total | fba8c6b2eba855740adb8ebb2d5585af5ea644a9 | 66,647 |
from datetime import datetime
def get_monthly_file_content_by_date(date: datetime) -> str:
"""
Get the content of the monthly trajectory summary file for a given date.
:param date: The date to get the monthly file for.
:return: The content of the monthly file.
:raises: requests.HTTPError if the ... | 35a1f57f952e94285ddea50bb623db2d25e71136 | 66,648 |
def get_frame(df, t, fps=20):
"""Gets the player data from the right frame
Arguments:
df: pd.DataFrame with player tracking data
t: timestamp of the play
fps: frame per second
Returns:
dfFrame: pd.DataFrame with player tracking data from timestamp t
Raises:
"""
dfFrame = ... | 51bad21aa17978bcfee37fe31edb79ddb45e9191 | 66,649 |
def MOE_batch_means(samples, log=False):
"""Assumes unkown mean, unknown variance, unknown distribution.
Assumes 50 samples. Batches into 5 groups of 10 samples.
Computes the 95 percent margin of error."""
if len(samples) == 0:
return float('nan')
batchSize = 10
batches = [samples[i:i+batchSize] for i in range(... | d7e9fc2cc2396e3072cc947bede43b0b8cde751c | 66,650 |
import math
def pformat_bar(
value, width=40, prefix="", vmin=0., vmax=1., border=True, fill=' ',
reverse=False):
"""Return a progressbar-like str representation of value.
Parameters
==========
value : float
Value to be represented.
width: int
Bar width (in charac... | 6b12a5bb2bd4d051224b2f5960a0378b0593b2f7 | 66,651 |
import functools
def Elrn_chan(state, chan, data):
""" External learning along a channel with data,
as mulitset of predicates """
def lshift(a, b): return a << b
freqs = [data(*data.sp.get(*a))
for a in np.ndindex(*data.sp.shape)]
freq = sum(freqs)
stats = [(data(*a) / freq) *... | 62846791f085ccf2d03a11a7f6a1bdc69a3a3605 | 66,652 |
import select
async def get_all_tenants():
"""
Return all tenants
"""
query = select(Tenant)
results = await DBSession.execute(query)
return {"action": "get", "tenants": results.scalars().all()} | 03de24fa79c8565d8409fa664f52e4b65ae84a78 | 66,653 |
import cmath
import math
def exp(x):
"""
Return the exponential value of x
"""
if isinstance(x,ADF):
ad_funcs = list(map(to_auto_diff,[x]))
x = ad_funcs[0].x
########################################
# Nominal value of the constructed ADF:
f = exp(x)
... | 3bbb7a29ae187f9450366e730cb13aec6da04bbc | 66,654 |
def lab2xyz(lab_arr):
"""
Convert colur from CIE 1976 L*a*b* to CIE 1931 XYZ
Parameters
----------
lab_arr: ndarray
Color in CIE 1976 L*a*b*
Returns
------
xyz_arr: ndarray
Color in CIE 1931 XYZ
"""
L, a, b = lab_arr[:, 0], lab_arr[:, 1], lab_arr[:, 2]
... | 08edc4ce78837369a87135e3cf4b35e2965f356d | 66,655 |
def test_generator(func_graph, stack_roots):
"""Return the function that will start the fault-tolerance testing for a graph"""
def test(self):
"""Test fault-tolerance of the topology"""
self.set_up(func_graph, stack_roots)
self.network_function()
return test | 1a607086ef68833894f8d031589c61dd8557f090 | 66,656 |
def gaussian2D(omega1, cent1, delta1, omega2, cent2, delta2, corr=0.0):
"""Two-dimensional complex Gaussian lineshape
"""
gamma1 = 0.0
gamma2 = 0.0
return voigt2D(omega1, cent1, delta1, gamma1,
omega2, cent2, delta2, gamma2, corr=corr) | 104e692401e87608cf235b21c8e79d5b8cb35f2c | 66,657 |
from typing import List
def create_msk_from_classes(
mc_msk: np.ndarray,
classes_to_use: List[int],
out_msk_pix_value: int = 255,
out_msk_dtype: np.dtype = np.uint16,
) -> np.ndarray:
"""
Create a mask of type out_msk_dtype set to the out_msk_pix_value for pixels
belonging to the required ... | d1818935a9948090882431454dc04dc0d34b076f | 66,658 |
def kmeans(
s: pd.Series,
n_clusters=5,
init="k-means++",
n_init=10,
max_iter=300,
tol=0.0001,
precompute_distances="auto",
verbose=0,
random_state=None,
copy_x=True,
n_jobs=-1,
algorithm="auto",
):
"""
Perform K-means clustering algorithm.
"""
vectors = l... | c28dcca61c637923a69dece2cc9b1b61d66526f0 | 66,659 |
def tile_read_utm(source, bounds, tilesize, indexes=[1], nodata=None,
alpha=None, dst_crs='EPSG:3857', verbose=False,
boundless=False):
"""Read data and mask.
Arguments
---------
source : str or :py:class:`rasterio.io.DatasetReader`
input file path or :py:cla... | c16c89cc2d4c62c530f8f9ecafe73fb858a7f664 | 66,660 |
def __float2pcm(npy_array, _type='int16'):
"""Convert <npy_array> from float to pcm.
Default conversion type is 'int16'.
"""
info = np.iinfo(_type)
amp = 2**(info.bits - 1)
offset = info.min + amp
npy_array = npy_array * amp + offset
return npy_array.clip(info.min, info.max).astype... | 1d7e125740e77cce01ea15081d17bea0e397c82e | 66,661 |
def force_str(s, encoding="ascii", errors="strict"):
"""Converts s to str (which is bytes on Python 2, and unicode on Python 3), using
the provided encoding if necessary. If s is already str, it is returned as is.
If errors="strict", str is bytes, and s is str, its encoding is verified by decoding
it; ... | 0b8b78f715923680bd56e025bded36fba98ee332 | 66,662 |
import csv
def process_csv(csv_file):
"""Turn the contents of the CSV file into a list of lists"""
print("Processing {}".format(csv_file))
with open(csv_file, "r") as datafile:
data = list(csv.reader(datafile))
return data | 87603c21d09332cc1e1d25a3de6074f984f95426 | 66,663 |
def _change_vname(match) -> str:
"""Change variable name using the match object from re.
:param match:
:return: String with the variable name translated
"""
return (
match.group('mup_pre')
+ _translate(match.group('vname'))
+ match.group('mup_post')
) | e1c8a5c250a5bf0d67906e54d12a97067403fdb8 | 66,664 |
def weighted_average(values, weights=None):
"""Calculate the weighted mean average between two iterables of `values`
and matching `weights`. If weights is ``None`` they will be autogenerated
Args:
values(iterable): Values to average, either `int` or `float`
weights(iterable): Matching weigh... | 465b63f02e3a7cf92737938e4352c154abbae911 | 66,665 |
import math
def random_cartesian_from_polar(r_low, r_high):
""" function that returns a random cartesian coordinates gives within the radius limits from polar coordinates """
# generate the polar angle between 0 <= x < 360 degree
polar_angle = np.random.uniform(0, 360, 1)[0]
# generate the radius... | 0dc136ab0e56902625cba8a70ba76b782b7bab04 | 66,666 |
def unwrap_f(arg):
"""Multiprocessing pool.map requires a top-level function."""
return Corex.calculate_p_xi_given_y(*arg) | f3440ca4927eff696b95ed00bbf92b0e1a58f8a3 | 66,667 |
from typing import Union
def precision_rate(true: np.ndarray,
predicted: np.ndarray,
condition: Union[bool, int, str, list, tuple, set]) -> float:
"""
compute precision rate, refer module description for calculation;
:param true: numpy.ndarray(shape=(m), ), an array o... | 671c00b4a3c5886a22d34a822564f7fd4e5bde17 | 66,668 |
def u3(self, theta, phi, lam, q):
"""Apply u3 to q."""
return self.append(U3Gate(theta, phi, lam), [q], []) | 85f9da6a911e7ef8fbfb47771331843511d1b8fb | 66,669 |
import re
def new_exposures(out):
"""Scan rsync output for exposures to be transferred.
Parameters
----------
out : :class:`str`
Output from :command:`rsync`.
Returns
-------
:class:`set`
The unique exposure numbers detected in `out`.
"""
e = set()
e_re = re.c... | 8fc8817fe0ad79c177473ec676853569d733ec65 | 66,670 |
def conv2d_reduce_sum(x, input_height, input_width, padding, strides):
"""Sums along the output dimensions in line with a convolution.
For example, with a kernel size of 3, padding=`VALID`, and stride of 1, then
with respect to each spatial dimension of the convolution (and disregarding
class, batch and channe... | d7d345cf0b0c03144b173404d258a5d745793dd7 | 66,671 |
def violin_plot(df, class_masks, class_names, column_name, class_colors=None, alpha=1.0, transformation_function=None,
pseudocount=0, y_label=None, figname=None, vert=True, yticks=None, figax=None, **kwargs):
"""Make a violin plot with len(class_masks) violins for the specified column from a DataFra... | 76445f7d7bed5e503c5978c1aba602893ad389bd | 66,674 |
from datetime import datetime
def now():
"""Current UTC datetime string suitable for use as a Solr dt field."""
return datetime.utcnow().isoformat(timespec='seconds') + 'Z' | 390877fc1b7592df54300cb70b9b62590f1bd4c9 | 66,675 |
def get_classification(X, theta, temp_parameter):
"""
Makes predictions by classifying a given dataset
Args:
X - (n, d - 1) NumPy array (n data points, each with d - 1 features)
theta - (k, d) NumPy array where row j represents the parameters of our model for
label j
... | cce812d6511a197767c7c1c7cf6ad26f09c306c1 | 66,676 |
import base64
def create_message(sender, to, subject, message_text):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text: The text of the email message.
Returns:
An object ... | 89f9ddde8d5a1161461078ab614c718d8ef6dd12 | 66,677 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.