content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def match(pattern, name):
"""Test whether a name matches a wildcard pattern.
Arguments:
pattern (str): A wildcard pattern, e.g. ``"*.py"``.
name (bool): A filename.
Returns:
bool: `True` if the filename matches the pattern.
"""
try:
re_pat = _PATTERN_CA... | 145023b54449f85bed0421dcf446352c32328bae | 52,866 |
def _OldEnough(try_bot_cache, bot_id):
"""Checks if the build in the given bot's cache is older than threshold."""
built_cp = try_bot_cache.full_build_commit_positions[bot_id]
tot_cp = git.GetCommitPositionFromRevision('HEAD')
return built_cp < tot_cp - STALE_CACHE_AGE | 0b6ff7a3e1f08ecf602239d127ac879539975bcc | 52,867 |
def the_joke():
"""
Combining both joke and emojis into one function.
"""
return yomama() + laugh() | f7a6baa9cba166f8ddd6d8993f4d8d7225c8d467 | 52,868 |
def return_dict():
"""
"interfaces": {
"Tunnel0": {
"state": "UP"
},
"Tunnel1": {
"state": "DOWN"
}
}
}
"""
return {"interfaces": {"Tunnel0": {"state": "UP"}, "Tunnel1": {"state": "DOWN"}}} | 2c3e71341c425166d11aba9175e3a98027c3d53e | 52,869 |
from typing import List
import itertools
def allocation_with_lowest_gain(agents: List[Agent], allocations: List[CakeAllocation]) -> CakeAllocation:
"""
Finds an allocation such that for all agents, gain(agent) (as defined by `get_agent_gain`) in that
allocation scope is less than the sum of gain(agent) fo... | 3de69a8f735329fb110e7323c851b3a13c58522e | 52,870 |
import torch
def replace_magnitude(x, mag):
"""
Extract the phase from x and apply it on mag
x [B,2,F,T] : A tensor, where [:,0,:,:] is real and [:,1,:,:] is imaginary
mag [B,1,F,T] : A tensor containing the absolute magnitude.
"""
phase = torch.atan2(x[:, 1:], x[:, :1]) # imag, real
ret... | b535e4271c6fc4fe508af358fbe3eee59a95cc6b | 52,871 |
def is_ip_address(host: str) -> bool:
"""Determine if host is an IP Address."""
try:
ip_address(host)
except ValueError:
return False
return True | 90b66e8b8b43ee20796ba2e3a408d217978741aa | 52,872 |
def cut_rod2(p, n, r={}):
"""Cut rod.
Same functionality as the original but implemented
as a top-down with memoization.
"""
q = r.get(n, None)
if q:
return q
else:
if n == 0:
return 0
else:
q = 0
for i in range(n):
... | 2fa1433dffb9099709e466025645c4981f289692 | 52,873 |
import logging
def RunLoad(redis_vm, load_vm, threads, port, test_id):
"""Spawn a memteir_benchmark on the load_vm against the redis_vm:port.
Args:
redis_vm: The target of the memtier_benchmark
load_vm: The vm that will run the memtier_benchmark.
threads: The number of threads to run in this memtier_... | 9935a619a6c267023fdcf751b24b9a339d28551a | 52,874 |
from re import T
def import_data():
"""
Export data via CRUD controller.
Old - being replaced by Sync.
"""
title = T("Import Data")
return dict(title=title) | 5547236231e524e3d36fde1249f0eb0eaa9427df | 52,877 |
def _set_karma(bot, trigger, change, reset=False):
"""Helper function for increasing/decreasing/resetting user karma."""
channel = trigger.sender
user = trigger.group(2).split()[0]
if reset:
bot.db.set_nick_value(user, 'karma', 0)
return
karma = bot.db.get_nick_value(user, ... | 72531c032625c365e057057edb84672b86a4faac | 52,878 |
def read_kazr(filename, field_names=None, additional_metadata=None,
file_field_names=False, exclude_fields=None):
"""
Read K-band ARM Zenith Radar (KAZR) NetCDF ingest data.
Parameters
----------
filename : str
Name of NetCDF file to read data from.
field_names : dict, opt... | 7b8d87c27b4a69ddbe40ed4e8c5b68b981b06ef9 | 52,879 |
def addScriptOptions(parser, pos_args, kw_args):
""" add script-specific script options """
script_options_group = parser.add_argument_group('Options')
hlpstr = "Prefix string for output filenames. Can optionally include a " \
"full path. Defaults to the input filename."
... | fbf44211bd23eb46e564dee9e6f8b5262f613176 | 52,880 |
def get_dag(node):
"""
:param str node:
:return: Maya dag path node
:rtype: OpenMaya.MDagPath
"""
sel = OpenMaya.MSelectionList()
sel.add(node)
return sel.getDagPath(0) | c28ce48a801ebde3c55e34235546eafa9f67b612 | 52,881 |
def aistats2022():
"""Font size for AISTATS 2022."""
return _from_base(base=10) | 984c4e7e697fea6a8c7643d2e8ac80b20f1fdfc5 | 52,882 |
def format_filt( something ):
"""
Example of a filter that can be used within
the Jinja2 code
"""
return "Not what you asked for" | 3878f805f21f2be3a4b96173f04257308f72bd45 | 52,883 |
def conv_upample(conv, x, occupy, real_num, out_coords, out_occupy, out_stride=1, mul_occupy_after=True):
"""
Add occupancy value for sparse convolution that decreases the stride for input data
"""
if occupy.ndim < 2:
occupy = occupy.unsqueeze(1)
if conv.kernel.ndim < 3:
conv.kerne... | 84b21d16fe3105dd6b1c8cc191b1a1a9303fc1f7 | 52,884 |
def get_field_node(field_config: dict, config: dict, source=None) -> object:
"""
get field node.
"""
required = field_config.get(FIELD_REQUIRED, False)
field_type, field_attrs = tuple(field_config[FIELD_TYPE].items())[0][0], tuple(
field_config[FIELD_TYPE].items())[0][1]
if field_type ==... | 431b43032fa77823860aa697df776d4539628615 | 52,885 |
from typing import Optional
def subcycles() -> Parser:
"""Return a parser to parse the <subcycles> tag.
:return:
A parser that consumes the <subcycles> tag and produces an
:class:`rads.config.ast.Assignment` AST node which assigns to
"subcycles" a :class:`rads.config.tree.SubCycles` d... | 50d79b8424b1ec082f12cf8af4f295f057294aeb | 52,886 |
from gtmcore.container.local_container import LocalProjectContainer
from gtmcore.container.hub_container import HubProjectContainer
from typing import Optional
def container_for_context(username: str, labbook: Optional[LabBook] = None, path: Optional[str] = None,
override_image_name: Optiona... | 792b2111de209e7a11900eae513e839677ad8f82 | 52,887 |
import re
def suggest(term):
"""
Find most appropriate EFO term for arbitrary string
Arg:
* string
Returntype: string (EFO ID)
"""
server = 'http://www.ebi.ac.uk/spot/zooma/v2/api'
url_term = re.sub(" ", "%20", re.sub("[%&]", "", term))
ext = "/services/annotate?propertyValue=%s&filter=required:[none],... | 4673c1fc715cc77bfb0db8b877174c5be6e6af51 | 52,888 |
import numpy
def plot_matplotlib_dgt(func, **kwargs):
"""
Plot scalar discontinuous Galerkin Trace functions in 2D
"""
# Get information about the underlying function space
function_space = func.function_space()
family = func.ufl_element().family()
mesh = function_space.mesh()
ndim = m... | e581b761614ba99424d0933a1f4b4d124921e44d | 52,889 |
from typing import Callable
from typing import Awaitable
def mapi_async(mapper: Callable[[TSource, int], Awaitable[TResult]]) -> Projection[TSource, TResult]:
"""Map with index async.
Returns an observable sequence whose elements are the result of
invoking the async mapper function by incorporating the e... | 86c2f1ea0a20b04dab24246a92dda87e29ed4ead | 52,890 |
def descriptors_to_file(config_filepath: str, descriptors: kapture.Descriptors) -> None:
"""
Writes descriptors to CSV file.
:param config_filepath:
:param descriptors:
"""
return image_feature_to_file(config_filepath, descriptors) | cfbfa147893681672666cd09a1b94574893a9798 | 52,891 |
def get_activation_function(label: str) -> ActivationFunction:
"""Get activation function by label
:param label: string denoting function
:return: callable function
"""
if label == 'lin':
return Linear()
if label == 'sigmoid':
return Sigmoid()
if label == 'tanh':
ret... | d143734f0e2713fbc6e660467d1256afd876a681 | 52,893 |
def Detector_List(scanIOC):
"""
Define the detector used for:
keithley_live_strseq()
Detector_Triggers_StrSeq()
BeforeScan_StrSeq() => puts everybody in passive
CA_Average()
WARNING: can't have more than 5 otherwise keithley_live_strseq gets angry.
"""
BL_mode=BL_Mod... | c2303314fb556e504540ccd2f2f0af0c9c2590b2 | 52,894 |
import torch
def _instance_accuracy(label, raw_pred, compare_func, return_float=True, feed_dict=None, args=None):
"""get instance-wise accuracy for structured prediction task instead of pointwise task"""
# disctretize output predictions
if not args.task_is_sudoku:
pred = as_tensor(raw_pred)
... | 51831f2160a0eec6fbec4e7d8992009b3fff7811 | 52,895 |
import html
def get_stressors(lat,lon):
"""
Example for looking up stressors at a particular location.
"""
# Note df is a flattened list of lat/lon values that only includes those over land
df = pvcz.get_pvcz_data()
# Point of interest specified by lat/lon coordinates.
lat_poi = float(l... | 34718b197d265c98d2d3e0a30d041af6e8b1e44e | 52,896 |
def load_and_prepare_image(filename, img_shape=224, rescale=True):
"""
Preparing an image for image prediction task.
Reads and reshapes the tensor into needed shape (img_shape, img_shape, 3).
Image tensor is rescaled.
:param filename (str): full-path filename of the image
:param img_shape (int):... | e666dc909dbc0411c009ca791d1ee2aacf9d32c1 | 52,897 |
def jacobi_recr_coeffs(n, alpha, beta):
"""calculate the coefficients used in recursion relationship
Args:
n: the targeting order
alpha: the alpha coefficient of Jacobi polynomial
beta: the veta coefficient of Jacobi polynomial
Returns:
a1, a2, a3, a4: the coefficients used... | f9beb604af7b82fad8e0a81beed6852ea007cd30 | 52,898 |
def get_key(window, key):
"""
Returns the last reported state of a keyboard key for the specified
window.
Wrapper for:
int glfwGetKey(GLFWwindow* window, int key);
"""
return _glfw.glfwGetKey(window, key) | b3b1b699d766ae9054278bcc85654c35cd9b3241 | 52,899 |
def service_unavailable(request,template_name='503.html'):
"""
Default service unavailable view
"""
return TemplateResponse(request,template_name,status=503) | e474d5780bff381a6365fe9c8e28416c7a689708 | 52,900 |
from datetime import datetime
def utcnow_str():
""" Return a new datetime string representing UTC day and time. """
return time2str(datetime.datetime.utcnow()) | 1008efc7536880a389913f5dd3a03c157323dc2a | 52,901 |
def accuracy(output, target, topk=(1,)):
"""
Computes the precision@k for the specified values of k
Parameters
----------
output : pytorch tensor
output, e.g., predicted value
target : pytorch tensor
label
topk : tuple
specify top1 and top5
Returns
-------
... | 018d19d70084c9e1f4f5269f4cf6c444a41e016b | 52,902 |
def compute_divide(z, w):
"""
Compute `z` divided by `w`.
:param z: MathsComplexNumber object to be divided.
:param w: MathsComplexNumber object to divide by.
:return: MathsComplexNumber object of `z` divided by `w`.
"""
# z = a + bj
# w = c + dj
a, b = z.re, z.im
c, d = w.re,... | 0740446226dbc52273c7dcdc0e7c1cf1deb8df70 | 52,903 |
import six
def _build_deeplab(inputs_queue, outputs_to_num_classes, ignore_label):
"""Builds a clone of DeepLab.
Args:
inputs_queue: A prefetch queue for images and labels.
outputs_to_num_classes: A map from output type to the number of classes.
For example, for the task of semantic segmentation wi... | 5ff0a26a68355eff7a940534c79a8edcb39fe981 | 52,904 |
from datetime import datetime
def clean_up():
"""Clean up the cache.
Finish introspection for timed out nodes.
:return: list of timed out node UUID's
"""
timeout = CONF.timeout
if timeout <= 0:
return []
threshold = timeutils.utcnow() - datetime.timedelta(seconds=timeout)
uui... | d22423d9e9eb8d06e4f9887b9f4ee0a395e9a51d | 52,905 |
from typing import Type
from typing import Sequence
from textwrap import dedent
def create_triggers_sql(*, audit_logged_model: Type[Model]) -> Sequence[str]:
"""
Create the SQL requried to set up triggers for audit logging to the given
audit log entry model.
"""
# Get the model that we are audit ... | 3b5b5e3e236adb06f6f30961adb7ee4da5ad6d30 | 52,906 |
def _get_neighbors(loc, image, voxels, thresh, dist_params):
"""Find all the neighbors above a threshold near a voxel."""
neighbors = set()
for axis in range(len(loc)):
for i in (-1, 1):
next_loc = np.array(loc)
next_loc[axis] += i
if thresh is not None:
... | e7e1e7e7509609a40803fff0816d30a056824395 | 52,907 |
def is_partition(set_of_sets, alphabet):
"""
Determine whether `set_of_sets` partitions `alphabet`; that is,
is every element of `alphabet` represented exactly once in `set_of_sets`?
Parameters
----------
set_of_sets : a (frozen)set of (frozen)sets
The potential partition.
alphabet ... | dab446b6f9beefe4acc5c400f71749352ab81b46 | 52,908 |
def OMO(
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 = "2020-06-08", **kwargs
) -> Graph:
"""Ret... | c9e37f025788e8c1a2630e9ba9b7ee8f542f34dc | 52,909 |
def _render_dimensional_metric_cell(row_data: pd.Series, metric: Metric):
"""
Renders a table cell in a metric column for pivoted tables where there are two or more dimensions. This function
is recursive to traverse multi-dimensional indices.
:param row_data:
A series containing the value for t... | 36dce77d07b6581d0bf120f55f4bc3e1813c3deb | 52,910 |
def allocationsCount(memory):
"""Return the total number of allocations.
"""
return np.count_nonzero(memory['allocations'] > 0) | 171374eb60cc63f56c54b667eaadaa43cc611b38 | 52,912 |
def _get_annotation_type(annotation) -> AnnotationType:
"""
Returns the type of a given annotation.
Annotation can be a BinaryBuffer, TypedBuffer or something else
"""
if isinstance(annotation, list):
if len(annotation) == 2:
return AnnotationType.BINARY_BUFFER
elif len... | 1b499a6137d7378661b521bbc94ed574994a3c9d | 52,915 |
import ast
def is_obvious_builtin(node, value):
# type: (ast.expr, Any) -> bool
"""
Return True if this node looks like a builtin and it really is
(i.e. hasn't been shadowed).
"""
return ((isinstance(node, ast.Name) and
node.id in builtins_dict and
builtins_dict[node.... | 8a404b5cc84a6ea19edf60e3211497002426ede6 | 52,916 |
def insert_records(conta, data):
"""
Recebe o objeto e inseri a data no banco de dados. A data são os logs de exibições recebidos do manager.
param: conta : Account:
data: list of dicts:
return: records: int: Quantidade de registros inseridos
"""
records = 0
i = len(data) - 1
... | a136fd7bda8d0c32deb45290661574735d9faf2f | 52,918 |
def sample_2d_no_compete(alternatives, choosers, sample_size, capacities=None):
"""
Samples alternatives in a manner that guarantees that capacities will
be respected: the maximum # of times a given alternative can appear
in the sample (across choosers) is equal to its capacity.
Use this for the la... | d96dd35c7c03ddb39784c91bd8efc989c5226f26 | 52,919 |
from typing import Sequence
def notch_filter():
""" implements a notch filter with notches at 1/week and 2/week; assuming input signal sampling rate is 1/week"""
fs, f0, Q = 1, 1/7, 1
b1, a1 = iirnotch(f0, Q, fs)
b2, a2 = iirnotch(2*f0, 2*Q, fs)
# Frequency response
b = convolve(b1, b2)
a ... | 1a7162d24124c177e1ec8b76bb0d424a8a3ccbb4 | 52,920 |
def monthly_file_name(var, model, rcp):
"""Function for creating file connections for different variables
scenarios and models. Preasently, ensemble member r1i1p1 is assumed, as
well as 200601-210012 dime span for the monthly data."""
# e.g. hfls_Amon_CNRM-CM5_rcp85_r1i1p1_200601-210012.nc
f = var + "_" + "Amon_... | 7aeea6d3724c470e076645ddb96877e9fa15843f | 52,921 |
def extract_sum_of_products(cluster, template, *args):
"""
Extract sub-expressions in sum-of-product form, and assign them to temporaries.
"""
make = lambda: Scalar(name=template(), dtype=cluster.dtype).indexify()
rule = q_sum_of_product
costmodel = lambda e: not (q_leaf(e) or q_terminalop(e))
... | b5eab74b889dfdf528677170fe0c5b0c5828e4d1 | 52,922 |
def minimize(_mol, nsteps, opttol, func, minimizer):
""" Minimizes a single molecule
Arguments:
nstesp -- perform a maximum of nsteps steps
opttol -- the maximum rms gradient shall be below this value
func -- energy and gradient function
minimizer -- a minimizer
"""
... | e465c415066c0619a7fbc84656e32eeddf21ac8e | 52,923 |
import requests
def request(method, url, **kwargs):
"""
Central place to make any v1 api request.
:param (str) method: The request method ('get', 'put', 'delete', ...).
:param (str) url: The full api url to make the request to.
:param kwargs: These are passed along to requests.
:return: (requ... | ca3bc5e5607d1b3dbebcfa92c8532dee9ab2b673 | 52,925 |
from typing import Callable
import cloudpickle
def default_key_provider(func: Callable, *args, **kwargs) -> str:
"""
Default cache key function. This uses cloudpickle to hash the function and all arguments.
"""
return cloudpickle.dumps({"function": func, "args": args, "kwargs": kwargs}) | 693129568a45270d48c1cedb6995d07abd875715 | 52,927 |
import warnings
def fips_to_location_id(fips: str) -> str:
"""Converts a FIPS code to a location_id"""
try:
return dataset_utils.get_fips_to_location().at[fips]
except KeyError:
# This happens mostly (entirely?) in unittest data where the first two digits
# are not a valid state FI... | d1478f36a39534a22860b8382fc4808cd0deedff | 52,928 |
from datetime import datetime
import pytz
def check_asset_availability(start=None, end=None):
"""
Am I within the Asset's availablity window?
If "start" is defined, now >= start must be True
If "end" is defined, now <= end must be True.
Otherwise each condition is presumed TRUE
(e.g., n... | 12c2480c51c8656f46b905f454620c73c826a6f5 | 52,929 |
def calc_distance(l):
"""Calculates distance between list items in two lists"""
# l needs to start from zero, get lowest number and substract it from all numbers
min_l = min([x[1] for x in l if x[1] != ''], default=0)
l = [[x[0], (x[1] - min_l)] for x in l if x[1] != '']
distance = 0
for id... | 57d52eb4bb4b772024d68cb397f2e315825a25df | 52,930 |
def load_archive(task_name: str, hparam_set_name: str):
"""Load a precomputed archive file for `task_name` and `hparam_set_name`."""
path = get_baseline_archive_path(task_name, hparam_set_name)
return read_npz(path) | 69cf98f9e7193bb60aa8a5c17e9574289c73e7c4 | 52,931 |
import torch
from typing import Tuple
def get_explanation_accuracy(model:torch.nn.Module,loader:torch.utils.data.DataLoader,mem_loader:torch.utils.data.DataLoader,device:torch.device)-> Tuple[float, float, float]:
""" Method to compute the explanation accuracy for different settings, as
described in the paper... | 2c90a5df55925016c85b6c494cee0279cddfdb41 | 52,933 |
import locale
import warnings
def locale_convert(key):
"""Creates a converter for a locale key."""
def lc_converter(val):
try:
locale.setlocale(LOCALE_CATS[key], val)
val = locale.setlocale(LOCALE_CATS[key])
except (locale.Error, KeyError):
msg = 'Failed to ... | 54f45d2290c47e9773a269f9cd3e65ebce8a233d | 52,934 |
from datetime import datetime
def get_offer_info(soup, offer_id):
"""get information about a specific offer according to its id
information: title, company name, published date, link
Parameters
----------
soup: BeautifulSoup
html code
offer_id: str
offer identifier
Retur... | 516c555a86e40e2b9e45e05a7994e39c5ae9ae23 | 52,935 |
def to_csv(raw_data):
"""Converts a serialized TfStatsDatabase string to CSV."""
tf_stats_db = tf_stats_pb2.TfStatsDatabase()
tf_stats_db.ParseFromString(raw_data)
return generate_chart_table(tf_stats_db.with_idle,
tf_stats_db.device_type).ToCsv() | eecd980878849ec5853662fe647cb9dbe3ec98a3 | 52,936 |
def lam(x, lam0, alpha=4.0):
"""Return classic alpha model lambda value(s) for input value(s)."""
return lam0 * ( 1.0 - x**alpha ) | 37a10d890acc2b983c09300b865e58fe9dc2f7fe | 52,937 |
def Add(left: Expr, right: Expr) -> BinaryExpr:
"""Add two numbers.
Produces left + right.
Args:
left: Must evaluate to uint64.
right: Must evaluate to uint64.
"""
return BinaryExpr(Op.add, TealType.uint64, TealType.uint64, left, right) | 27ba874d66b57669f6ec332e86530f40b022a637 | 52,938 |
def reduceCoefficients(polynomial : Polynomial) -> Polynomial:
"""
Initialize a Polynomial for the Kerner method:
Make the leading coefficient 1
"""
eq = polynomial.eq()
h_coeff = eq.get(max(eq))
return Polynomial([
coefficient / h_coeff for coefficient in polynomial.arr()
... | d31c538801c3a7472eb6e52b17421b783f239a0f | 52,939 |
def count():
"""
查询记录总数
"""
return Record.objects.owner().count() | 0e4466da6c3a4c1f549bcdbafa0b76233daa4a40 | 52,940 |
def subset(part, whole):
"""Test whether `part` is a subset of `whole`.
Both must be iterable. Note consumable iterables will be consumed
by the test!
This is a convenience function.
Examples::
assert subset([1, 2, 3], [1, 2, 3, 4, 5])
assert subset({"cat"}, {"cat", "lynx"})
... | 4200ea95e0c9ff03d0b7589812d0313c5d13cfac | 52,943 |
def kl_categorical_uniform(preds):
"""KL divergence between categorical distribution and uniform prior."""
kl_div = preds * jnp.log(preds + EPS) # Constant term omitted.
return kl_div.sum(1) | 311cae987a9e43742d036fe9b23f37654987264f | 52,944 |
def remove_proxy_vcs(session, quantity, return_type=None, **kwargs):
"""
Removes proxy vcs.
:type session: zadarapy.session.Session
:param session: A valid zadarapy.session.Session object. Required.
:type quantity: int
:param quantity: The number of vcs to be removed. Required.
:type re... | 2d5e05f338e0414e0ed5fe6c5eb567aaf8f01f9f | 52,945 |
from pathlib import Path
def stem(fname, include_suffix=False):
"""/blah/my_file.json.gz --> my_file"""
path = Path(fname)
stem = path.stem
# If a filename has multiple suffixes, take them all off.
stem = stem[: stem.index(".")] if "." in stem else stem
if include_suffix:
stem = stem... | 9e4c557dff8583f9129215f91f8e123f062ccf52 | 52,946 |
def compile(fmt, names=None):
"""Compile given format string `fmt` and return a compiled format
object that can be used to pack and/or unpack data multiple times.
Returns a :class:`~bitstruct.CompiledFormat` object if `names` is
``None``, and otherwise a :class:`~bitstruct.CompiledFormatDict`
objec... | 00c4596739e65295b579002917ddfbaee6a7390b | 52,947 |
import sqlite3
def username_lookup(userName):
""" Lookup user from availability.db by unique username """
# connect to db
conn = sqlite3.connect("availability.db")
# create cursor
c = conn.cursor()
# check if lookup initiated for specific user or for all users
if userName:
# quer... | 36c0927a79791eca8d69f574799490c716f2fe05 | 52,948 |
def allInfoTests(P, inIter=10, outIter=10):
"""
performs information theoretic tests on a tripartite behaviour
"""
results = []
# get marginal for X,Y
l = len(P.shape)
t = tuple(np.arange(2,l))
m = pr.marginal(P, t)
# calculate mutual information of the marginal X,Y
mutInf =... | ecf3f2a2e2fd2ba29847e6ae5d883aced5a1f8df | 52,949 |
def Insert(head, data):
"""
>>> head = None
>>> node = Insert(head, 4)
>>> assert(node.data == 4)
>>> head = Node(6)
>>> node = Insert(head, 4)
>>> assert(node.next.data == 4)
>>> head = Node(6, Node(7))
>>> node = Insert(head, 4)
>>> assert(node.next.next.data == 4)
"""
... | 3372a20ba7a9b6e80b07fadedce9bfb12baed4e9 | 52,950 |
def important_features(model):
""" Get the most important features from some model """
invalid_features = ["count_","tf_idf_","word2vec_"]
feat_importances = pd.Series(model.feature_importances_, index=features).to_string()
feat_importances = [i for i in feat_importances if not any(feat in i for feat i... | 22880b50b83f08c224f1e1bd0cc7032f2b6ccd0b | 52,951 |
def get_backend(config):
"""
:param app: celery instance
:type app: celery.Celery
"""
klass = config.backend_class
kwargs = config.backend_kwargs
url = config.backend_url
return klass(url, **kwargs) | 57d6c82f99888ae992503492a8edfa802315a3cc | 52,952 |
def affine(f, T):
"""Applies the affine transformation on a given
image.
' g(r, c) = f(T^{-1}(r,c)) '
Direct mapping:
From image (f) map the values to image (g)
- g(T(r,c)) = f((r,c)) ,
(r,c) in [0,H-1]x[0, W-1]
- con: T(r,c) might not fill every pixel of G
Indirect Mapping
... | 593617f5296361ac7d797e2f804eb12dea347e1c | 52,953 |
def atol(s, base=None): # real signature unknown; restored from __doc__
"""
atol(s [,base]) -> long
Return the long integer represented by the string s in the
given base, which defaults to 10. The string s must consist
of one or more digits, possibly preceded by a sign. If base
is 0, it i... | f39aa403cbad98c448a35305c97c595bc3a77c02 | 52,954 |
def open_or_std(file, std, *args, **kwargs):
"""
Opens the file in the specified mode unless file is STD_IDENTIFIER,
in which case it returns std.
"""
if file == STD_IDENTIFIER:
return std
return open(file, *args, **kwargs) | dd8b08569ff6ee702864fe453e13d3e8f7497267 | 52,955 |
from typing import Tuple
from typing import Optional
def translate(
parsed_symbol_table: parse.SymbolTable,
atok: asttokens.ASTTokens,
) -> Tuple[Optional[SymbolTable], Optional[Error]]:
"""Translate the parsed symbols into intermediate symbols."""
underlying_errors = [] # type: List[Error]
def ... | 7e293389b51fdc9f05ef047c82bd5a0362cb3c01 | 52,956 |
def tokens_to_sovatoms(tokens: float) -> int:
"""Convert tokens to sovatoms."""
return int(tokens * 100000000) | 23f4bc3a1afc4520b5e2416332702d0a594c5039 | 52,957 |
def _frame_only(frame, skeleton_data):
"""
Save only one frame from skeleton data
"""
result = []
for raw_descriptor in skeleton_data:
if raw_descriptor[0] == frame:
result.append(raw_descriptor)
return result | 1581ddc52eedc81dbe2cc71ed66524b6af5f4b3d | 52,958 |
def sort_node_id(a, b):
"""
@param a, b: node pair to be sorted by id
@type treenode, treenode
"""
if a.id > b.id:
return 1
else:
return -1 | 2db33f63f009d4d50c922b4daf45dbac56a60312 | 52,959 |
def generate_steps(model_name, new_steps, generator='random(edge_coverage(100))'):
"""
This is the top level builder for making test steps.
Args:
model_name (str): The name of the model file - no extension needed.
new_steps (bool): Whether to recalculate the model steps.
generator (... | c825ea6fe81a9bdfe436a7382b564729fae585d7 | 52,960 |
def collect_trajectories(env,
policy_fun,
num_trajectories=1,
policy=env_problem_utils.CATEGORICAL_SAMPLING,
max_timestep=None,
boundary=20,
epsilon=0.1,
... | 77af43962dec2ba236ceb7a33fbcbc51b410a9dc | 52,961 |
from datetime import datetime
def request_directions(start_location, end_location):
"""Request directions from start_location to end_location.
Args:
start_location: tuple of floats (lat, lon) for starting point
end_location: tuple of floats (lat, lon) for ending point
Returns:
a list of directions ... | a4e2208f18fb885d083f28aafcb2e48529b9e3fe | 52,962 |
def __Boundary_outside__(self):
"""Is the boundary is on the outside of the mesh."""
return self.leftCell() is not None and self.rightCell() is None | cce3ffadc5e2598beae8b320b4d2f5122d6de904 | 52,963 |
def create_dataset_lookup(py_obj):
""" What type of object are we trying to pickle? This is a python
dictionary based equivalent of a case statement. It returns the correct
helper function for a given data type.
Args:
py_obj: python object to look-up what function to use to dump to disk
... | 0a36c178c6ceccafe35f1023cbfe6eb293ad0ba3 | 52,964 |
def find_anagrams(s):
"""
:param s: search str
:return: a list of anagrams
"""
print('Searching...')
return find_anagrams_helper(s, '', []) | f636200d611d0a38a8cdfc8802f611a0fb6073b1 | 52,965 |
from typing import List
def follow_directions(start: Cell, directions: List[Direction]) -> Cell:
"""
Walk the ``directions`` from the ``start``.
:return: The final :py:class:`Cell` of the journey
"""
cursor = start
for direction in directions:
cursor = next_cell(cell=cursor, direction... | 4409a7ba6a2edf53e0f9aaeb2cbf90e96e72c5e5 | 52,966 |
def mongo_dump(server, args_array, **kwargs):
"""Method: mongo_dump
Description: Function stub holder for mongo_db_dump.mongo_dump.
Arguments:
(input) server -> Server instance.
(input) args_array -> Dictionary of arguments.
"""
status = False
err_msg = None
if server... | 895ad2d77282d1d5c65c54940a4f83b64023f92d | 52,967 |
def majority(taxa, th=0.8):
"""Select taxon from list by majority rule.
Parameters
----------
taxa : list of str
Input taxon list.
th : float, optional
Threshold of majority, range = (0.5, 1.0].
Returns
-------
str or None
Selected taxon.
"""
for taxon, ... | 0828b8704aeb1f7ced1446b563ba4f1f98634ffe | 52,968 |
from .matplotlib import plot_roc_curve as _plot_roc_curve
from .plotly import plot_roc_curve as _plot_roc_curve
def plot_roc_curve(fpr, tpr, roc_auc=None, backend="plotly", **kwargs):
"""Plots a receiver operating characteristic (ROC) curve.
Args:
fpr: an array of false postive rates
tpr: an ... | d4bcfe3d37478602a9a80435c5aa979fcb2143cc | 52,970 |
def send(draw, min_value=0, max_value=None):
"""Generates the send for Blast+6 file format.
Arguments:
- `min_value`: Minimum value of send to generate.
- `max_value`: Maximum value of send to generate.
"""
return draw(integers(min_value=min_value, max_value=max_value)) | 6b6cd9d5965cb3e114c61aeff76dca1bc3149d64 | 52,971 |
def flow_cell_mode(info_reads):
"""Return flow cell sequencing mode."""
res = ''
if info_reads:
read_lens = [
a['num_cycles'] for a in info_reads if not a['is_indexed_read']]
if len(read_lens) == 1:
res = '1x{}'.format(read_lens[0])
elif len(set(read_lens)) ==... | 0563d0c163c2bd42b05d07fb30940669a8ef3513 | 52,972 |
def dynamic_module_wrapper(wrapped_module: nn.Module):
"""
Wrapped module must locate on one single device, but could be moved around.
Input device and output device are automatically detected.
"""
wrapper = NeuralNetworkModule()
wrapper.add_module("wrapped_module", wrapped_module)
wrapper.... | 963200ae5abf305deb08b2e3a2b78e58d068ff75 | 52,973 |
def fixture_conf2():
"""Instance of loaded config_test2.ini."""
return md.FrontMatter("./tests/config_test2.ini") | 34b78a4a23fc253dea014152a3f20ec3a1c535ce | 52,974 |
import pycountry
import urllib
import requests
import json
def find_best_match(row, scopus_url):
"""Splits the name and surnames and tries to find some combination
of them, that still matches the country."""
# Prepare the parameters
csv_name = row['firstName'].replace(",","").replace(" or ", " ")
... | 42d9b2cd4a9cc2544337cad3e211a1d9bd3ab6d7 | 52,975 |
def git_get_tags_by_referred_object(context: RepoContext, obj_name: str) -> list:
"""
:param context:
:param obj_name:
:rtype: list of Ref
"""
commit_tags = git_get_tag_map(context).get(obj_name)
return commit_tags if commit_tags is not None else [] | 59211ed55db6b446caae2c5ecade7bc956c2cb92 | 52,977 |
def sortKey(e):
"""
This sorts the chores based on their start time.
e[0] is the start time for all the chores in my array of chores.
"""
return int(e[0]) | 00d37751d23fe6210b406485cbd76906075b2578 | 52,978 |
def merge_into_dict(original, secondary):
"""Merge two dictionaries into the first and return it.
This is simply a conveinence wrapper around the dictionary update method. In
addition to the update it returns the original dict to allow for chaining.
Args:
original: The dict which will be updated.
seco... | 899d40396885f0775f2cbaa865702ed0e5706dba | 52,979 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.