content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def askFile():
""" Ask the user to select a file """
root = Tk()
root.withdraw()
root.wm_attributes('-topmost', 1)
filename = askopenfilename(parent=root)
return filename | d58b629f1f75abbe8661f0d4bea3503707c039ad | 78,425 |
def forum_detail_by_id(request, id):
"""
View the contents of a specific forum.
"""
forum = get_object_or_404(Forum, pk=id)
return _forum_detail(request, forum) | 334c9e624af1ec44c91725fb2c83aa2c1d7ba3a7 | 78,426 |
def relu(x):
"""Take relu of input x.
Parameters
----------
x : tvm.Tensor
Input argument.
Returns
-------
y : tvm.Tensor
The result.
"""
return tvm.compute(x.shape, lambda *i: tvm.max(x(*i), 0)) | 906bdc42f4f6f4488a75492d56d3edace2b6ff5a | 78,427 |
def add_argument(parser, flag, type=None, **kwargs):
"""Wrapper to add arguments to an argument parser. Fixes argparse's
behavior with type=bool. For a bool flag 'test', this adds options '--test'
which by default sets test to on, and additionally supports '--test true',
'--test false' and so on. Finall... | d802615f737c806be97962f18fdd7e8057512f96 | 78,428 |
def comm_svr():
"""Return global comm_svr configuration"""
return Conf.comm_svr | 2506605dc0ed4313b905696726e031130cf397e8 | 78,429 |
def pl_true(expr, model={}):
"""
Return True if the propositional logic expression is true in the model,
and False if it is false. If the model does not specify the value for
every proposition, this may return None to indicate 'not obvious';
this may happen even when the expression is tautological.
... | d77436f42c27ab2b3eccf85e9d6dbf3eddfb8fc2 | 78,430 |
def region_of_interest(img, vertices, overplot=False):
"""
Applies an image mask.
Only keeps the region of the image defined by the polygon
formed from `vertices`. The rest of the image is set to black.
`vertices` should be a numpy array of integer points.
Be aware that if overplot=Tru... | 6d14b118667e2e1221899c88008826fddea364b2 | 78,431 |
import queue
import json
def get_devices(event: dict, context: "LambdaContext") -> dict:
"""get device informations.
Parameters
----------
event : dict
event object.
context : LambdaContext
context object.
Returns
-------
dict
dict corresponding to http respon... | 3f484d2d1ec02b143e557f110e1f7cf276c178d3 | 78,432 |
def interpret_kfold_results(
kfold_results, crits, minimize=False, save_weight_path=None, hps=None
):
"""Return the parsed results of the best performing model from
kfold_solve.
Args:
kfold_results (dict): As returned by kfold_solve()
crits (str or list of str): Metric criteria to base ... | a74f9f7d6a65870d2c26df614f3d2dd87b06c45f | 78,433 |
from armor.objects3 import kongrey # the data
from armor.objects3 import kongreywrf2 # the models
def testA(startingFrom='20130828.0600', endsAt='20130830.0900', threshold=-9999):
"""
testA : get all the correlations
"""
"""
1. apply LoG(sigma=100) + threshold to models (M01-M20, +- 6 hours... | 57228538f07a04b3da209142baf10087d7808008 | 78,434 |
def extract_seq_patches(x, kernel_size, rate):
"""x.shape = [None, seq_len, seq_dim]
滑动地把每个窗口的x取出来,为做局部attention作准备。
"""
seq_dim = K.int_shape(x)[-1]
seq_len = K.shape(x)[1]
k_size = kernel_size + (rate - 1) * (kernel_size - 1)
p_right = (k_size - 1) // 2
p_left = k_size - 1 - p_right
... | 3ebb358a06d4548befdf18d4696243d0ed80e7bf | 78,435 |
def get_email():
"""
Return the configured email of the current repo
"""
repo = get_repo()
return repo.config_reader().get_value("user", "email") | 29a59226b686df02e9ede3481c458aac229b0fa9 | 78,436 |
def one_vs_one_svm_inference(X, W, b):
"""Multiclass linear SVM prediction of the class labels.
Parameters
----------
X : ndarray, shape (m, n)
input features (one row per feature vector).
W : ndarray, shape (n, s)
weights (one vector per pair of classes).
b : ndarray, shape (... | 567ad40848a1a8db489d3c650f3cd78db4eeec2e | 78,437 |
def add_features(dataframe):
"""
Adds Recency, Frequency and Revenue Features to data frame.
Recency = (Closing Transaction Date - Recent Transaction Date) + 1
Frequency = Number of purchases
Monetary Value = Max Revenue Generated (Unit Price x Quantity)
:parameter:
dataframe: pandas d... | c3dbf6d58fd88120a6f5172efa10537da31de97b | 78,438 |
def array_to_schedule(array, events, slots):
"""Convert a schedule from array to schedule form
Parameters
----------
array : np.array
An E by S array (X) where E is the number of events and S the
number of slots. Xij is 1 if event i is scheduled in slot j and
zero otherwise
... | 3627fb47de482d972053a3460df2cee98be06d3c | 78,439 |
def group_fasta(fa):
"""
return:
{>id: ATCG..., }
"""
ids = []
seqs = []
seq = ''
with open(fa, 'r') as fo:
n = 0
while True:
line = fo.readline().strip('\n')
if line.startswith('>'):
ids.append(line)
if seq:
... | 821746f46a0458c99e34f38f175fc36dc3550a9c | 78,440 |
import re
def removeParam(urlquery, parname, mode='complete'):
"""Remove a parameter from current query"""
urlquery = urlquery.replace('&&', '&')
urlquery = urlquery.replace('?&', '?')
pstr = '.*(%s=[a-zA-Z0-9\.\-\_\,\:]*).*' % parname
pat = re.compile(pstr)
mat = pat.match(urlquery)
if ma... | e0e32a3f55119ad4089b33e9da7f8f822527f4bb | 78,441 |
def set_sample_rate(rate):
"""
Set the sample rate and save it in the settings file.
:param rate: ADC sample rate in samples per second. 1 < rate < 100.
:return: bool indicating whether or not the operation was successful.
"""
# check if the number is in the allowed range
if rate < 1 or ra... | 3f7e652e6e36d83518de05f756d1ff5fceda2b60 | 78,442 |
def process_dataset(dataset_obj: dict, syn=None):
"""
Takes in a dataset from the configuration file and passes it through the
ETL process
:param dataset_obj: a dataset defined in the configuration file
:param syn: synapse object
"""
dataset_name = list(dataset_obj.keys())[0]
entities_a... | ac78369ca2ab53e539923f42009ae2371de446b1 | 78,443 |
import time
def convert_from_html_time(html_time):
"""Converts times sent through html forms to dates suitable for the database
html_time - Time of the format 9:00 AM
returns number of minutes since 12:00 AM
"""
parsed = time.strptime(html_time, "%I:%M %p")
return parsed.tm_hour * 60 + parsed.... | 89f8fe3ee1be7abb55cb523c73dc130cc38825d7 | 78,444 |
def get_animManager():
"""
Return axample of configured AnimationManager instance
example idea borrowed from:
http://matplotlib.org/examples/animation/simple_3danim.html
"""
NUM_LINES = 50
NUM_STEPS = 1000
STEP_MAX = 0.1
fig = plt.figure('3D Random walk example')
... | 7bf73a3a51264205ca6da8b93348673b46cd461f | 78,445 |
def context_combination(
windows,
use_docker,
use_celery,
use_mailhog,
use_sentry,
use_compressor,
use_whitenoise,
cloud_provider,
):
"""Fixture that parametrize the function where it's used."""
return {
'windows': windows,
'use_docker': use_docker,
'use_c... | 9a1e0b3adf3104fcb837078a61408db511d8f19e | 78,446 |
def init(runtime_id, name):
"""
Intializes the data source.
Returns the initial state of the data source.
"""
return {} | b90f6bb131df8c1e47bd8fead95273613b59ac3a | 78,447 |
def initialize_bias(dim_out):
"""
Initialize the bias of a neural network layer.
- dim_in: input size of the layer
- dim_out: output size of the layer
"""
b = np.zeros(dim_out).astype(np.float32)
return b | 2462699149f4949cf23de661d5e4daf88dbffb46 | 78,448 |
async def get_diagnostics_for_config_entry(hass, hass_client, domain_or_config_entry):
"""Return the diagnostics config entry for the specified domain."""
if isinstance(domain_or_config_entry, str):
config_entry = MockConfigEntry(domain=domain_or_config_entry)
config_entry.add_to_hass(hass)
... | 004c40344e376cc55894172f448006b2614ad788 | 78,449 |
async def add(request: Request, x: float, y: float) -> Response:
"""An addition endpoint."""
return JSONResponse({"result": x + y}) | 0fe5a8c95621f31b1b90c95ff0e685ea424e9c6d | 78,450 |
def get_time_from_sim_steps(steps: int, units: str) -> int:
"""Calculates simulation time in the specified *units* from the *steps* based
on the simulator precision.
Args:
steps: Number of simulation steps.
units: String specifying the units of the result
(one of ``'fs'``, ``'ps... | 7a9eae3f6873b76fecd65f73ded6c077c877ee94 | 78,451 |
from socket import getfqdn
def our_host_name():
"""Try to return the canonical name for this computer. This is used
in the drag-and-drop protocol to work out whether a drop is coming from
a remote machine (and therefore has to be fetched differently)."""
global _host_name
if _host_name:
return _host_name
try:... | 48ad2b0f64ff51a7c14b2c2d1c48a45da171a623 | 78,452 |
def identity(x):
"""Returns whatever is passed."""
return x | e18cfe924da5195d2608f1808b17f142e23a83da | 78,453 |
def _get_depth(matrix, vec, height):
""" Get the depth such that the back-projected point has a fixed height"""
return (height - matrix[1, 3]) / (vec[0] * matrix[1, 0] + vec[1] * matrix[1, 1] + matrix[1, 2]) | b0db2823a47b110c302595a4c281e81e01bf7b2f | 78,456 |
import bisect
def get_window(chromosome, target_peaks, distance):
"""
Returns a window of all peaks from a replicate within a certain distance of
a peak from another replicate.
"""
lower = target_peaks[0].midpoint
upper = target_peaks[0].midpoint
for peak in target_peaks:
lower = m... | 875549b6000c4114b07b9de970b2b7071b704e2c | 78,457 |
def _rotate_pos(x, y, cx, cy, angle, base_angle=0.):
"""Rotates ``(x, y)`` by angle ``angle`` along a circle centered at
``(cx, cy)``.
"""
hyp = ((x - cx) ** 2 + (y - cy) ** 2) ** 0.5
xp = hyp * cos(angle + base_angle)
yp = hyp * sin(angle + base_angle)
return xp + cx, yp + cy | 2b3502a35f58eddbcf05176e6f2dff663d2341fb | 78,458 |
def checkout_dropdown(request, checkout):
"""Display a checkout summary suitable for displaying on all pages."""
discounts = request.discounts
taxes = request.taxes
def prepare_line_data(line):
first_image = line.variant.get_first_image()
if first_image:
first_image = first_... | a1018757961973adefa3ad3eaea6431a42ba1c3a | 78,459 |
import torch
def transformation_from_parameters(axisangle, translation, invert=False):
"""Convert the network's (axisangle, translation) output into a 4x4 matrix
"""
R = rot_from_axisangle(axisangle)
t = translation.clone()
if invert:
R = R.transpose(1, 2)
t *= -1
T = get_tra... | 60e3f797790dfb24e3989502ca1350731dea336f | 78,460 |
def _get_file_pairs(first_app, second_app):
"""
:param first_app:
:param second_app:
:return: A dictionary mapping file name to tuple where the first element is
the corresponding file on the first app and the second is the corresponding
file on the second app.
"files" will be empty string... | 54fa23bc6166014012991ff92fee7dc059bf647f | 78,461 |
def model_with_buckets(encoder_inputs_tensor, decoder_inputs, targets, weights,
buckets, seq2seq, softmax_loss_function=None,
per_example_loss=False, name=None):
"""Create a sequence-to-sequence model with support for bucketing.
The seq2seq argument is a function t... | 83432f79f0dbb5c68a19429c47f407958dd655c9 | 78,463 |
def project_execution_sequence_to_leafs(execution_sequence):
"""
Project an execution sequence to the set of leafs
of the tree.
Parameters
------------
execution_sequence
Execution sequence on the process tree
Returns
------------
list_leafs
Leafs nodes of the proce... | 8f72c144186c73fa702202ecfc0377d2dbeebc32 | 78,464 |
from typing import List
from typing import Dict
def mapping_security_zone(iplist: List[str]) -> Dict[str, str]:
"""
Fake list of ranges for GCP
"""
dmz_range = list(netaddr.IPNetwork('192.168.0.0/24'))
secure_range = list(netaddr.IPNetwork('192.168.2.0/22'))
ip_zone = {}
for ip in iplist... | f7e80bdfbd2cec9674aa2de4dbf0fb0bc3b38ac8 | 78,465 |
def validate_booleanunsure(value):
"""Validate BooleanUnsure values."""
if value not in set(x.name for x in BooleanUnsure):
raise ValidationError('Value must be "true", "false", or "uncertain".')
return True | 1cdb8f44831ad508423d8d76009f5c4555e6b339 | 78,466 |
def cancel_all_open_orders():
"""Cancels all open orders.
:returns: The list of orders that were cancelled.
"""
url = urls.orders()
items = helper.request_get(url,'pagination')
items = [item['id'] for item in items if item['cancel'] is not None]
for item in items:
cancel_url = ur... | 4bee186ca848c8be4f0e63a898a9fb2958677d28 | 78,467 |
def gettrigsources(name):
"""Return trigger option value according to 'name'.
@param name: Short name of item, e.g. "CUR_POS". Case insensitive, separated by "_".
@return : According enum value as integer.
"""
return __getopt(name, TriggerSources) | c8de496fc5e8ea3a48b078fb51442c43ac5cc755 | 78,469 |
def bitwise_dot_product(bs0, bs1):
"""
A helper to calculate the bitwise dot-product between two string representing bit-vectors
:param String bs0: String of 0's and 1's representing a number in binary representations
:param String bs1: String of 0's and 1's representing a number in binary representati... | edb928ead1c7e9bcd2756174629209eeab3cef87 | 78,471 |
def discover_database_servers(_ip):
"""Uses Nmap to scan the subnet of the specified IP-address for the following RDBMS:
SQL Server, IBM DB2, MYSQL, Oracle and Postgres."""
return discover_services(_ip, [1433, 523, 1521, 5432, 3306], True) | 35ca927fa8551c5809c8dcd4e2e0a00779fd8876 | 78,472 |
def dist_to_decision_boundary(
clf, x, target_class, target_confidence, lp_space, inv_feature_weights=None, _grad_norm=None
):
"""
Compute distance to the decision boundary of a binary linear classifier.
"""
confidence = clf.predict_proba([x])[0, target_class]
if confidence > target_confidence:
... | 1ee84fdb327a72907fad2b27e6ddc150f400fedf | 78,474 |
def xsd42():
"""Load DataCite v4.2 full example as an etree."""
return _load_xsd('4.2/metadata.xsd') | 53838737dd3a623e442b4be92d9f494e16e3f927 | 78,475 |
import shutil
def binary_available() -> bool:
"""Returns True if the Radix CLI binary (rx) is
availabile in $PATH, otherwise returns False.
"""
return shutil.which("rx") is not None | fa814b20b3fe47096dfed64bde3f9cb33e9b711d | 78,476 |
def format_codewars_puzzle_for_discourse(puzzle):
"""Format a codewars puzzle to post as a forum post in Discourse."""
print("helper got puzzle for discourse", puzzle)
if not puzzle:
return None
title = f"Puzzle: {puzzle['name']} [{puzzle['category']}]"
languages = "{}, and {}".format(", ".... | 0d27e69426676fec6d3f24b56acfcb93c4288ae7 | 78,477 |
import skimage.transform
def resize_to_mm(
data3d,
voxelsize_mm,
new_voxelsize_mm,
mode="reflect",
order=1,
anti_aliasing=False,
preserve_range=True,
**kwargs,
):
"""
Function can resize (grayscale or color) data3d or segmentation to specifed voxelsize_mm
:param data3d: in... | 494bbdf5861898a0608423536a532fae2c86ab3b | 78,478 |
def fromURL(url, log=None):
"""Shortcut Pynliner constructor. Equivalent to:
>>> Pynliner().from_url(someURL).run()
Returns processed HTML string.
"""
return Pynliner(log).from_url(url).run() | cac3909f370848a5fb06ab43adf236f07417a675 | 78,479 |
def prep_difflines(content):
""" difflib takes input in this "readlines" compatible format """
return [ x+"\n" for x in content.split("\n") ] | 192f198285598e3fe69c6155459974f7664af090 | 78,480 |
def model_pred_on_gen_batch(model, b_gen, b_idx=0):
"""
Predict on model for single batch returned from a data generator.
Returns predictions as well as corresponding targets.
"""
# predict on model
X,y = b_gen.__getitem__(b_idx)
pred = model.predict_on_batch(X)
return pred, y | 1a23903f088fc61b96060ab913ddbc554d5584a6 | 78,481 |
def user_registry(username, password):
"""Registry a new user
:param username: an email address
:param password:
:return:
"""
try:
user = User.objects.create_user(username=username,
email=username,
password=password)... | 9042b659442fb4a93517c01d39074030634ccad4 | 78,483 |
def equation_string(A: np.ndarray, b: float, rel: str = ' ≤ ') -> str:
"""Return the string representation of an equation.
For A = [a1,..,an], b, and rel returns the string form of the equation
a1 * x_(1) + ... + an * x_(n) rel b where rel represents some equality
symbol = or inequality symbol <, >, ≥,... | 6566c4b57293b24377fee82bf5ea2c498a60a3a8 | 78,484 |
def read_user_me(
*,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_active_user),
):
"""read current login user"""
return current_user | d9f006f6229e6ec2a5088884e0347b9e2638784c | 78,485 |
def distance(x1: float, y1: float, x2: float, y2: float):
"""
Calculates the euclidean distance between two points in 2d space.
"""
return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) | 913bf1595def0c74a3fa6370dc1cd4e798dbc74c | 78,486 |
def get_encoding_mu_logvar(encoding_image):
"""Computes the encoding_image's style noise parameters.
Args:
encoding_image: [B, H, W, 4] input RGBD image to run Infinite Nature on
Returns:
tuple of tensors ([B, z_dim], [B, z_dim]) corresponding to mu and logvar
normal parameters.
"""
with tf.comp... | 75a41dc5d3c252de9d9bb95ab02bcb5d6a65aa7e | 78,487 |
from typing import Union
import math
def _kl_divergence_bernoulli_bernoulli(
dist1: Union[Bernoulli, tfd.Bernoulli],
dist2: Union[Bernoulli, tfd.Bernoulli],
*unused_args, **unused_kwargs,
) -> Array:
"""KL divergence `KL(dist1 || dist2)` between two Bernoulli distributions.
Args:
dist1: insta... | 8c5f137a0939566e6cdc40d7aec79bf48c341b6c | 78,488 |
def compute_F1(cm):
"""
For Binary classification problems only
:param cm:
:return:
"""
assert len(cm.shape) and cm.shape[0] == cm.shape[1] and cm.shape[0] == 2
TP = cm[1, 1]
TN = cm[0, 0]
FN = cm[1, 0]
FP = cm[0, 1]
assert (2*TP + FP + FN) != 0
return float(2*TP)/(2*TP +... | 4c0b53dc78f7f52d2fa3ffa1fc5492dab2b7dba4 | 78,490 |
def portForward(port):
"""
Decorator wrapper function for port forwarding of the REST calls of any
function to a given port.
Currently there are three constraints for applying this decorator.
1. The function to be decorated must be defined within a class and not being a static method.
The re... | a8b390aab65da2c239558f64360e9391dc1d9f63 | 78,491 |
import functools
def basic_block(stride, filter_mul):
"""Returns a ResNetv1 basic block."""
input_name = "input"
ops = []
append = functools.partial(append_op, ops)
out_filters = "S:-1"
if filter_mul > 1:
out_filters = f"{out_filters}*{filter_mul}"
append(op_name="conv0",
op_type=OpType.C... | 78c747221a4bae51da7ba59e9e6deece47f06f04 | 78,492 |
import time
def mk_epoch_from_utc(date_time):
"""
Convert UTC timestamp to integer seconds since epoch.
Using code should set
os.environ['TZ'] = 'UTC'
"""
pattern = '%Y%m%d-%H%M%S'
return int(time.mktime(time.strptime(date_time, pattern))) | 070cc8b6ad23e9b590b35d014d7accdab5649a16 | 78,493 |
def reg_copy(reg, keys=None):
"""
Make a copy of a subset of a registry.
:param reg: source registry
:param keys: keys of registry items to copy
:return: copied registry subset
"""
if keys is None:
keys = reg.keys()
reg_cls = type(reg)
new_reg = reg_cls()
mk = {} # empt... | bbf7c5f7074996b5623bde5e8e9fa5d7e1fcf6fa | 78,494 |
def canonicalize_with_h(mol, reaction=False, old2new_mapno={}):
"""
Outputs the canonical SMILES with hydrogens.
Parameters
----------
mol: rdkit.Chem.Mol
RDKit molecule.
reaction: bool, default False
Whether the input SMILES stems from a reaction and therefore map numbers need ... | 615c47ccedf30b5116f29af13346b42084b0a82e | 78,495 |
def convert_list_of_schema_fields_to_list_of_lists(input_schema_fields_list):
"""
This is a helper function to assist in comparing output of two methods of schema conversion from JSON to BigQuery.
Iterate through a list of SchemaFields and apply the function convert_schema_field_to_list to each SchemaField... | 08244510a81570ce71e8f62e04115f37d88569a5 | 78,496 |
def get_runscript(self) -> str:
"""Run a parallel version of CP2K without mpirun or srun, \
as this can cause issues with some executables.
This method is monkey-patched into the PLAMS ``Cp2kJob`` class.
"""
cp2k_command = self.settings.get("executable", "cp2k.ssmp")
return f"{cp2k_command} -... | 1f9ea38a6171881848919d88eb9c48a0e649f504 | 78,497 |
def create_root(file_prefix, width, height):
"""[summary]
Arguments:
file_prefix {[type]} -- [description]
width {[type]} -- [description]
height {[type]} -- [description]
Returns:
[type] -- [description]
"""
root = ET.Element("annotations")
ET.SubElemen... | 2c67d016a69c2e8dbebf4420d3f1880110226fb6 | 78,498 |
def dateformat(*args):
"""
.. function:: dateformat(date[,inpformat,outformat])
Returns *date* formatted with *outformat*. Default *inpformat* is %d-%m-%y and default
*outformat* is %Y-%m-%d. To change *inpformat* just provide as second parameter the input format.
To change *outformat*, both format... | 88cbcc8d3c0a8db296234976fcd7cba8a764a9cd | 78,499 |
import pickle
def _get_results(args, bhv, num_epochs = 10,k_param = 10, perm=False):
""" load results pkl file
Args:
k_param: k_hidden if model_type = 'lstm'
k_wind if model_type = 'tcn'
k_layers if model_type = 'ff'
corr_thresh if model_type = '... | d1b5a496d068d49209e550dc83ac77e7d5450594 | 78,500 |
def private_key_to_public_hex(private_key_hex):
"""Given private key as hex string, return the public key as hex string."""
private_key_int = int(private_key_hex, 16)
return hex(private_to_stark_key(private_key_int)) | 1b318f62c0a3fe3e0d65bdbd06aab6deba02e525 | 78,501 |
import csv
def load_dataset_tasks_csv(fp):
"""Loads the problem definitions for an entire dataset from one CSV file."""
reader = csv.DictReader(fp, fieldnames=TASK_FIELDS)
rows = [row for row in reader]
tasks = VideoObjectDict()
for row in rows:
key = (row["video_id"], row["object_id"])
... | 2209ab17b73e36b70cd3b75bb0ac88614ea27a8c | 78,502 |
import html
def Add_Dash(server):
"""Create a Dash app."""
tickers = pd.DataFrame(data2.infobox.head(7))
tickers.set_index('infobox', inplace=True)
external_stylesheets = ['/static/dist/css/styles.css',
'https://fonts.googleapis.com/css?family=Lato',
... | 3ec8fbe06b5c27f36731fbf9d82dbeaaa7412787 | 78,504 |
def exportLamp(ob, mx, mw, **common):
"""converts Lamp-Object to desired projection and representation(DXF-Entity type)
"""
p = Mathutils.Vector(ob.loc)
[p] = projected_co([p], mx)
[p] = toGlobalOrigin([p])
entities = []
c = lamp_as_list[GUI_A['lamp_as'].val]
if c=="POINT": # export as POINT
dxfPOINT = DXF.... | adafec7bb5dba3f55de7bf040c8e6fd16e4a4fab | 78,505 |
def get_app_dir():
""" Getter for invoke global. """
if not TASKS_INITIALIZED:
raise SyntaxError("You must call init_monorepo_tasks() before using this task.")
global APP_DIR # pylint: disable=global-statement
return APP_DIR | caa919034d658fb3450fd8760822ead5fa80ddd9 | 78,507 |
def _bytes_feature(bytes_list):
"""Supports lists with either bytes or str elements"""
# Str?
if len(bytes_list) > 0 and type(bytes_list[0]) is str:
decoded_value = [str.encode(v) for v in bytes_list]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=decoded_value))
# Bytes
... | ab709d9c6cce2105212e02ac8374440beb2fdb3c | 78,508 |
def distance_pruning(context):
"""Prune sentence annotations based on nearest character distance of a
lexical modifer to lexical target, resulting in one modifier per target.
Args:
context (pyConTextNLP.pyConTextGraph.ConTextDocument): object containing
sentence markups across the r... | ee5a4df92210243c563edf9dfac0f1ac33f6c22c | 78,509 |
import math
def compliant_distance_ft(eirp_mw: float, mpe_limit_mwcm2: float, ground_reflections: bool) -> float:
"""Calculate what distance from an antenna will comply with a maximum permissible exposure (power density) limit.
Based on area of sphere.
:param ground_reflections: Whether to account for gr... | f7cec9bc94e1df4493d76ecffdaca66a413e4120 | 78,510 |
def load_hdf5(filename):
""" loads new .mat file save using the -v7.3 flag in matlab.
:param filename: file to load
:return: dict with the values
"""
fh = tables.open_file(filename)
data = dict()
data['labelimg'] = fh.root.newCell.labelimg[:].T
data['dendTable'] = fh.root.newCell.de... | 6e27846eccabf01032b497b23565b91b6403a315 | 78,512 |
def get_boolean(value):
"""Convert a value to a boolean.
Args:
value: String value to convert.
Return:
bool: True if string.lower() in ["yes", "true"]. False otherwise.
"""
return True if value.lower() in ["yes", "true"] else False | 5ec4048608fb0f456b1eecb463202cba54784a28 | 78,513 |
import numpy
def twoLeg(L1, L2, th1, th2):
"""
B
\
\ang2/
\ /
A\/
/
/
/ ang1
______O/_______
"""
th1 = numpy.radians(th1)
th2 = numpy.radians(th2)
origin = numpy.array([0, 0])
... | e35fad473cbad0918b11a153b1dfadca678e10f4 | 78,514 |
import warnings
from Bio import BiopythonParserWarning
import struct
def _sff_file_header(handle):
"""Read in an SFF file header (PRIVATE).
Assumes the handle is at the start of the file, will read forwards
though the header and leave the handle pointing at the first record.
Returns a tuple of values... | 0f91452a5ca83d29bdebc81ff060b327a38ff3c8 | 78,515 |
from typing import Iterable
from typing import List
from typing import Union
import tqdm
def quantize_model_post_training(
onnx_file: str,
data_loader: DataLoader,
output_model_path: str = None,
calibrate_op_types: Iterable[str] = ("Conv", "MatMul", "Gemm"),
exclude_nodes: List[str] = None,
in... | 172b6a64fa9260a7090109fb6912f1cfd51966b5 | 78,517 |
def is_background(sample):
"""Return ``True`` if given sample is background and ``False`` otherwise."""
background_relations = sample.resolwe.relation.filter(
type='compare',
label='background',
entity=sample.id,
position='background'
)
return len(background_relations) > ... | ba2bac31991798d1cfb1c00a27aaeb4dbc79a73b | 78,518 |
import json
def unpacking_func(row):
"""
Unpack a MySQL row (dictionary with keys as col names) into a claim object.
"""
claim = Claim(id=row["id"], email=row["email"], weeks=row["weeks"])
claim.form_url = row["form_url"]
claim.is_delivered_successfully = row["is_delivered_successfully"]
... | 507ea83798fe9482960986cdcbe5cfb6f2c7d67c | 78,519 |
def TryLinkWO(context, text=None, extension='.c', **overrides):
"""Try compile and link a program in a modified environment.
This test temporarily applies **overrides** to context.sconf.env and runs
``context.sconf.TryLink(text, extension)``.
:Parameters:
context
SCons configur... | 691819b1f907f2701085bea3287cd65e3e82e202 | 78,520 |
def is_url_valid(youtube_url):
"""
Checks a given url is valid or not
:param youtube_url: is URL
:return: True if the URL is valid, otherwise False
"""
if "https://www.youtube.com/watch?v=" not in youtube_url:
return False
return True | 32bb09da3071504a3c7857e6a028d9925447f3d4 | 78,522 |
def waypoint_list_from_tuple(traj):
"""Return a list of Waypoint instances from a list of (x, y, timepoint)"""
waypoint_list = []
for x, y, timepoint in traj:
waypoint = Waypoint()
waypoint.pose = Pose()
waypoint.pose.position.x = x
waypoint.pose.position.y = y
waypoi... | c866ebeebaaeab9bc1863697bbc829ca05468a37 | 78,524 |
def register():
"""Register user"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide usern... | 90a2ab3970d32a88896fe4c38c0c15c9847e4b4e | 78,526 |
def get(name: str) -> BaseEncoding:
"""
Gets an encoding by name.
Example usage:
>>> bases.get("base16")
ZeropadBaseEncoding(
StringAlphabet('0123456789ABCDEF',
case_sensitive=False),
block_nchars=2)
:param name: the encod... | 6df2a7cdd9b42e0796e3a30c8653cc199637e70c | 78,527 |
from typing import Any
from typing import Optional
def toDate(value: Any) -> Optional[dt.datetime]:
"""
Coerces the input value to a Date instance.
Null values and empty strings are mapped to null.
If an optional parser function is provided, it is used to
perform date parsing, otherwise Date.parse... | dd0d44fe91b3d98610af4b5042bc852130870b6a | 78,528 |
def getAirflowVariable(variableName):
"""Gets an Airflow variable and removes leading & trailing whitespace, so that it user has included these in error, they won't affect the scripts.
Args:
variableName (string): Name of the Airflow variable to get.
Returns:
Variable with leading and trailing whitespac... | 1f4bd178ae2ebd224b461dfc8f77cbe18307980b | 78,529 |
import types
import functools
def require_unique_document_schema(schema=None):
"""Decorator to enforce only one singleton document exists in the system.
An example of a singleton document is a ``LayeringPolicy`` document.
Only one singleton document can exist within the system at any time. It is
an ... | 50babdeae991074581393698a2fb3118104defd4 | 78,530 |
def checkNaN(x):
"""checkNaN(x)
This checks if a value (e.g. K-ratio) is NaN and sets the value to
zero if it is. This really helps when writing data frames to be
read by R."""
if isNaN(x):
x = 0.0
return x | 52fac065fa8fd3f9ffadf8d6706dcf456d91ab8a | 78,531 |
def get_z_variable(nc):
"""
Returns the name of the variable that defines the Z axis or height/depth
:param netCDF4.Dataset nc: netCDF dataset
"""
z_variables = get_z_variables(nc)
if not z_variables:
return None
# Priority is standard_name, units
for var in z_variables:
... | 3dc78491753eb0e6ebca686aeed3e436fdcc32a9 | 78,532 |
def get_slice(x, indices):
"""Return a slice of an array, following Numpy's style.
Parameters
----------
x : array-like, shape=[dim]
Initial array.
indices : iterable(iterable(int))
Indices which are kept along each axis, starting from 0.
Returns
-------
slice : array-l... | 7836a66e81e564aec1e2e1f20200318f10fea8ce | 78,533 |
import torch
def ravel_state_dict(state_dict):
"""
state_dict: all variables, incluing parameters and buffers
"""
li = []
for _, paras in state_dict.items():
li.append(paras.view(-1))
return torch.cat(li) | 16e5fe5ec07357f694c5665aba96d7ca2ce53796 | 78,534 |
from typing import Hashable
from typing import Optional
from typing import List
from typing import Dict
from functools import reduce
import warnings
def filter_date(
df: pd.DataFrame,
column_name: Hashable,
start_date: Optional[dt.date] = None,
end_date: Optional[dt.date] = None,
years: Optional[L... | 7099df28e61a6f369741ecdbb98f76d6d9e09d4d | 78,535 |
def length_gt(value, arg):
"""Returns a boolean of whether the value is greater than an argument."""
return len(value) > int(arg) | 99ec2a83d20e1982ec1667132a1c7ee4baf87af7 | 78,536 |
def course_page(school, department):
""" Renders the page where the user selects their course. """
courses = GetCourses(school, department)
if courses is None:
return default_error, 400
return render_template('courses.html', courses=courses) | 3f9cce91c73374b7e06fd648e26a1ad17c24eca0 | 78,537 |
def get_averagedslices_flight(df,BL,SCS,US,ISI,Trials,fs=5,Behav='Freezing',Group=[]):
"""Flight version of get_averagedslices(). Slices and averages data for
baseline and individual stimuli within trials.
Parameters
----------
df : pandas dataframe
dataframe generated from Threshold2F... | 20243c83df7ee7acc3a3cde7e9dfb1b83caa926a | 78,538 |
def is_bam(fname):
"""Check if a given file is a bam file
Args:
fname: file name
Returns:
True if file is a bam file, otherwise False
"""
try:
fileType = pybedtools.BedTool(fname).file_type;
if fileType == "bam":
return True
except ValueError as ... | fa26f690c935ef3b1b7ddb8d17899412792b581f | 78,539 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.