content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def genotype_likelihood_index(allele_indices):
"""Returns the genotype likelihood index for the given allele indices.
Args:
allele_indices: list(int). The list of allele indices for a given genotype.
E.g. diploid homozygous reference is represented as [0, 0].
Returns:
The index into the associated... | 646cdfa8e895480d7f7bd022461721ebf68af60d | 655,078 |
def wrap_neg_index(index, dim, neg_step: bool = False):
"""Converts a negative index into a positive index.
Args:
index: The index to convert. Can be None.
dim: The length of the dimension being indexed.
"""
if index is not None and index < 0 and \
not (neg_step and index == -1):... | 6198db6ac350971fad37754a196f2c1c62a1563b | 655,079 |
import re
def text_area_extractor(text):
"""
Textbox extractor function to preprocess and extract text
Args:
text: Raw Extracted Text from the News Article
Returns:
text: Preprocessed and clean text ready for analysis
"""
text = text.lower()
text = re.sub(r'[^a-zA-Z0-9\s]',... | 202168bb6763b96b93aec51821cc13a1bf697f5e | 655,080 |
def to_str_raw(data) -> str:
"""Quick and very dirty -- use str() with replacements."""
s = str(data)
s_ = s.replace('\'', '"')
return s_ | e2e3c89b4afdd69b6684fd715da3eee600c39221 | 655,081 |
import calendar
import time
def time_string_to_unix(time_string, time_format):
"""Converts time from string to Unix format.
Unix format = seconds since 0000 UTC 1 Jan 1970.
:param time_string: Time string.
:param time_format: Format of time string (example: "%Y%m%d" or
"%Y-%m-%d-%H%M%S").
... | 1b091a425b9bd16ff0dcc8f7e4acbd6980ee1252 | 655,082 |
def alpha_to_leet(character):
"""
Uses some mapping from http://www.robertecker.com/hp/research/leet-converter.php to switch an alphabetical character
to a numeric character. Utilizes some "standards" as well (like "3" for "E")
:param string character:
:return string:
"""
swaps = {
... | e6698f3371e48463d6342fe9320fd647446e0ddd | 655,084 |
import csv
def export_to_csv(dict_data,e):
"""Fonction export au format tsv"""
# Export au format TSV
csv_columns = ["mnemonique","adresse","variable","remarque"]
try:
with open(e.path, "w") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns, delimiter="\t")
... | 933eb05c9d4c20e377c6294c8ace55d2eb6b01b4 | 655,086 |
import click
def read_user_variable(var_name, default_value):
"""Prompt the user for the given variable and return the entered value
or the given default.
:param str var_name: Variable of the context to query the user
:param default_value: Value that will be returned if no input happens
"""
#... | c731ed7313924f00b4117fda451f87cbcf50a463 | 655,089 |
def cut_part_img(img, cut_percent):
"""
# 从宽度和高度两个方向,裁剪身份证边缘
:param img: 身份证区域
:param cut_percent: 裁剪的比例
:return: 裁剪后的身份证区域
"""
height, width, _ = img.shape
height_num = int(height * cut_percent) # 需要裁剪的高度值
h_start = 0 + height_num // 2 # 左右等比例切分
h_end = height - h... | 3a8c889822ad04eefdb00c5ece2663e3b025accd | 655,090 |
import argparse
def _parse_args(argv):
"""Parses command-line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--datasets",
help="""Datasets to use for training and out of study-testing.
""",
required=True,
nargs="+",
)
parser.ad... | 7edf698708a3148cd31b1565836727b6d772327b | 655,091 |
def no_error_func(num: int, name: str, outcome: bool) -> None:
"""No error function
>>> all_args(1, "a", True)
None
"""
return None | f01b981c6d5e7c07834967aa6f87c4bbb7ecc358 | 655,093 |
def change_korean_aux(corpus):
"""Changes instances of the "aux" relation towards the UD annotations scheme.
Only apply this method to: "GSD", "PUD"!
For each instance of "flat":
Let its dependent be the auxiliary.
Let its head be the main verb.
If the UPOS tags for both auxiliary and main verb are "VE... | 21a711e5315ab57fac24a995e5378c9b318fea21 | 655,094 |
def _finalize_memory(jvm_opts):
"""GRIDSS does not recommend setting memory between 32 and 48Gb.
https://github.com/PapenfussLab/gridss#memory-usage
"""
avoid_min = 32
avoid_max = 48
out_opts = []
for opt in jvm_opts:
if opt.startswith("-Xmx"):
spec = opt[4:]
... | 519110c2a9c912f82e5d5476730a52f0f5db12d7 | 655,095 |
import re
def translate_mute(program):
"""
Replaces 'explain' magic comments in the given program for a rule version of those magic comments.
@param str program:
@return:
"""
for hit in re.findall(
"(%!mute ((\-)?([_a-z][_a-zA-Z0-9]*(?:\((?:[\-a-zA-Z0-9 \(\)\,\_])+\))?)(?:[ ]*:[ ]*(.*)... | 8300ffca66fe8d6e5e38b605c6dad6cc90dacb18 | 655,096 |
def read_ds9(pfile):
""" Read ds9 region file, just grab the RA/DEC
circle(12:00:5.173,-29:58:50.149,10")
ellipse(12:00:00.554,-29:59:46.400,9.600",8.800",359.99987)
"""
fp = open(pfile)
lines = fp.readlines()
fp.close()
#
out = []
for line in lines:
w = line.split('(')
... | 635fe4f1806bebf787b2487c47d3ea0e4fe72566 | 655,097 |
def serialize_nested(session):
"""Serialize data using the nested mapper defined on this field.
:param session: Kim pipeline session instance
"""
if session.data is None:
session.data = session.field.opts.null_default
return session.data
# Grab the Mapper defined for the nested fi... | cc9966fbb06937cded1326f5ad641e47cfeff6b9 | 655,098 |
import re
def validate_user_data(user):
""" this funtion validates the user data """
user['username'] = user['username'].lower()
if user['username'] == '':
return {'warning': 'username is a required field'}, 400
# Check for empty email
elif user['email'] == '':
return {'warning'... | 38d6a48704f93bc6ab767a8f7eafa60964f30b30 | 655,099 |
def gvariant(lst):
"""Turn list of strings to gvariant list."""
assert isinstance(lst, list), "{} is not a list".format(lst)
content = ", ".join(
"'{}'".format(l) for l in lst
)
return '[{}]'.format(content) | fb98a4996981c9f20622cedb0c6e7eab11c1572f | 655,100 |
import requests
def req_post(url, dat):
"""
:param url:
:param dat:
:return:
"""
try:
return requests.post(url, json=dat, timeout=10)
except (requests.ConnectionError, requests.Timeout) as exception:
print("[x] No internet connection.")
return None | 8757e57a78394bc52f4140ef9d70d426f4d73e01 | 655,101 |
def aggregate(df, xvar: str):
"""Compute mean of xval column."""
groupedDf = df.select_dtypes('float64').groupby([xvar])
meanDf = groupedDf.mean()
cnt = groupedDf.size()
errDf = groupedDf.std().transform(
lambda x: x / cnt.astype('float64')
)
errNames = {x: x+'_err' for x in errDf.co... | 275b33047e48b5b70a377a7ef0f6fe5643d6cccd | 655,102 |
def compss_open(file_name, mode='r'):
# type: (str, str) -> object
""" Dummy compss_open.
Open the given file with the defined mode (see builtin open).
:param file_name: The file name to open.
:param mode: Open mode. Options = [w, r+ or a , r or empty]. Default=r.
:return: An object of 'file' ... | 040668276c54cb2799a36d639cfc2da2605b9677 | 655,103 |
import json
import requests
import random
def mapquest_single_location(location, key):
"""
find the MapQuest location json for a single location
Input: location Twitter location, check that it's not null before calling
key MapQuest developer key
Output: json ret... | a6039a16f804223fdb24612e55aae7adfb866383 | 655,104 |
def url_for(server, *args):
""" Generate versions REST url """
return "{}/v0/{}".format(server, "/".join(args)) | e06345d5e5bd4a50b3b7d4d5b84056c82811a7f5 | 655,105 |
def intersection(surface, rect):
""" Remove zone of out of bound from ROI
Params:
surface: image bounds is rect representation (top left coordinates and width and height)
rect: region of interest is also has rect representation
Return:
Modified ROI with correct bounds
"""
l_x = max(sur... | 82fd7c010e7fbd8e81eacdd95e8073b0b87d4837 | 655,106 |
def _build_headers(range_):
"""
:type range_: list
every split's range_
:rtype: dict
"""
headers = {"accept-encoding": '*',
"User-Agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.3; WOW64; Trident/7.0; \
.NET4.0E; .NET4.0C; .NET CLR 3.5.3... | 0337f312cd74de6da5ab060aa4efd7323de5eb45 | 655,109 |
import math
def _ceil(number):
"""Ceils the number in graph mode."""
return math.ceil(number) | 6944685832f9ccc2320445af518201284887a903 | 655,110 |
def can_view_cohorts(user):
"""To access Cohort views user need to be
authenticated and either be an admin, or
in a group that has the 'view cohorts' permission."""
return user.is_authenticated and user.has_perm('release.view_releasecohort') | 23c13e604e78a53e1a130a5bb12430d058276770 | 655,111 |
from typing import Counter
import math
def conditional_entropy(x, y):
"""
Calculates the conditional entropy of x given y: S(x|y)
Wikipedia: https://en.wikipedia.org/wiki/Conditional_entropy
:param x: list / NumPy ndarray / Pandas Series
A sequence of measurements
:param y: list / NumPy ... | 56af850404476a213222d2100737e708cf9ab4ca | 655,112 |
import os
import stat
def get_secret_token(token_environvar,
token_file,
logger):
"""
This loads the specified token file from the environment or the token_file.
"""
if token_environvar in os.environ:
secret = os.environ[token_environvar]
if... | f2082ec063ca0893ab47e3a1266ea38d62646ed7 | 655,113 |
def iss():
"""
``iss`` field for tokens
"""
return "localhost" | b9faee170fc1e77fc8a4e65f9f82af39e686c246 | 655,114 |
def parse_object(response, infotype):
"""
Parse the results of an OBJECT command
"""
if infotype in ('idletime', 'refcount'):
return int(response)
return response | 0c709296689b978030a824b8e7766607f1bc6ea2 | 655,115 |
def evaluate_error(model, test_gen, no_test_sam):
"""
DESCRIPTION: Evaluate the network performance
INPUT: The trained model, the test set generator,
number of testing images
OUTPUT: List of statistics about the performance of the model
"""
stats = model.evaluate_generator(test_gen, no_test_... | d76fcc9fffeee3bb79d399f728b8cb35432ec2e9 | 655,116 |
import re
def format_weibo(weibo): # , after_segment=False):
"""
对于话题进行格式化,统一成一样含义的话题
:param weibo:
# :param after_segment: 是否分词之后的微博
:return:
"""
# 微博话题还原
# if after_segment:
# pattern = re.compile('#[^#]+#')
# new_weibo = re.sub(pattern, lambda x: x.group(0).replace(... | 9008e61fd6673a0ddde226d7cb91c18abba24cc6 | 655,117 |
import torch
def get_valid_negative_mask(labels):
"""
To be a valid negative pair (a,n),
- a and n are different embeddings
- a and n have the different label
"""
indices_equal = torch.eye(labels.size(0)).byte()
indices_not_equal = ~indices_equal
label_not_equal = torch.ne(labels.unsqueeze(1), labels.unsqu... | 08c408ad4cec3ee2367b6224aaabf397f2c8eea1 | 655,118 |
def compoundInterestFutureValue(p, r, c, n):
"""Compound interest future value
Returns: future value
Input values:
p : principal
r : interest rate
c : number of compounding periods in a year
n : (c * t) , total number of compounding periods
"""
fv = (p * (1 + (r / c))) **... | 19f865d29c8dd541b7aba5e043babc81828340db | 655,119 |
import os
def gera_chave():
"""Gera a chave aes secreta"""
AES_tamanho_chave = 32
chave_aes_secreta = os.urandom(AES_tamanho_chave)
return chave_aes_secreta | 96a2e689461a07abc06caef044bf6081cf967657 | 655,120 |
import importlib
def reload_os_and_fitting():
"""Some tests patch os and need to reload the modules."""
os = importlib.import_module("os")
os = importlib.reload(os)
fit = importlib.import_module("..fitting", "freesas.subpkg")
fit = importlib.reload(fit)
return fit | 29fb35c0e08de7db1b4fa4b422d4e0ae506c7bac | 655,121 |
def signature(self):
"""
Returns the signature of the quadratic form, defined as:
number of positive eigenvalues - number of negative eigenvalues
of the matrix of the quadratic form.
INPUT:
None
OUTPUT:
an integer
EXAMPLES:
sage: Q = DiagonalQuadraticForm(Z... | b87114af527ae465a5f686ee403da357fc8e3115 | 655,123 |
def rgb_to_hex(r, g, b):
"""
Convert RGB color to an Hexadecimal representation
"""
return "%02x%02x%02x" % (r, g, b) | 4f5edefa2a1137e910b7cf20041667e59b04f700 | 655,124 |
def _filter_keys(item, keys):
"""Filters all model attributes except for keys
item is a dict
"""
return {k: v for k, v in item.iteritems() if k in keys} | 65c888bf372c5fabccfad913ff248a619370c2ca | 655,125 |
def str_to_bytearray(data):
"""
@type data: C{str}
@rtype: C{bytearray}
"""
# we could also do: return map(ord, data), but it's slower
return bytearray(data) | eb3a1a54c4daaa7c9ba7020a1218a052ba91abbf | 655,126 |
def binary_lookup(index, offsets):
"""
Given a character index, look up the index of it in the offsets. This will
be the number at which the next index is greater
"""
bottom = 0
top = len(offsets) - 1
if index > offsets[top]:
return top
while top - bottom > 1:
mid = ... | 924a24d8bbcba135911c58ff0ad166a352c7e137 | 655,128 |
def _make_number(ctx, param, value):
"""converts a number to float/int"""
if value:
try:
value = int(value)
except ValueError:
value = float(value)
return value | e5b5581b1df11cf909f9bae4fe3657d146823e8d | 655,129 |
import unittest
def _decorate_skip(method, reason):
"""unittest provides a built-in skip decorator that can be reused for
disabled test cases that do not match the filter criteria. It is a
parameterized decorator, so dynamic decoration syntax is convoluted
"""
return unittest.skip(reason)(... | 085552ffcf0aec1fbf23b42cf667242477871315 | 655,130 |
def enter_is_terminate(x):
"""This thing makes enter terminate the input."""
if x == 10:
return 7
else:
return x | 4b15da9718097ae9f9b10f1caa3192b94f2f4a60 | 655,131 |
import os
import sys
def should_do_replacements():
"""
Tell whether it is advisable to do version/author/email replacements.
"""
setup_dir = os.path.dirname(sys.argv[0])
# Don't do replacements if we're not running setup.py
# from the project directory
return setup_dir in [".", ""] | 026cad8d62544d1fcc04a11f2e06c619661c6d30 | 655,132 |
import random
def snp(sequence):
"""
Function takes a sequence string and introduces a single nucleotide polymorphism (SNP)
Randomly finds an index in the string and replaces the value at the index with a new
letter from the given alphabet. If the value is the same as the previous value, the
funct... | 37ad64080b02d36d204efa0fe18265aee12bb258 | 655,133 |
import csv
def load_training3(infile):
"""Load training data with normalized unigram count, hamming distance, and
query length.
Args:
infile: file name to load data from
"""
X = []
Y = []
with open(infile, 'r') as f:
reader = csv.reader(f)
for row in reader:
if reader.line_num == ... | 317d0e82781539ca7089c5552249104000d69715 | 655,134 |
def compute_whitespace(d):
"""Calculates the percentage of empty strings in a
two-dimensional list.
Parameters
----------
d : list
Returns
-------
whitespace : float
Percentage of empty cells.
"""
whitespace = 0
r_nempty_cells, c_nempty_cells = [], []
for i in ... | 9b137632654f54ba1fedfdc12dfca7f430b45679 | 655,135 |
def clean_whitespace(contents: str) -> str:
""" Return the given string with all line breaks and spaces removed.
For some reason our mock service returns a SOAP response with lots
of whitespace.
"""
lines = [line.strip(" \r\n") for line in contents.split('\n')]
return ''.join(lines) | 217220710bce413c46ec18ca4fc2680ae02bbc02 | 655,136 |
import time
import torch
from typing import OrderedDict
def load_model(model, model_file, is_restore=False):
"""Load model.
:param model: created model.
:param model_file: pretrained model file.
:param is_restore: set true to load from model_file.
"""
t_start = time.time()
if isinstance(m... | c949d44b6099c417f00e688f7f2bc12746963ca1 | 655,137 |
import re
def camel_case(words):
"""Convert a noun phrase to a CamelCase identifier."""
result = ''
for word in re.split(r'(?:\W|_)+', words):
if word:
if word[:1].islower():
word = word.capitalize()
result += word
return result | 4707e5c48f803c78ebd08a2b3099bc5b25cab0df | 655,138 |
def key(profile):
"""Get a sorting key based on the lower case last name, then firstname"""
components = profile["name"].lower().split(" ")
return " ".join([components[-1]] + components[:-1]) | 3615e439a249065eb5c428f417d7b4d0aa311d68 | 655,139 |
import random
def _find_external_v4_ip(config):
"""
Determines the external IPv4 address.
:type config: akanda.router.models.Configuration
:param config:
:rtype: str
"""
v4_id = config.external_v4_id
if v4_id:
return v4_id
else: # fallback to random value
return ... | ccf61e7c6e6f502e386b8a42a8341cc2e48d85b3 | 655,140 |
def insertion_sort(A, reverse = False):
"""Assumes A is a list of integers, by default reverse = False
Returns the sorted A in non-decreasing order if reverse = False,
and in non-increasing order if reverse = True.
****************************************
The complexity of the algorithm... | 01898d6f7836f3fdfd8be3a7d49becd9a1186cee | 655,141 |
def get_first_time(dao, order_field, **kwargs):
""" 最近的统计时间 """
row = dao.filter(**kwargs).order_by(order_field).first()
if row is None:
return None
#
attr = order_field
if attr[:1] in ['+', '-']:
attr = attr[1:]
return getattr(row, attr) | 5a9aaa63fd76c8afc42e939a32eeda44f22c6243 | 655,142 |
import importlib
def get_model(model_name):
"""
Return an instance of the model model_name.
Dynamic module discovery.
"""
module_name = 'strain.models.strain_' + model_name.lower()
model_module = importlib.import_module(module_name)
obj = getattr(model_module, model_name)
return obj | cc4d51cf050fc3b2f76f4206be8ebe152713fcf2 | 655,143 |
def impl_key_dict(value, priority=1):
"""to reduce duplicate code in configs.py and handcar_configs.py"""
return {
'syntax': 'STRING',
'displayName': 'Implementation Key',
'description': 'Implementation key used by Runtime for class loading',
'values': [
{'value': val... | eb336015f471326ba2d97098fb673554499261e7 | 655,144 |
import torch
def gap__forward(ctx, self, inputs):
"""Rewrite `forward` of GlobalAveragePooling for default backend.
Replace `view` with `flatten` to export simple onnx graph.
Shape->Gather->Unsqueeze->Concat->Reshape become a Flatten.
"""
if isinstance(inputs, tuple):
outs = tuple([self.g... | 2d6572db1fa0fcac445cdc27b09e4d664afeca1b | 655,145 |
import numpy
def get_time_mask(data, time_limits=(-numpy.inf, numpy.inf)):
"""
Get a mask given the time limits.
Parameters
----------
data: 1D Numpy array of floats
The time values
Returns
-------
mask: 1D Numpy array of integers
The mask
"""
mask = numpy.whe... | b9cb8ec23457f5fde477f65caf6177d8af596a9e | 655,146 |
def min_tss_dist(dist_seq):
"""
Find the TSS distance in `dist_seq` with minimum absolute value.
We prefer negative TSS distances because we prefer upstream SNPs.
That is to say, if the minimum absolute value in `dist_seq` is `n`,
and both `n` and `-n` are present in `dist_seq`, choose `-n`
... | 5d319206caae9e223d16bd5751756c26a46657cd | 655,148 |
import random
import json
def _retrieve_quote(json_filename):
"""
Retrieve a random quote entry from json_filename, very quickly,
without loading the entire file into memory
:param str json_filename: Name of .json file to open
:return: Tuple of the form: (str(quote_text), str(quote_author))
... | 5c36e812e9219acc7fabc6483f6773abfa76e473 | 655,149 |
import platform
import subprocess
def ping(host: str) -> bool:
"""Return if the host responds to a ping request.
:param host: The hostname to ping
:returns: True if an ICMP echo is received, False otherwise
"""
parameters = ['-n', '1'] if platform.system().lower() == 'windows' else ['-c', '1']
... | 368ae93d1ed8da13ac41eb3b393ba2c781d3c55c | 655,151 |
def compute_overdose_deaths(run, start_year, end_year, config, intervention):
"""Compute number of opioid overdose deaths from start_year to end_year.
Parameters
----------
run: whynot.dynamics.Run
Run object produced by running simulate for the opioid simulator
start_year: int
... | 308959e39e99e10bc78728bd262d47b7c16b17cc | 655,152 |
def _inverse_permutation_worker(permutation: list, items: list) -> int:
"""
The index of permutation in the Johnson-Trotter list of
permutations of elements in items.
"""
if len(permutation) == 1:
return 0
else:
n = len(items)
index = permutation.index(items[-1])
... | cbaeb23818e29280c3ebbfee52576260917232fb | 655,153 |
from typing import Set
def format_entities(entities: Set[str]) -> Set[str]:
"""
Remove
:param entity:
:return:
"""
result = []
for entity in entities:
if entity[-1] in [".", ",", "?", "!", ":"]:
entity = entity[0:-1]
entity = entity.replace("\n", " ")
if... | 24a5d0d49cf9fba2112145ad45ecdd8fbb8fb04f | 655,154 |
import os
def xdg_config_home():
"""Base directory where user specific config files should be stored."""
value = os.getenv('XDG_CONFIG_HOME') or '$HOME/.config/'
return os.path.expandvars(value) | a4c2dce794bb93d966e98999d16512458f9a1793 | 655,155 |
def make_ArrayOfData(param, factory):
"""Generates ArrayOfData if input is a dictionary for list of dictionaries"""
if isinstance(param, dict):
return factory.ArrayOfData([{'field': field, 'value': value} for field, value in param.items()])
elif isinstance(param, list):
data = [[{'field': fi... | 608943174f825344010342d05d3936dee9c7c929 | 655,156 |
def sequential_search(target, lyst):
"""
in()
顺序搜索
Returns the position of the target item if found, or -1 otherwise.
:param target:
:param lyst:
:return:
"""
position = 0
while position < len(lyst):
if target == lyst[position]:
return position
positio... | 9a686606dd70b95568a016f4155c6b9ae55efca0 | 655,157 |
import torch
def epipolar_residual_error(pts1, pts2, F):
"""
Args:
pts1, pts2: (B, N, 3)
F: (B, 3, 3)
"""
# # Version 1:
# F = F.permute(0, 2, 1) # Move transpose inside
# l2 = torch.bmm(pts1, F)
# l1 = torch.bmm(pts2, F.permute(0,2,1))
# dd = ((pts2*l2).sum(2))
#... | b14eb55fe017d4c3535628957cfd6bf42e698c8f | 655,159 |
def check_obs(idx, obs):
"""Check every term in every sequence of obs and see if any term is >= idx
or < 0. If true, return false. Otherwise return true.
"""
for o in obs:
for term in o:
if (term >= idx) or (term < 0):
return False
return True | d61086d5a90e794b284edd530c0f3a72e9cf49ab | 655,160 |
from dateutil.tz import tzlocal, gettz
def to_system_time(dt):
"""
Converts a timezone aware datetime object to an object to be used in the messagebus scheduler
:param dt: datetime object to convert
:return: timezone aware datetime object that can be scheduled
"""
tz = tzlocal()
if dt.tzi... | 82557530afbe30219da37d631d5cef21e9af316a | 655,162 |
import os
import pickle
def read_ellipsefit(objid, objdir):
"""Read the output of write_ellipsefit."""
ellipsefitfile = os.path.join(objdir, '{}-ellipsefit.p'.format(objid))
try:
with open(ellipsefitfile, 'rb') as ell:
ellipsefit = pickle.load(ell)
except:
#raise IOError
... | 7655c2d93d8597b0798f79e6a38aac46bd001482 | 655,163 |
import torch
def to_gpu(x):
"""Move `x` to cuda device.
Args:
x (tensor)
Returns:
torch.Variable
"""
x = x.contiguous()
if torch.cuda.is_available():
x = x.cuda(non_blocking=True)
return torch.autograd.Variable(x) | 3740f42fc3d642a5dcfaa603791817c81e74e7a3 | 655,164 |
import os
def create_preproc_filenames(subjects_dir, subject_id, in_T1s):
"""
This function..
:param subjects_dir:
:param subject_id:
:param in_T1s:
:return:
"""
# Create output filenames
inputvols = list()
iscaleout = list()
ltaout = list()
orig_dir = os.path.join(sub... | a5bd9cda8f27e6202fb51bd5e8934cbf066e31ea | 655,166 |
def adj(a):
"""
Calculates the adjugate of A via just swapping the values.
The formula is [[a,b],[c,d]] => [[d,-b],[-c,a]]
:param a: the matrix A(2x2)
:return:
"""
B=[[0,0],[0,0]]
B[0][0]=a[1][1]
B[0][1]=-a[0][1]
B[1][0]=-a[1][0]
B[1][1]=a[0][0]
return B | 4fa87610f32f21069f9d7051e9d1cbfbca46b611 | 655,167 |
def invertTreeIterative(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
node_list = [root]
while node_list:
node_pop = node_list.pop()
if node_pop:
temp_node = node_pop.left
node_pop.left = node_pop.right
node_pop.righ... | db8c33b78b0dd64781ec703b3d0de6b78ff3ebf7 | 655,169 |
import math
def floor_with_place(value, keep_decimal_place):
"""
無條件捨去小數點後 N 位
Args:
value(float): 數值
keep_decimal_place(2): 要保留到小數點第幾位, e.g 2,表示保留到第二位,後面的位數則無條件捨去
"""
scale_value = math.floor(value * pow(10, keep_decimal_place))
result = scale_value / pow(10, keep_decimal_place)
return result | e36875b424d99a928aa08e4758a28f2acdaf8a2a | 655,170 |
def command_composer(args, options, use_long=True):
"""Compose arguments and options.
Parameters
----------
args : list or tuple
Iterable of strings that will be joined on a space.
options : list
List of 3 element tuples where the elements are the following:
* short_opt... | 15a4d7f0899e7ee835e639860e09032f597ba882 | 655,172 |
import copy
def merge(s):
"""
Given a nesting of TOML dictionaries, return a flat list of each
scheme in `s`. This applies the inheritance used is configuration
files so that each scheme has each attribute fully resolved.
"""
def settings_and_subschemes(d, defaults):
settings, subs = {... | 4d0374476effcae867d6d4b8f92baffe439459fe | 655,173 |
from pathlib import Path
import jinja2
def form_render(path: str, **kwargs) -> str:
""" Just jinja2 """
file_text = Path(f"codegen\\templates\\{path}").read_text()
template = jinja2.Template(file_text)
return template.render(**kwargs) | d343d1ca769bc3bd17775af3786d163e35edae24 | 655,174 |
def get_config_of(tests, test_name):
"""
Find generic values of test
"""
for test in tests:
if test.name == test_name:
try:
return test._test_case._config # pylint: disable=protected-access
except AttributeError:
return test._config # pyl... | 9ee8d34829d6258988be11d01b6a0d745164f1ef | 655,175 |
def ci_equals(left, right):
"""Check is @left string is case-insensative equal to @right string.
:returns: left.lower() == right.lower() if @left and @right is str. Or
left == right in other case.
"""
if isinstance(left, str) and isinstance(right, str):
return left.lower() == right.lower()
... | d3b927b196b3a1e0e9be8562f78b92191566a668 | 655,176 |
def get_trig_val(abs_val: int, max_unit: int, abs_limit: int) -> int:
"""Get the corresponding trigger value to a specific limit. This evenly
devides the value so that the more you press the trigger, the higher the
output value.
abs_val - The current trigger value
max_unit - The maximum value to re... | c965594555fb28ba3c85713d538ad7c47abdd705 | 655,178 |
def transpose(g):
"""Fonction qui, à l'aide d'une grille sous forme de liste contenant des listes, retourne une nouvelle grille
pour laquelle on a inversé les colonnes et les lignes de la grille d'origine.
Paramètre(s):
- g list: Grille à transposer sous la forme de liste de liste. La liste parente... | b9f7be8b0c6e1699230be7b238113ea764c90735 | 655,179 |
import random
def complete(subjects, seed=None):
""" Create a randomization list using complete randomization.
Complete randomization randomly shuffles a list of group labels. This
ensures that the resultant list is retains the exact balance desired.
This randomization is done in place.
Args:
... | 60cadade7b6d00b027bfc2a5524f664a67d2f879 | 655,181 |
def error_responses_filter(responses):
"""
:param responses:
:return:
"""
return [each for each in filter(lambda r: r.status_code >= 400, responses)] | 8c72e82b0d394f3405e7a7927152948733dc462e | 655,182 |
def ol(n):
"""olabel"""
return n + 1 | 2153084289782ba61930839cbb158206451b936f | 655,183 |
import platform
def GetOSPlatform():
"""Get OS platform."""
try:
return platform.system().lower()
except IOError:
raise AssertionError('Linux OS release not available.') | 886cfabae3ab0dd97aa558d64842fdd8996eb636 | 655,184 |
from typing import Optional
from typing import List
import os
import random
import sys
def _get_seeds(n_nightly_runs: int, seed: Optional[int]) -> List[int]:
"""
Gets a list of seeds based on environment variables and the seed function argument.
If it is specified to both run the test multiple times and r... | 33346651636702838b2372019418e7009d6b4128 | 655,186 |
def format_time(seconds):
"""seconds: number
returns a human-friendly string describing the amount of time
"""
minute = 60.00
hour = 60.00 * minute
if seconds < 30:
return f'{int(seconds * 1000)} ms'
if seconds < 90:
return f'{round(seconds, 2)} seconds'
if seconds < 9... | adc5a62969a15d79cdb39f96c250bf2d94a02b75 | 655,187 |
import sys
def is_in_ipython():
"""Funktionen returnerar True om scriptet kors under ipython
"""
return "IPython" in sys.modules | ca1c0037e2ff7ba9f22f4b2a3d303fde5e8c86f5 | 655,188 |
def str_to_int(num_str):
"""
Converts string into number.
Parameters:
num_str: a string to be converted into number
Returns:
numeric value of the string representing the number
"""
if num_str.lower().startswith('0x'):
return int(num_str[2:], 16)
return int(num_str... | 460bb299eee9f5dbdc7528db8249af54956c0a4a | 655,189 |
def D(x, y):
""" Converts D/data codes to bytes.
Does not result in 8b10b data; requires explicit encoding.
See the USB3 / PCIe specifications for more information.
"""
return (y << 5) | x | 0a9613504450ccf882a40ea5d03c648985d92b0a | 655,190 |
from typing import List
def scale_prev_up_to_1(prev_vals: List[float], fraction: float):
"""
Apply a percentage to the previous value, saturating at one or zero
"""
val = prev_vals[-1] * fraction
if val > 1:
return 1
elif val < 0:
return 0
else:
return val | 2a7b8946c4d12595e1f633fbb3c7789b07f97205 | 655,191 |
def checkIfExist(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
A=arr
if A.count(0) > 1:
return True
S = set(A) - {0}
for a in A:
if 2*a in S:
return True
return False | 29e5795f3b67f5ee83a120cef49cb853943d3800 | 655,192 |
def file_len(filepath):
"""
Static function to return the number of lines in a given file
:return:
"""
num_lines = 0
with open(filepath, encoding="utf-8") as f:
for i in f:
num_lines += 1
return num_lines | 5708287b3dc92cf9d21d095fcc606b8aa392c197 | 655,193 |
def generate_class_label_presence(data, state_variable ="target"):
"""
generates class label only for presence on a copy of data using only the columns
Removes: Pause and merges 'Step' and 'Stand' to same class
"""
r_data = data.copy()
r_data = r_data[ ~r_data['target'].str.contains("Pause") ]
... | 8a118145b5bb09a02af9302705f3b8db837bc4e8 | 655,194 |
def manhattan_distance(start, end):
"""Calculate the Manhattan distance from a start point to an end point"""
return abs(end.x - start.x) + abs(end.y - start.y) | 16dfa01c72a883106e8db0b9a41b274d4e38a37a | 655,195 |
def parse_alignment(alignment):
"""
Parses an alignment string.
Alignment strings are composed of space separated graphemes, with
optional parentheses for suppressed or non-mandatory material. The
material between parentheses is kept.
Parameters
----------
alignment : str
The a... | 8069f798238d917f09a7e894ce21c8c1213b5faa | 655,196 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.