content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def stackplot(data, add, xlabel='', ylabel='', cmap='Spectral',
figsize=(3, 4.5), lw=1, plot=True):
"""
Plots a stack plot of selected spectras.
:type data: list[float]
:param data: Data to in the plot.
:type add: float
:param add: displacement, or difference, between each curve... | 959118905abbfada9d4af3ac0a8ab414b00a9ffe | 3,633,556 |
import torch
def batch_detect(net, img_batch, device):
"""
Inputs:
- img_batch: a numpy array of shape (Batch size, Channels, Height, Width)
"""
B, C, H, W = img_batch.shape
orig_size = min(H, W)
# BB, HH, WW = img_batch.shape
# if img_batch
if isinstance(img_batch, torch.Tens... | e20de1e4f3915e2e377e790f7e6cb3df5d76b5cb | 3,633,557 |
def int_to_binary(x, n):
"""Convert an integer into its binary representation
Args:
x (int): input integer
n (int): number of leading zeros to display
Returns:
(str) binary representation
"""
if type(x) != int:
raise ValueError('x must be an integer.')
return f... | c3d68a798f84988290bd4e845a5bcc015872b054 | 3,633,558 |
def convert_examples_to_features(examples,
tokenizer,
max_seq_length,
max_program_length,
is_training,
op_list,
op_list_si... | d7024a0ff97d94a5c2aa32e63230e972584fb1d2 | 3,633,560 |
def negative_mean_successiness(c):
"""Negative mean successiness over the course of the trial."""
if c.needed_control_arm_events.size > 1:
center = float(c.needed_control_arm_events.mean())
width = float(c.needed_control_arm_events.std())
else:
center = float(c.needed_control_arm_events)
width = c... | ac6e07076c422ef524f46583edd41eff48f6733e | 3,633,561 |
def determina_putere(n):
"""
Determina ce putere a lui 2 este prima cea mai mare
decat n
:param (int) n: numarul de IP-uri necesare
citit de la tastatura
:return (int) putere: puterea lui 2 potrivita
"""
putere = 1
while 2**putere < n+2:
putere += 1
return put... | 85e2c1dcd2ea5d86b5db3c6ced28dd65e244c467 | 3,633,562 |
def attribute_rename_cmd(oldattr, newattr):
"""
Rename an attribute.
If it's not present nothing is done, and its value is kept.
That's it.
$ cjio myfile.city.json attribute_rename oldAttr newAttr info
"""
def processor(cm):
utils.print_cmd_status('Rename attribute: "%s" =>... | b48e0e90bbb75cdf9828e21c115b758250f433e2 | 3,633,563 |
from datetime import datetime
def editItemInCategory(item_id):
""" Edit an item in a given category."""
if 'username' not in login_session:
sMsg = "You are not authorized to perform this '%s' " % ('edit item category')
sMsg += "action because you are not logged in. You are being redirected to login."
flash... | ed2f51eea2713271f82440599edd90f015820b24 | 3,633,564 |
def factorial(n, show=False):
"""
-> Calcula o Fatorial de um número.
:param n: O número a ser calculado.
:param show: (opcional) Mostra ou não a conta.
:return: O valor do Fatorial de um número n.
"""
f = 1
for c in range(n, 0, -1):
if show:
print(c, end='')
... | 4e2928b2e2b197e40aacd8ec1b18c9afee42e229 | 3,633,565 |
def parse_commands(log_content):
"""
parse cwl commands from the line-by-line generator of log file content and
returns the commands as a list of command line lists, each corresponding to a step run.
"""
command_list = []
command = []
in_command = False
line = next(log_content)
wh... | dff555cd0ec84619425fc05e4c8892c603bcc994 | 3,633,566 |
from datetime import datetime
import ssl
import logging
import time
def wait_for_operation(client,
project,
op_id,
timeout=datetime.timedelta(hours=1),
polling_interval=datetime.timedelta(seconds=5),
sta... | a7487beda110d1b5d52d8073d58fb6a33b0997a2 | 3,633,567 |
def bij_connected_comps(components):
"""Set of connected planar graphs (possibly derived) to nx.PlanarEmbedding."""
res = nx.PlanarEmbedding()
for g in components:
g = g.underive_all()
g = g.to_planar_embedding()
res = nx.PlanarEmbedding(nx.compose(res, g))
return res | 7f705f25756e114c91bbff9a09880d5bfb8d37ee | 3,633,569 |
from typing import Tuple
def render_responses(intent: Intent, language_data: IntentLanguageData) -> Tuple[IntentResponseDict, str]:
"""
Return a copy of responses in `language_data` where intent parameter references are
replaced with their values from the given :class:`Intent` instance.
Args:
... | 4e83d1b75b25d8e3ab7d030890744f0081c02c10 | 3,633,570 |
def cropseq(indexes, l, stride):
"""generate chunked silencer sequence according to loaded index"""
print('Generating silencer samples with length {} bps...'.format(l))
silencers = list()
i = 0
for index in indexes:
try:
[sampleid, chrkey, startpos, endpos, _] = index
exc... | 09bac76a6209398cdb5cb230be7aa18f5f895204 | 3,633,572 |
import tqdm
def generate_claims(model, gen_dset, dl, tokenizer, device):
"""
Run generation using the given model on the given dataset
:param model: BART model to use for generation
:param gen_dset: The original dataset
:param dl: A dataloader to use for generation
:param tokenizer: A tokenize... | 0f042101ca6c864249c62e1934a9c58f0b21f9e7 | 3,633,573 |
def to_geojson(series):
"""Return a GeoJSON geometry collection from the series (must be in EPSG:4326).
Did not use the builtin for the series since it introduces a lot of bloat.
"""
return {
"type": "GeometryCollection",
"geometries": series.apply(lambda x: x.__geo_interface__).to_list... | 2ebdc001ed7a6fb3ee6e6cac9fc7722e19518e20 | 3,633,574 |
import copy
async def copy_context(ctx: commands.Context, *, author=None, channel=None, **kwargs):
"""
Returns a new Context with changed message properties.
"""
# copy the message and update the attributes
alt_message: discord.Message = copy.copy(ctx.message)
alt_message._update(kwargs)
... | 78a82922a7740cfcdad0e17a0f85a16ee53a068e | 3,633,576 |
def getConstraintWeightAttr(leader, constraint):
"""
Return the weight attribute from a constraint that
corresponds to a specific leader node.
Args:
leader (PyNode): A node that is one of the leaders of a constraint
constraint (PyNode): A constraint node
"""
for i, target in enu... | e53ef981f505f1c8fc21fff7b71605764d6da3e0 | 3,633,577 |
def approximate_mds(dists):
"""Approximate multidimensional scaling (MDS)
Estimate the inter-node distance matrix from source node distances as
described in "Iterative Geometry Calibration from Distance Estimates for
Wireless Acoustic Sensor Networks" (https://arxiv.org/abs/2012.06142).
Subsequentl... | 6f2aef5e71c439990840143089fa9cc941a81c2c | 3,633,579 |
def build_resnet_fpnindi_backbone(cfg, input_shape: ShapeSpec):
"""
Args:
cfg: a detectron2 CfgNode
Returns:
backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`.
"""
bottom_up = build_resnet_backbone(cfg, input_shape)
in_features = cfg.MODEL.FPN.IN_FEAT... | 40329cfb0d414305e7d38966b41e352cc44c6535 | 3,633,580 |
from typing import Tuple
from typing import Any
def _get_min_max_outputs(node: BaseNode,
fw_info: FrameworkInfo) -> Tuple[Any, Any]:
"""
Return the min/max output values of a node if known.
If one of them (or both of them) is unknown - return None instead of a value.
Args:
... | c43992c9b2cd64b9970766fe06d6d0c6af3a6954 | 3,633,581 |
def remove_stop_words(document):
"""Returns document without stop words"""
document = ' '.join([i for i in document.split() if i not in stop])
return document | c4385790901f09eadeac67dc1035a12bedf8cb45 | 3,633,582 |
def Ion_Flux_Relabeling(h,q):
"""
Oh no! Commander Lambda's latest experiment to improve the efficiency of her LAMBCHOP
doomsday device has backfired spectacularly. She had been improving the structure of
the ion flux converter tree, but something went terribly wrong and the flux chains
exploded. ... | 8d8694722c8a8d6dcf4aabad3d677fb059d252d9 | 3,633,583 |
def process_line(line, previous_state):
"""
Read line, split it before opening brackets if not in quotes nor escaped
and add '\n' in the end of new lines.
"""
# opening bracket and/or quote can start in other line
brackets = previous_state.brackets
in_quotes = pr... | 24b997f61263563a67f58a65f2e070c1b21ee478 | 3,633,584 |
def parse_tape6(tape6="TAPE6.OUT"):
"""Parses an ORIGEN 2.2 TAPE6.OUT file.
Parameters
----------
tape6 : str or file-like object
Path or file to read the tape6 file from.
Returns
-------
results : dict
Dictionary of parsed values.
Warnings
--------
This method... | 5082ee35ce8198db680c0b7be86d703c4c349402 | 3,633,585 |
def property_values_to_string(pv,extra_indentation = 0):
"""
Parameters
----------
pv : OrderedDict
Keys are properties, values are values
"""
# Max length
keys = pv[::2]
values = pv[1::2]
values = ['"%s"' %x if isinstance(x,_Quotes) else x for x in values]
key_lengths... | 0a8f5b188f74d1779c871a843eb7394631162fc4 | 3,633,586 |
def parse_cmdline():
"""parse command line arguments"""
parser = ArgumentParser(
description="dtbTool version " + str(QCDT_VERSION))
parser.add_argument("input_dir",
help="Input directory")
parser.add_argument("-o", "--output-file", type=FileType('wb'), required=True,
... | 4f2cf506c4463b19859403de0aac0707d4ad5050 | 3,633,587 |
def __build_vocab(nlp, datasets):
"""
Generates the encoder vocabulary (natural language tokens),
decoder vocabulary (programming language tokens) and stack
vocabulary (terminal and non-terminal symbols, tokens) by
parsing each source and target example in each split.
:param nlp: nl pro... | d162169874a1f82779641615658aa5be52aafb81 | 3,633,588 |
from typing import Optional
from typing import Dict
def get_profile(key: str) -> Optional[Dict]:
"""Fetch user profile.
Arguments:
---------
key: User's database key.
Returns:
---------
Profile dictionary if exists else None.
"""
return BASE_PROFILE.get(key=key) | 0bf1d86707b14735afb6b832d41b63a25650985e | 3,633,590 |
def rectangle_centered(
w: int = 1, h: int = 1, x: None = None, y: None = None, layer: int = 0
) -> Component:
""" a rectangle size (x, y) in layer
bad naming with x and y. Replaced with w and h. Keeping x and y
for now for backwards compatibility
.. plot::
:include-source:
imp... | a61c07a87c6b1a6d347ddc104863657eafd305ad | 3,633,591 |
from datetime import datetime
def sched_time_to_dt(timeStr, targetDate):
"""Converts a GTFS schedule time string to a datetime
Note that a GTFS time may be more than 24 hours, in which case
the function removes 24 from the hours part of the time and increases
the date part of the datetime by 1
Args:
t... | 9fb43c4e19d050480649b39f1ac9a79f617338b7 | 3,633,592 |
def get_arxiv_csl(*, arxiv_id):
"""
Generate a CSL Item for an unversioned arXiv identifier
using arXiv's OAI_PMH v2.0 API <https://arxiv.org/help/oa>.
This endpoint does not support versioned `arxiv_id`.
"""
# XML namespace prefixes
ns_oai = "{http://www.openarchives.org/OAI/2.0/}"
ns_a... | 54fcf1df4b6963a95788a1cdf3306d583fe0b8e6 | 3,633,593 |
from typing import Mapping
from typing import Sequence
import math
def _equivalent_data_structures(reference, struct_2):
"""Compare arbitrary data structures for equality.
``reference`` is expected to be the reference data structure. Cannot handle
set like data structures.
"""
if isinstance(refer... | 57ecaa315a1f9a516b4ac2c2528f0f207fffab6f | 3,633,594 |
def _find_line_bounding_boxes(line_segmentation: np.ndarray):
"""Given a line segmentation, find bounding boxes for connected-component regions corresponding to non-0 labels."""
def _find_line_bounding_boxes_in_channel(line_segmentation_channel: np.ndarray) -> np.ndarray:
line_activation_image = cv2.di... | f0a41d5b569601db6eaa4ca061bddbfe6b6c88fa | 3,633,595 |
def split_items(items, num_groups):
"""Splits a list of items into ``num_groups`` groups fairly (i.e. every
item is assigned to exactly one group and no group is more than one item
larger than any other)."""
per_set = len(items) / float(num_groups)
assert per_set >= 1, "At least one set will be empt... | 0e5af3c5d3e394b328bef63b5287bd673fef0241 | 3,633,596 |
from typing import OrderedDict
import json
def generate_tool_flow(tool: GladierBaseTool, modifiers):
"""Generate a flow definition for a Gladier Tool based on the defined ``funcx_functions``.
Accepts modifiers for funcx functions"""
flow_moder = FlowModifiers([tool], modifiers, cls=tool)
flow_states... | 1ae457676ee2bfaa872f237036261bbfbdc644fb | 3,633,597 |
def paralellLines(M,axis=1,labels=(), interactive=True, title="",show=True):
"""
Makes an optionally interactive paralell Lines plot.
M: Matrix to visualise.
axis: Axis of data values to plot. Needs to be either 1 or 0. Defaults to 1.
labels: Labels of the axes to plot.
inte... | a3ff1f1faa0e1704df24aac0024330458b037027 | 3,633,598 |
import types
import pandas
def hpat_pandas_series_dropna(self, axis=0, inplace=False):
"""
Intel Scalable Dataframe Compiler User Guide
********************************************
Pandas API: pandas.Series.dropna
Limitations
-----------
- Parameter ``inplace`` is currently unsupported b... | 9389f3cb90d22435133f04b3c48f761c65eceee3 | 3,633,599 |
def sort_characters(text, alphabet):
"""Counting Sort"""
dim = len(text)
order = [0] * dim
count = {k: 0 for v, k in enumerate(alphabet)}
for char in text:
count[char] += 1
for j in range(1, len(alphabet)):
count[alphabet[j]] += count[alphabet[j-1]]
for i, char in reversed... | 9beb0f28a7f1ffb892e1393522b94f12e873ba66 | 3,633,600 |
def get_rp_throughput_summary(isamAppliance, date, duration, aspect, summary=True, check_mode=False, force=False):
"""
Retrieving a summary of throughput for all Reverse Proxy instances
"""
return isamAppliance.invoke_get("Retrieving a summary of throughput for all Reverse Proxy instances",
... | a559ae507939d8fc29db8ac92fdacda7742ee522 | 3,633,601 |
from typing import Optional
from typing import Union
from typing import Dict
from typing import List
from typing import Tuple
def do_regress(
test_features: np.ndarray,
train_features: np.ndarray,
train_targets: np.ndarray,
nn_count: int = 30,
batch_count: int = 200,
loss_method: str = "mse",
... | 49257c187462cfea362b35b3cb399d2851f4a7e5 | 3,633,602 |
def set_computer_policy(
name, setting, cumulative_rights_assignments=True, adml_language="en-US"
):
"""
Set a single computer policy
Args:
name (str):
The name of the policy to configure
setting (str):
The setting to configure the named policy with
cum... | 708b39564e7e97be8a986981dab3b2eedec5e01f | 3,633,603 |
import requests
def get_api_result(url):
"""
Retrieve JSON data from API via a supplied URL
"""
s = requests.Session()
r = s.get(url)
return r.json() | 933bd000b2e352f950ec86f8b6f1470ff2b0ecbd | 3,633,604 |
from functools import reduce
def lens_compose(big_lens, *smaller_lenses):
"""
Compose many lenses
"""
return reduce(_lens_compose2, smaller_lenses, big_lens) | f1be58ba017235661b5cd08bf38dbdfb3fcdfdd6 | 3,633,605 |
def renew_defs(func: PrimFunc):
"""Re-generate the definition nodes for a TIR, including VarDef, BufferDef.
This pass works as a simple DeepCopy to duplicate a function with different Vars and
Buffers but the same behavior
Parameters
----------
func: PrimFunc
The input function
Ret... | 838ebc2e30e72d6b3a9405980be2843800091cea | 3,633,607 |
def requires_common_raster(method):
"""
A decorator for spectrum methods that require that another spectrum as an input and require it to be sampled on the
same wavelength raster as us.
:param method:
A method belonging to a sub-class of Spectrum.
"""
def wrapper(spectrum, other, *args... | 5ba5fb3c4dca60f730e201fa0a25781f898f5c97 | 3,633,608 |
def k8s_conf_dict(boot_conf, hb_conf):
"""
Generates and returns a dict of the k8s deployment configuration
:param boot_conf: the snaps-boot config dict
:param hb_conf: the adrenaline config dict
:return: dict with one key 'kubernetes' containing the rest of the data
"""
k8s_dict = __generat... | 49d6ee49a7c665f521dde4f9a2cf2d9e10442064 | 3,633,609 |
def autodetect_mode(a, b):
"""
Return a code identifying the mode of operation (single, mixed, inverted mixed and
batch), given a and b. See `ops.modes` for meaning of codes.
:param a: Tensor or SparseTensor.
:param b: Tensor or SparseTensor.
:return: mode of operation as an integer code.
""... | 48d7af7f075113863090380f1823349fc676f9ec | 3,633,610 |
def f_unc(x, k, weight):
"""
similar to the raw function call, but uses unp instead of np for uncertainties calculations.
:return:
"""
term = 1
# calculate the term k^x / x!. Can't do this directly, x! is too large.
for n in range(0, int(x)):
term *= k / (x - n) * unp.exp(-k/int(x))
... | 6f24688bd9c08d7632846b145ef540235da6cd4f | 3,633,611 |
def get_data(n_clients):
"""
Import the dataset via sklearn, shuffle and split train/test.
Return training, target lists for `n_clients` and a holdout test set
"""
print("Loading data")
diabetes = load_diabetes()
y = diabetes.target
X = diabetes.data
# Add constant to emulate interce... | 0459f2ffbeaf1e21780efba9785c96d75a641d93 | 3,633,613 |
def fn(r):
"""
Returns the number of fields based on their radial distance
:param r: radial distance
:return: number of fields at radial distance
"""
return 4 * r + 4 | 5fa4a5e8f2304f907b9dd806281dc77a2152f431 | 3,633,614 |
def do_icon(name, *args, **kwargs):
"""
Render an icon
This template is an interface to the `icon` function from `django_icons`
**Tag name**::
icon
**Parameters**:
name
The name of the icon to be rendered
title
The title attribute for the icon
... | 7b8addf38d056c070af20f447435a67e29a09a8a | 3,633,615 |
def ED_BldGag(ED):
""" Returns the radial position of ElastoDyn blade gages
INPUTS:
- ED: either:
- a filename of a ElastoDyn input file
- an instance of FileCl, as returned by reading the file, ED = weio.read(ED_filename)
OUTPUTS:
- r_gag: The radial positions of the ga... | fa95475218bf35a90790296ce7149a286440a39e | 3,633,616 |
from typing import List
from typing import Dict
def multiclass_confusion_matrix_metrics(
cm: np.ndarray, labels: List[str]
) -> Dict[str, int]:
"""
Create a dictionary of multiple class labels and their TP, TN, FP, FN values
:param cm: Confusion matrix
:param labels: string labels corresponding to... | 4098dfd1e8618b1d9d87f93b924400925e047680 | 3,633,617 |
import textwrap
def is_perf_benchmarks_scheduling_valid(
perf_waterfall_file, outstream):
"""Validates that all existing benchmarks are properly scheduled.
Return: True if all benchmarks are properly scheduled, False otherwise.
"""
scheduled_non_telemetry_tests = get_scheduled_non_telemetry_benchmarks(
... | 732664db5c17b8c7e4474048da6822c0e5ea207a | 3,633,619 |
import base64
def download_link(object_to_download, download_filename, download_link_text):
"""Generates a link from which the user can download object_to_download
Method from https://discuss.streamlit.io/t/heres-a-download-function-that-works-for-dataframes-and-txt/4052
Args: object_to_download ... | 81299651997d0bf41cf0c2e000741e6e5f7ba3d2 | 3,633,620 |
def run_epoch(sess, cost_op, ops, reset, num_unrolls):
"""Runs one optimization epoch."""
sess.run(reset)
for _ in range(num_unrolls):
results = sess.run([cost_op] + ops)
return results[0], results[1:] | 975634b3498d6385b53222a88b8f79b7d3ee4d3d | 3,633,621 |
def transformToUTM(gdf, utm_crs, estimate=True, calculate_sindex=True):
"""Transform GeoDataFrame to UTM coordinate reference system.
Arguments
---------
gdf : :py:class:`geopandas.GeoDataFrame`
:py:class:`geopandas.GeoDataFrame` to transform.
utm_crs : str
:py:class:`rasterio.crs.C... | 02405ca581054b5d804c6e4eb49be96d0915e3de | 3,633,622 |
import re
def remove_prohibited_characters(prompt_str: str) -> str:
"""
Remove prohibited characters.
"""
prohibited_chars = ["[", "]", "<", ">", "#", "%", "$", ":", ";", "~", "\r", " ", "\n"]
result_str = prompt_str
for ch in prohibited_chars:
result_str = result_str.replace(ch, "")
... | 8eabb923b5ee59656fb41164d14be0ba6e4535f4 | 3,633,623 |
import scipy
def correction_factors(kappa, eta, gamma, b0, use_eta=True):
"""Computes correction factors for MLE of high dimensional logistic reg."""
system_ = get_system(kappa, eta, gamma, b0, use_eta)
if use_eta:
init = np.array([2, 2, np.sqrt(eta / 2), b0 / 2])
else:
init = np.array([2, 2, np.sqrt(... | 633183d63fc4c974b4f95d587f5bd625ab14e8b9 | 3,633,624 |
def make_style_prompt(choices: list, default: str = None, prompt_msg: str = "Would you like to:",
main_style: str = "none",
frame_style: str = "none",
frame_border_style: str = "none") -> str:
"""
Prompts user in a cool way and retrieves what the... | 06f20893f6e8616998142fee43ae5cb8ccb16bad | 3,633,626 |
from typing import OrderedDict
def jsonfile_1():
""" A JSON File object """
return thresh.TabularFile(
content=OrderedDict({"bar": 4, "foo": 3}), alias="JSON_", length_check=False, namespace_only=True
) | 7c9d856f7619fad54a7614107d018ec4be645498 | 3,633,627 |
def _get_cmfs_xy():
"""
xy色度図のプロットのための馬蹄形の外枠のxy値を求める。
Returns
-------
array_like
xy coordinate for chromaticity diagram
"""
# 基本パラメータ設定
# ------------------
cmf = CMFS.get(CMFS_NAME)
d65_white = D65_WHITE
# 馬蹄形のxy値を算出
# --------------------------
cmf_xy = X... | 67517dedbb53a30270b6bf2022dec64f796e1e31 | 3,633,629 |
def square_matrix_multiply(A, B):
""" 定義通りの計算 Θ(n^3)
"""
n = len(A)
C = [[0] * n for _ in range(n)]
for i in range(n):
for j in range(n):
for k in range(n):
C[i][j] += A[i][k] * B[k][j]
return C | e0c2766bb9f5f77df1f95f9158fd027db6b7eadb | 3,633,630 |
def _filter_irregular_boxes(boxes, min_ratio=0.2, max_ratio=5):
"""Remove all boxes with any side smaller than min_size."""
ws = boxes[:, 2] - boxes[:, 0] + 1
hs = boxes[:, 3] - boxes[:, 1] + 1
rs = ws / hs
keep = np.where((rs <= max_ratio) & (rs >= min_ratio))[0]
return keep | 31c6113c45195a31c0a9325a113363cc018a0a24 | 3,633,631 |
import http
def login(user, password):
"""
Authenticate against SomethingAwful, both storing that authentication in
the global cookiejar and returning the relevant cookies
:param user: your awful username for somethingawful dot com
:param password: your awful password for somethingawful dot com
... | ad76dc9e1af0e33cfb9d64b6a64dc7d1b3d4e57e | 3,633,632 |
def streams(url: str, **params):
"""
Initializes an empty Streamlink session, attempts to find a plugin and extracts streams from the URL if a plugin was found.
:param url: a URL to match against loaded plugins
:param params: Additional keyword arguments passed to :meth:`streamlink.Streamlink.streams`
... | 58a3cefa0c2957a168282f41457d1844fafdb728 | 3,633,633 |
def get_questionnaire_example() -> pd.DataFrame:
"""Return questionnaire example data.
Returns
-------
data : :class:`~pandas.DataFrame`
dataframe with questionnaire example data
"""
return load_questionnaire_data(_get_data("questionnaire_sample.csv")) | ed067c3a051e91d95326002fa52245304d1d7085 | 3,633,634 |
def tabulate_e2e_vectors(*, tau_n=dna_params['tau_n'], unwrap=None):
"""Return a lookup table of entry->exit vectors with the right magnitude in
nm. Multiply on the left with the entry orientation matrix to obtain the
entry to exit displacement vector.
One vector for each possible level of unwrapping.
... | 469e5e4389ea7215cad44862f8377a517714137f | 3,633,636 |
def load_fooof_task_pe(data_path, side='Contra', param_ind=1, folder='FOOOF'):
"""Loads task data for all subjects, selects and return periodic FOOOF outputs.
data_path : path to where data
side: 'Ipsi' or 'Contra'
"""
# Collect measures together from FOOOF results into matrices
all_alphas = n... | 7b7b6c26343b58c7c579c890d384f3d8a31611fa | 3,633,637 |
def warning(message):
"""Generic warning message formatter.
Args:
message (string): A message that describes the warning.
Returns:
(str): Formatted warning message.
"""
return bcolors.WARNING + "WARNING: " + bcolors.ENDC + message | d7a06aaf90f24cbb18028a8b921086d3c83efe76 | 3,633,638 |
def GetResult(cl, opts, result):
"""Waits for jobs and returns whether they have succeeded
Some OpCodes return of list of jobs. This function can be used
after issueing a given OpCode to look at the OpCode's result and, if
it is of type L{ht.TJobIdListOnly}, then it will wait for the jobs
to complete, other... | 8bdee53bc6a693436084362f8c6c643e3e565a0d | 3,633,639 |
from .SpectralDecomposer import Decomposer
from .model_housing import indivmodel
def decomposition_method(input):
"""
Decomposition of an individual spectrum using input guesses from the parent
SAA
Parameters
----------
input : list
A list which contains the following:
spectr... | 071ce1bde7d5302d09d41fc30216d578263cfbbf | 3,633,640 |
def cal_features(pm):
"""
only one track in pm, all bars are calculated
Returns:
used_pitch
used_note
pitch_histogram
pitch_interval_hist # not for track 2
pitch_range
onset_interval_hist
duration_hist
"""
result_features = {}
chromagram = np.zeros(12)
duration_h... | aad1d644b97c4b294c6bf25b6a5447475bcaaf4a | 3,633,642 |
def grayscale(img):
"""Applies the Grayscale transform
"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read an image with cv2.imread()
# return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) | 7e6408b4decb2b3a6a66b92afc1359fba2036735 | 3,633,643 |
def sample_user(email='test@joeshak.com', password='testpass'):
""" Create a sample user """
return get_user_model().objects.create_user(email, password) | a999bba7581edfd65491eee68ea6b9f0b786dcf0 | 3,633,644 |
from typing import Concatenate
def GroupConv1D(x, in_channels, out_channels, groups=1, kernel=1, strides=1, name=''):
"""
group Convolution 1D
group=1 means pointwise convolution
----
input:
- x:
input tensor
- in_channels:
input channels
- out_chann... | 7921e245a4988c0b5cbe4e45061d8aa1a97ece7a | 3,633,645 |
import logging
def get_logger_obj(logger=None):
"""Get a logger object that can be specified by its name, or passed as is.
Defaults to the root logger.
"""
if logger is None or isinstance(logger, py.builtin._basestring):
logger = logging.getLogger(logger)
return logger | 263b2f70211fa82891a41dce0cdee23cc7ca3e93 | 3,633,646 |
def calculate_wake_wing_influence_matrix(cpoints, wake, normals):
"""
Calculate influence matrix (steady wake contribution).
Parameters
----------
cpoints : np.ndarray, shape (m, n, 3)
Array containing the (x,y,z) coordinates of all collocation points.
wake : np.ndarray, shape (n, 4, 3)... | d99ca1c1291688462a8044fcfd558fbbba5f09b4 | 3,633,649 |
def get_recent_games(summoner_id):
"""
https://developer.riotgames.com/api/methods#!/1016/3445
Args:
summoner_id (int): the ID of the summoner to find recent games for
Returns:
RecentGames: the summoner's recent games
"""
request = "{version}/game/by-summoner/{summoner_id}/rece... | 12e5ec6816b987af74b79b0839c76b582793c145 | 3,633,650 |
import itertools
def create_daily_rate_line_plot(sources, services, y_axis_type='log', y_range=(1, 10**7)):
"""
Returns
-------
plotting.figure
A Bokeh plot that can be shown.
"""
# create plot with a datetime axis type
p = plotting.figure(plot_width=700, plot_height=1200, x_axi... | ef71f51aef3ebb039661c64a6ec9e7191ce04d21 | 3,633,651 |
def masked_loss(y_gt, y_pred, loss_fn, **kwargs):
"""Calculate 2d loss by removing mask, normally it's durrations/f0s/energys loss."""
real_len = tf.reduce_sum(tf.cast(tf.math.not_equal(
y_gt, 0), tf.float32), axis=1) # shape [B,]
max_len = tf.shape(y_gt)[1]
max_len = tf.cast(max_len, real_len... | eb9491d0dde283942a2983bce582d61c34aaa95c | 3,633,652 |
def call_ft(function, *args):
"""Call an FTDI function and check the status. Raise exception on error"""
status = function(*args)
if len(bRaiseExceptionOnError) > 0:
if status != FT_OK:
raise DeviceError(status)
return status | b78b7f39b06d990199f73c6d705408e291b85a91 | 3,633,653 |
import random
def reshuffle_words_to_fit(word_tuples_to_fit):
"""Within each length-class, reshuffle the words."""
new_word_tuples_to_fit = deepcopy(word_tuples_to_fit)
distinct_lens = set(len(wt.board) for wt in new_word_tuples_to_fit)
for word_len in distinct_lens:
word_inds_with_len = [i fo... | 17ef2434dbf540757daf194ae96ae5b8f6c098e6 | 3,633,654 |
def make_tree_all_params(species, dbh, height, stem_x, stem_y, stem_z,
lean_direction, lean_severity, crown_ratio, crown_radius_E,
crown_radius_N, crown_radius_W, crown_radius_S,
crown_edge_height_E, crown_edge_height_N, crown_edge_height_W,
crown_edge_height_S, s... | c7be83ebd67d6de21a2c7f82248903c23d63a83d | 3,633,655 |
def get_cfg_defaults():
"""Get a yacs CfgNode object with default values"""
# Return a clone so that the defaults will not be altered
# This is for the "local variable" use pattern
return _C.clone() | 7cbf9b8f325ba417cf6c959d900b61c727cec816 | 3,633,656 |
from typing import List
import fnmatch
def should_ignore(file: str, exclusions: List[str]) -> bool:
"""Check if a file matches a line in the exclusion list."""
for excl in exclusions:
if fnmatch(file, excl):
return True
return False
# for file in Path(".").glob("**/*.py*"):
# ... | ea8c4e4a6546d4f73009296208718696a443ac9f | 3,633,658 |
def fpn_classifier_graph(rois, feature_maps,image_shape, pool_size, num_classes,config):
"""Builds the computation graph of the feature pyramid network classifier
and regressor heads.
selector: 0 for training and 1 for inference
rois: [batch, num_rois, (y1, x1, y2, x2)] Proposal boxes in normalized
... | 3d6b649b2d4eab53aa856b169d87d83ba4c2eaff | 3,633,659 |
def fit_unitarity(depths, shifted_purities, weights=None):
"""Construct and fit an RB curve with appropriate guesses
:param depths: The clifford circuit depths (independent variable)
:param shifted_purities: The shifted purities (dependent variable)
:param weights: Optional weightings of each point to ... | a8fb739b4c64cf63ceff51ef9eabd276c2b6c48d | 3,633,660 |
import re
def filter_paragraph(p):
"""Simple filter to remove obviously bad paragraphs (bad text extraction).
Note this needs to run very quickly as it is applied to every paragraph
in the corpus, so nothing fancy! This whole method should be linear
expected time in len(p).
Args:
p: string, paragraph
Returns:
... | 4458a480c176149d1375dfafb13211b4fd7ee9d0 | 3,633,661 |
def get_matching_tables(tables, path):
"""Get list of matching tables for provided path
Return list is sorted by longest matching path part
:param tables: List of `Table' objects
:param path: Path like string
:return: List of matched by path tables
"""
candidates = []
for table in tabl... | e91e93cef56d3eb6e5b6ae85f522fbb042e472a9 | 3,633,662 |
import requests
def email_video_link(talk):
"""Send the presenter a link to their video, asking to confirm."""
meeting_recordings = common.zoom_request(
requests.get,
common.ZOOM_API + f"/meetings/{talk['zoom_meeting_id']}/recordings"
)
if not len(meeting_recordings["recording_files"])... | f47139dd42606a57406295f2079fdcc18e8fcfc0 | 3,633,663 |
import traceback
def make_import_user_csv_files(uw_accounts,
filepath):
"""
:param uw_accounts: a list of UwAccount objects
Writes all csv files. Returns number of records wrote out.
"""
if not uw_accounts or len(uw_accounts) == 0:
return 0
file_size = ge... | f41077fa18103edc63b727574b2e2c8ea8d039c8 | 3,633,664 |
def distanceInOval(x, y, a=3, b=2, k=0.2):
"""
:param x: high-dimension embedding of cell A
:param y: high-dimension embedding of cell B
:param a: major axis length
:param b: minor axie length
:param k: Deformation parameter
:return: distance between cell A and B in oval whose function is
... | acea2495d146a858ddfe5770025d95899f00c797 | 3,633,665 |
def file_generator(
wrapped=None,
ids=["file"],
names=[uuid4().hex],
suffixes=[""],
dirs=[SANDBOX],
properties=None,
):
"""Decorator which automates setup and return for file generation functions.
The decorator fulfills 3 tasks:
1. Generating required temporary file names.
... | ea36dbb67f722513bb149250f7536f331f95918d | 3,633,666 |
def optimal_t_from_selection(x, y, ts, J, min_n):
"""
Time complexity:
O(T*N)
Space complexity:
O(N+T) - to store the input
"""
N = len(x)
best_loss = np.inf
best_t = -np.inf
idx = None
for t in ts: # O(T)
# evaluate loss for splitting [:s], [s:]
y_l = y[x <= ... | 90e882f97cbf83c66dd395c8bf45993ae445cd9a | 3,633,667 |
def _deserialize_qnode(qnode_id, qnode):
"""Returns a QNode from a single deserialized QueryGraph node in a
TRAPI request
"""
constraints = []
try:
ids = qnode.get('ids')
categories = qnode.get('categories')
is_set = qnode.get('is_set')
req_constraints = qnode.get('co... | 81278d775ecc68b9202fc3941549414f98e8b7f9 | 3,633,668 |
def combined_f1_rmse(y_true, y_pred):
"""Difference between F1 score and root mean square error (rmse).
The optimal values for F1 score and rmse are 1 and 0 respectively.
Therefore, the combined optimal value is 1.
"""
return f1_score(y_true, y_pred) - rmse(y_true, y_pred) | e43511cbea8a6a7fe5eaa5e142ece568d59ec0f8 | 3,633,669 |
from pathlib import Path
def get_images_with_annotations(host, public_key, private_key, project_id=None, download=True, annotation_ids=None):
"""
Find and download (if not present) annotation information and images
:param annotation_ids: List of annotations to fetch
:param download: Whether or not to ... | 75ac5e025ead946e9d2c626799eb54d02e0cde71 | 3,633,670 |
async def infer_type_make_record(engine, _cls: dtype.TypeType, *elems):
"""Infer the return type of make_record."""
cls = _cls.values[VALUE]
if cls is ANYTHING:
raise MyiaTypeError('Expected a class to inst')
expected = list(cls.attributes.items())
if len(expected) != len(elems):
rai... | 8389217a1fee854b73d6189cf811a26a7613680a | 3,633,672 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.