content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def node_connectivity_degree(node, network):
"""Get the degree of connectivity for a node.
Args:
node ([type]): [description]
network (class): A network composed of nodes (points in space) and edges (lines)
Returns:
[type]: [description]
"""
return len(
netw... | 7c492abc7bd146ff1bbb0ac8c56aa389b2f23f42 | 680,248 |
def quantify(iterable, pred=bool):
"""Count how many times the predicate is true.
:param iterable: source of values
:param pred: the predicate whose result is to be quantified when applied to
all values in iterable. Defaults to bool()
"""
# quantify([2, 56, 3, 10, 85], lambda x: x... | a9c8b611bf7f38aaf6d4e0f1fbbb6bd0a1b32073 | 680,249 |
def ensure_all_tokens_exist(input_tokens, output_tokens, include_joiner_token,
joiner):
"""Adds all tokens in input_tokens to output_tokens if not already present.
Args:
input_tokens: set of strings (tokens) we want to include
output_tokens: string to int dictionary mappi... | bb73fd901eccab0109d27f5d9eb8ed4f881833e9 | 680,250 |
import asyncio
def async_return(result):
"""Mock a return from an async function."""
future = asyncio.Future()
future.set_result(result)
return future | 8dcf55b5fc1ded019c9bec668d17f919215b09c7 | 680,251 |
def get_ttylog_lines_from_file(ttylog):
"""Read from ttylog. If lines have '\r' at end, remove that '\r'. Return the read lines"""
ttylog_file = open(ttylog,'r',errors='ignore', newline='\n',encoding='utf-8')
ttylog_read_data = ttylog_file.read()
#Replace escaped double qoutes with qoutes
ttylog_rea... | 7c900d11f9d872ef2c23bb6932724ac5a4c3b501 | 680,252 |
def _generate_and_write_to_file(payload, fname):
"""
Generates a fake but valid GIF within scriting
"""
f = open(fname, "wb")
header = (b'\x47\x49\x46\x38\x39\x61' #Signature + Version GIF89a
b'\x2F\x2A' #Encoding /* it's a valid Logical Screen Width
... | 8e3834dbbba64068ec17b2b7a21c5c9c3b1c518e | 680,253 |
from pathlib import Path
def read_input_file(input_file_path):
""" read the input file and convert the contents
to a list of ints """
p = Path(input_file_path)
with p.open() as f:
data = list(map(int, f.readlines()))
return data | 5b3352ff1bdd0ab895e69a43f20100b92ad86f35 | 680,254 |
def CalculateInteraction2(dict1={}, dict2={}):
"""
Calculate the two interaction features by combining two different
features.
Usage:
res=CalculateInteraction(dict1,dict2)
Input: dict1 is a dict form containing features.
dict2 is a dict form containing features.
... | 3e868098369d1d57523194e816d192cb2566fa47 | 680,255 |
def flat_conf(conf):
"""Flats a configuration iterable to a list of commands ready to concate to """
results = []
for field, value in conf:
results.extend(["--conf", field + "=" + value])
return results | e248394e302fed9f992d19f828278f53da30687f | 680,256 |
def variable_to_jsonpath(p):
"""Converts a expression variable into a valid JSON path starting with $."""
# replace JSON_ with $ and _ with .
return p.var.replace('JSON_', '$').replace('_', '.') | 92466ade3d97b31471e8b2f78199bc5c8ae0f33b | 680,257 |
from datetime import datetime
def get_suffix():
"""
Generates a filename suffix using the currrent datetime.
Returns
-------
str
String suffix
"""
return datetime.now().strftime("%d-%m-%Y_%H-%M-%S") | c0a26a81c23f1eb8191c528bc6cbb4231b38874b | 680,258 |
def check_overlap(peak1, peak2):
"""check_overlap checks if a peak overlaps, if they do, it returns 0, if not, it returns 1 if the first given peak is greater than the second, or -1 if otherwise
Args:
peak1 (tuple): start, end tuple which constitutes a peak
peak2 (tuple): start, end tuple which... | fc74421f275a416061ccebdaf575804ca3f954c5 | 680,259 |
def format_tracks_picks(tracks, picks):
"""Formats tracks as a list, with picks in bold."""
return "\n".join(
[
f"<li><b>{track}</b></li>"
if picks is not None and index in picks
else f"<li>{track}</li>"
for index, track in sorted(tracks.items())
]... | 365aa3ddabf56cc4c229b4995bc29239f19551b9 | 680,262 |
def remove_bottom(pnts, gt_box, bottom):
"""
Args:
* `pnts`: Lidar Points
* `gt_box`: The 3D bounding box of the object
* `bottom`: A height threshold, deciding which points to keep\n
Return:
`pnts` whose heights are larger than -dz/2 + bottom, where dz is from the `gt_box`.
... | 3f03276134db713e587c9e4145c21b85543f20c5 | 680,263 |
def extractPajamaDays(item):
"""
Parser for 'Pajama Days'
"""
return None | dc6e614fc51b83bb5e20ba5cddf4be5dd59f9f76 | 680,264 |
def abcproperty(index):
"""Helper function to easily create Atom ABC-property."""
def getter(self):
spos = self.atoms.get_scaled_positions()
return spos[self.index][index]
def setter(self, value):
spos = self.atoms.get_scaled_positions()
spos[self.index][index] = value
... | 2e84f21abc3b9da81716b07bba149e598dcfec8d | 680,265 |
def check_qfac(nifti, array):
"""
See https://vtk.org/pipermail/vtk-developers/2016-November/034479.html
"""
qfac = nifti.header['pixdim'][0]
if qfac not in (-1, 1):
raise ValueError(f'Unknown qfac value: {qfac}')
elif qfac == -1:
array = array[..., ::-1]
return array | 17827d50e12b628a3a3b4737acc4492639337993 | 680,266 |
from datetime import datetime
def _convert_to_datetime(unix_timestamp):
"""
Converts a unix timestamp to a human readable date/time
:param float unix_timestamp: A unix timestamp
:return: A date/time in the format YYYY-mm-dd HH:MM:SS
:rtype: str
"""
try:
unix_timestamp = float(uni... | be5aa2d95729c0cc779c232db76acebbc03f8c95 | 680,267 |
import pickle
def read_rv_data(in_dir):
"""Read radial-velocity pickle file."""
pickle_in = open(in_dir, 'rb')
all_rv_data = pickle.load(pickle_in)
pickle_in.close()
return all_rv_data | 70d3107c779cc45be0be60c9ada192f1501aad93 | 680,269 |
def _extract_username(request):
"""
Look for the "username" in a request. If there is no valid username we
will simply be throttling on IP alone.
"""
return request.POST.get("username", "notfound").lower() | 79641a2d6721af21ce5eb1bbeafe0cc387616adb | 680,270 |
import subprocess
def needs_maas_dns_migration():
"""Determines if the MAAS DNS ocf resources need migration.
:return: True if migration is necessary, False otherwise.
"""
try:
subprocess.check_call(['grep', 'OCF_RESOURCE_INSTANCE',
'/usr/lib/ocf/resource.d/maas... | 94397e3d4d1a0f4e87b36338b0c2e7590770093e | 680,271 |
def transistor_power(vcc_max, i_out, r_load, r_set):
"""Calculate power loss in the transistor."""
r_tot = r_load + r_set
# Find point where power is maximum
max_pwr_i = vcc_max/(2 * r_tot)
load_rdrop = max_pwr_i * r_tot
v_trans = vcc_max - load_rdrop
return max_pwr_i * v_trans | b114de9ec8adc28f0728df77dfe935d80d8d245d | 680,272 |
def read_list(sents, max_chars=None):
"""
read raw text file. The format of the input is like, one sentence per line
words are separated by '\t'
:param path:
:param max_chars: int, the number of maximum characters in a word, this
parameter is used when the model is configured with CNN word en... | 6fdcb4145479624cfb7643cc8c9f17351e0f4a15 | 680,273 |
from typing import List
import time
def tmp_path(base: str, _time_stamp: List[int] = []) -> str:
"""Get a temporary path containing a time stamp."""
if not _time_stamp:
_time_stamp.append(int(time.time()))
return f"{base}{_time_stamp[0]}" | 26041b4c1377048e97a5587ff12c27e468ecd9cf | 680,274 |
import torch
def compute_u1_plaq(links, mu, nu):
"""Compute U(1) plaqs in the (mu,nu) plane given `links` = arg(U)"""
return (links[:,mu] + torch.roll(links[:,nu], -1, mu+1)
- torch.roll(links[:,mu], -1, nu+1) - links[:,nu]) | b93191e78c51fbc197f9a463bfd48b821e914cf1 | 680,275 |
import os
import sys
def _get_stripper(paths):
"""Returns a function to strip common path prefixes.
There are 3 kinds of paths:
- relative paths
- absolute paths
- absolute paths in stdlib
"""
if not paths:
return lambda f: f
stdlib = os.path.dirname(os.__file__)
# Find the common root f... | d6803e62180cecca5955f53beae348b9b70b670b | 680,276 |
def is_error_response(res):
"""
check the status code of http response
:param res: http response
:return: True if the status code less than 200 or larger than 299;
False if the status code is between 200 and 299
"""
if res is None:
return True
if res.status_code < 200 or... | fb4153acb3efac0ec93e01b6e8ef5a7c02d07218 | 680,277 |
def id_for_label(value):
"""generate a test id for labels"""
return f"labels->{value}" | 4aa16dd2b50f33a86b21e8e723170c7ff8e44594 | 680,278 |
def get_content(*filename:str) -> str:
""" Gets the content of a file or files and returns
it/them as a string
Parameters
----------
filename : (str)
Name of file or set of files to pull content from
(comma delimited)
Returns
-------
str:
Content from the fi... | 5d19f26bd14200d9a71d2f246014bf7a56f5c7a5 | 680,279 |
def get_index(fields, keys):
""" Get indices of *keys*, each of which is in list *fields* """
assert isinstance(keys, list)
assert isinstance(fields, list)
return [fields.index(k) for k in keys] | fcaab2a055c223b29689fe6175212de480861288 | 680,280 |
def crop(image, bbox):
""" Crops the Bbox(x,y,w,h) from the image. Copy indicates to copy of the ROI"s memory"""
return image[bbox.y : bbox.y + bbox.h, bbox.x : bbox.x + bbox.w] | f6b295924b923fadf5584b924601c703b6801e44 | 680,282 |
import os
def _has_src_file_changed(src, dst):
"""
Return true if src is newer than dst, or if dst doesn't exist.
"""
if not os.path.exists(src) or not os.path.exists(dst):
return True
return os.stat(src).st_mtime > os.stat(dst).st_mtime | 0ea7e62b93ea27637e95989cd8417d816de6b32b | 680,283 |
def client(api_client):
"""We are testing path that doesn't match mapping rule so we need to disable retry"""
assert api_client().get("/get").status_code == 200
return api_client(disable_retry_status_list={404}) | 0a855e9fbfc64de9c90c02c03acebd7720ed933a | 680,285 |
import attr
def _style_columns(columns):
"""Generate a list of column styles given some styled columns.
The 'Table' object in Grafana separates column definitions from column
style definitions. However, when defining dashboards it can be very useful
to define the style next to the column. This functi... | 2ea6925f0508a950e7e61739b5cc6d5126ed7a7a | 680,286 |
def gen_state_encoding(population_size):
""" @author = Huy """
state_encoding = [0, ]
for i in range(1, population_size):
state_encoding.extend([i, -i])
return state_encoding | 4d8abed3b0962dab1c470387f411e7fd2e6c3852 | 680,287 |
import os
def get_labels_list(labels_dir):
"""从指定文件夹中找出所有的标签,并返回一个标签列表。
Arguments:
labels_dir: 一个字符串,是所有图片标签文件存放的路径。
Returns:
labels_list: 一个列表,包含了文件夹内所有图片标签的名字,并且每个标签的名字都是其
完整的文件路径。
"""
labels_list = []
for dir_path, _, labels_name in os.walk(labels_dir):
... | f3ee2408ef41583553229e7e62c834e6ed1e1a25 | 680,288 |
def _list_difference(l1, l2):
"""list substraction compatible with Python2"""
# return l1 - l2
return list(set(l1) - set(l2)) | e10890c005ed27fc40b4251ac37b57dc365b20d7 | 680,289 |
def convert_to_minotl(outline, indent = 4, curr_indent = 0):
"""Converts to a standard minotl format"""
lines = []
for i in outline:
if type(i) == str:
lines.append("%s%s" % (curr_indent * " ", i))
else:
lines.append("%s%s" % (curr_indent * " ", i[0]))
lin... | 3485e04ec83865d47def1c00e8aeb2e84dc56d01 | 680,290 |
def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
num1:
The first number to find the lcm for
num2:
The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
while True:
if bigger % num1 == 0 and bi... | a307e9fdb391dc46dbb1e82c1c88890562304cd1 | 680,291 |
def parse_txt_function_def(function, function_names, function_parameters):
"""
Helper function that parses the function definition of a neutron problem
and returns the function name and parameters.
@param function :: neutron function definition string
@param function_names :: array of names of the ... | 70a5dd1668df926c9df073c0cb501f82442b94d2 | 680,293 |
import subprocess
def _get_changed_files(base_branch):
"""
Get list of changed files between current branch and base of target merge branch
"""
# Get file changes between branch and merge-base of specified branch
# Not combined to be Windows friendly
base_commit = subprocess.check_output(
... | 51b623370b81dc21940df33a10fca2252b25912a | 680,294 |
def tupleit(lst: list) -> tuple:
"""Cast all lists in nested list to tuple."""
return tuple(map(tupleit, lst)) if isinstance(lst, list) else lst | e089aba1da3d92604547182366dd01c483b071ec | 680,295 |
def get_lista_candidatos(filename=None):
"""
Retorna uma lista de candidatos e ids
"""
candidates = []
if filename is None:
filename = '../../data/external/ListaCandidatos.csv'
with open(filename) as fl:
for line in fl.readlines():
candidates.append(line.split(','))
... | 99de1e3e6824c83af5fc7c4d7c3363cc2a14545d | 680,296 |
import importlib
def find_type_object(type_name):
"""Try to find the type object given the name of the type.
Deals with cases such as `argparse.ArgumentParser` where a module needs to
be imported before we can find the correct type object. If the type object
cannot be found, a `NameError` is raised.
... | bdb748be96bb755de372343eb463f03c20f13bf8 | 680,297 |
def add(x, y):
"""Add two coordinate pairs."""
return (x[0] + y[0], x[1] + y[1]) | ab900b9d683bd9215a35879f8bc3425c0e94e956 | 680,298 |
def is_prime(a):
""" 素数判定プログラム(フェルマーの小定理) """
a = abs(a)
if a == 2:
return True
if a < 2 or a & 1 == 0:
return False
return pow(2, a-1, a) == 1 | 3c46c3d26f251782dad4e34368e178d3147b3727 | 680,299 |
import itertools
def get_permutations(a):
"""
get all permutations of list a
"""
p = []
for r in range(len(a)+1):
c = list(itertools.combinations(a,r))
for cc in c:
p += list(itertools.permutations(cc))
return p | 3e3b71eeff6d29b60de28b38a524b1b07655048d | 680,300 |
from typing import Dict
from typing import Any
from typing import List
def collect_anchors_from_index(object_index, field_name: str):
"""Get text anchors out of an index of terms or enactments."""
result = []
for key, value in object_index.items():
if value.get("anchors"):
anchored_obj... | 5d27d88fa6a5f5bce174fcab8381fe2b0b33e093 | 680,302 |
from pathlib import Path
import subprocess
def count_number_of_reads(filename: Path) -> int:
""" Returns the number of reads in a fastq file."""
if filename.suffix == '.gz':
command = f"zcat {filename}"
else:
command = f"cat {filename}"
process = subprocess.Popen(command.split(), stdout = subprocess.PIPE)
ou... | 506181fb092e88f4c4d712022437bf5aa5df0fb9 | 680,303 |
import os
def security(test=os.environ):
"""
Default values are generally rendered using repr(),
but some special cases -- like os.environ -- are overriden to avoid leaking sensitive data.
"""
return False | 8ce33a24d3786bacde544ec8051163080551d97d | 680,304 |
from datetime import datetime
def fm_string(dt_string, millisecond=False):
"""
Input a date string and returns a datetime object.
"""
if millisecond:
return datetime.strptime(
dt_string, '%Y/%m/%d %H:%M:%S.%f')
else:
return datetime.strptime(
dt_string, '%Y/... | 7d4856e86cf24088c4ca7193caca0b2f3956ec0f | 680,305 |
def list2cmdline(seq):
""" Extended version of list2cmdline from subprocess.
Additional conditions sufficient to wrap argument with double quotes are added:
* argument contains parenthesis.
"""
result = []
needquote = False
for arg in seq:
bs_buf = []
# Add a space to se... | e4fcd72c7ca39f2df87af87548d9ef08b1dcf813 | 680,306 |
def density_matr(C, F=2):
""" Computes the density matrix ρ
Uses the expression ρ_γδ = Σ_j C*_jγ C_jδ
"""
D = (C.conj().T[:, :F]) @ (C[:F, :]) # slightly faster (1.6 µs < 2.5 µs)
return D | 1c7ac8ffd8f90f6126ff0996466d57e2295d241b | 680,307 |
def _is_weekend(date):
"""Returns whether the date is a weekend."""
return date.isoweekday() in (6, 7) # Saturday, Sunday | 71074d8b7e7e0d1f9a8d8e7c3f608a0f1b91ed9b | 680,308 |
import math
def _selection_size_heuristic(num_samples):
"""Return size of mini-batch, given size of dataset."""
# Incrase size of mini-batch gradually as number of samples increases,
# with a soft cap (using log).
# But do not return size larger than number of samples
return min(num_samples,
... | 605694af4875ac295ae9dea63b1ebda4308c038a | 680,309 |
def get_learning_rate(args, current, best, counter, learning_rate):
"""If have not seen accuracy improvement in delay epochs, then divide
learning rate by 10
"""
if current > best:
best = current
counter = 0
elif counter > args.delay:
learning_rate = learning_rate / args.lr_div
c... | 4e7ad1f7d905e3386ae8f500e3ec1cdb1af35471 | 680,310 |
import hashlib
def generate_md5(unicode):
"""
Generate an MD5 hash
Args:
unicode (bytes): Unicode bytes representing the string you want to be hashed
Returns:
str: An MD5 hash (hex characters)
"""
hasher = hashlib.md5()
hasher.update(unicode)
return hasher.hexdigest() | ecee642ca54ddf87d27d0d495395770d78e8fd78 | 680,311 |
def standardize_channels(X):
""" takes N x Channel x D data matrix, and for each row,channel
(n \in N and c \in Channel), divides X[n,c] by std(X[n,c])
"""
Xstd = X.std(axis=2)
Xstandardized = X / Xstd[:,:,None]
return Xstandardized | 98a0423c00031f01e6b5b719adef24b624a8ba6b | 680,312 |
import math
def factors_of(x):
"""Returns a set of tuples of factors of x.
Examples
--------
>>> factors_of(12)
{(1, 12), (2, 6), (3, 4)}
>>> factors_of(20)
{(1, 20), (2, 10), (4,5)}
"""
factors = set()
sqrt_x = math.sqrt(x)
if sqrt_x == int(sqrt_x):
factors.add... | 1b00d8292193a0cb16616f34f16154361c5b0dfc | 680,313 |
def userAgentProductTokens(user_agent):
"""
Parse an HTTP User-Agent header to extract the product tokens and ignore
any parenthesized comment strings in the header.
@param user_agent: text of User-Agent header value
@type user_agent: L{str}
@return: list of product tokens extracted from the h... | f896b20ca6c30a6f96469e38597dfbbf38238ac7 | 680,314 |
import math
def uv(sped, drct2):
"""Convert to u,v components."""
dirr = drct2 * math.pi / 180.00
s = math.sin(dirr)
c = math.cos(dirr)
u = round(-sped * s, 2)
v = round(-sped * c, 2)
return u, v | 0e1bacf73ec88e58ee495a1932fe24f6df0993bd | 680,315 |
import itertools
import pandas
def _get_cut_data(ZZ, leaf_data, groups, bounds_min):
"""Return data of cut lines.
Parameters
----------
ZZ : pandas.DataFrame
leaf_data : pandas.DataFrame
groups : list[int]
bounds_min : float
Returns
-------
df : pandas.DataFrame
"""
Z... | 4b4a0acd785fd6256571cdf71b37dfc6ce4b9c44 | 680,316 |
def getfmt(n,dtype ="d"):
"""
Generates the binary format n dtype
defualts to double
@param n: number of particles
@param dtype: data type
returns the format string used to decode the binary data
"""
fmt = ""
fmt += dtype
for i in range(n):
... | a81ad1dac80d01fdcf809588d032ed1208333b37 | 680,317 |
def clean_timestamp(timestamp, format=False):
"""
used to remove unwanted characters from the overly long timestamp in the json data of a tweet
eg: timestamp comes in as 'Thu Dec 17 13:44:24 +0000 2020' and for now we only want 'Thu Dec 17 13:44'
"""
cleaned_timestamp_list = str(timestamp).split(' ... | 5fc1846f411ea8379dccf45f0770b946c718002b | 680,318 |
import torch
def transform_tensor_by_dict(tensor, map_dict, device="cpu"):
"""
Given a tensor of any shape, map each of its value
to map_dict[value].
:param tensor: input tensor
:param map_dict: value mapping dict. Both key and value are numbers
:return: mapped tensor, type is FloatTensor
... | 2bc6db21c579dea88b2b0612f80697797ab3deeb | 680,319 |
def brier_score_calc(
classes,
prob_vector,
actual_vector,
sample_weight=None,
pos_class=None):
"""
Calculate Brier score.
:param classes: confusion matrix classes
:type classes: list
:param prob_vector: probability vector
:type prob_vector: python list o... | f04d92d748befdf41b99c98580002a38ca9f1a43 | 680,320 |
def connection_callback(isolation_level=None,
read_only=None,
deferrable=None,
application_name=None,
inherit=None):
"""
Decorator for functions used in :meth:`IConnectionManager.open_and_call`.
When the functio... | 2e043fa57e139a098ed41c4a4b4a25d2d50a6bcb | 680,321 |
def synonym_normalisation_4_genia(term_str):
"""
synonym + inflectional(simply lemmatization replacement) normalisation for GENIA dataset evaluation
this method applies to the surface form of both gs term ('concept.txt') and term candidate before further normalisation
:param term_str:
:return:
... | 207601e839e83057460d7535e1941b5335153f94 | 680,322 |
import os
import re
import logging
def read_names_dmp(infile, outdir):
"""
Reading names.dmp file
"""
outfile = os.path.join(outdir, 'names.dmp')
regex = re.compile(r'\t\|\t')
regexp = re.compile(r'^[^_]+_|_')
names_dmp = {}
logging.info('Reading dumpfile: {}'.format(infile))
with... | c63f33ef5fdecac5b29f20bd57895379436cd305 | 680,323 |
def _generate_variable_name(variable_counter):
"""
Generates a unique variable name.
"""
return "v{}".format(variable_counter.next()) | 667ff33cee4d6a42547e078737d265d9dd147dc6 | 680,324 |
def null_padded(string, length):
"""
Force a string to a given length by right-padding it with zero-bytes,
clipping the initial string if neccessary.
"""
return bytes(string[:length] + ('\0' * (length - len(string))), 'latin1') | f39bb45b1dac9f901ae1acb24903eb43759436cd | 680,325 |
def ReadText():
"""
Read the text from "movies.txt"
and returns it as lines of text
Keyword argument:
Return- The text from "movies.txt"
"""
with open("movies.txt") as text:
linesOfText = text.readlines()
return linesOfText; | ac0d8d3ab5aa56642d1b6ba36a67cb14e1609b81 | 680,326 |
def get_size(rscript):
"""PARSES the model R file that is generated by macs2, and instead
of making an R script, it translates it to a python dictionary: values"""
values = {}
with open(rscript) as model:
for line in model:
if line.startswith("p <- "):
#CONVERT to py... | 498ae0d89618f27138e2273f13b8d557d534e45f | 680,327 |
from typing import Dict
def get_border_width(width: int) -> Dict[str, int]:
"""Replicates border_width parameter from Gtk3, by producing a dict equivalent margin parameters
Args:
width (int): the border width
Returns:
Dict[str, int]: the dict with margin parameters
"""
return dic... | b29dbbf0fcd49b6ac1abfa1439ba7a81c8651ca6 | 680,328 |
import os
def remap_gpu_devices(in_device_ids):
"""
Working limitation for CUDA
:param in_device_ids: real GPU devices indexes. e.g.: [3, 4, 7]
:return: CUDA ordered GPU indexes, e.g.: [0, 1, 2]
"""
os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(map(str, in_device_ids))
return list(range(le... | a29cfcfc5d9dbe26396adb2390fb744e324fe6dd | 680,329 |
import pathlib
def checkFile(filename):
"""
Check whether file is present or not
Parameters
----------
filename: Path of the file to check
Returns
-------
"""
return pathlib.Path(filename).is_file() | de075b05369b88541176b1a7c39fff3cadcf07eb | 680,330 |
def digram_filter(candidates):
"""Remove unlikely letter pairs from permutations
Args:
candidates (set): permutations
Returns:
(set): permutations without digrams
"""
filter_set = set()
rejects = ['dt', 'lr', 'md', 'ml', 'mr', 'mt',
'mv', 'td', 'tv', 'vd', 'vl', ... | a428a37b60bad9d7550f8b7b7815c791a4f00e59 | 680,331 |
def nordic2Assoc(data, arrival_id, origin_id):
"""
Function for converting a nordic file into a Assoc string
:param NordicData data: NordicData object to be converted
:param int arrival_id: arrival id of the assoc
:param int origin_id: origin id of the origin
:returns: assoc string
"""
... | 9eb361a83bfd76458c0c74d9ba4ef68f884ee8b9 | 680,332 |
import argparse
def parse_arguments():
"""Parse arguments for real time demo.
"""
parser = argparse.ArgumentParser(description="Amvoc")
parser.add_argument("-i", "--input_file", required=True, nargs=None,
help="File")
return parser.parse_args() | a3cc554e89c703007f5c0a0ffb79eb4bfc5af2fb | 680,333 |
from typing import Counter
def top_senders(msgs, limit=20):
"""Highest number of messages sent
"""
return Counter([m['user'] for m in msgs]).most_common(limit) | a7793c12de157a84ae9e7c1fc2b19c758f4be870 | 680,334 |
def filter_dataframe(df, column, value):
"""Filter DataFrame for a column and a value or a list of value
Parameters
----------
df: DataFrame
DataFrame to filter
column: str
column name
value: list or 1dim value
values
Returns
-------
DataFrame: filtered Data... | e94d2d0be3d02bee999fdc9e5665785c862a19a8 | 680,335 |
import os
def _env_vars_exposed(env_vars, env=os.environ):
"""Check if environment variables are exposed."""
return all(var in env for var in env_vars) | d42afe06c13ad1c2ef2840f71ce0f8e26e0cb09e | 680,337 |
def phi(T):
"""
:param T: [°C] Temperatura
:return: Factor que cuantifica la rapidez de cambios en los canales iónicos debido a la temperatura (T).
"""
Q_10 = 3 # Radio de las tasas por un incremento de temperatura de 10 °C
T_base = 6.3 # Temperatura base [°C]
return Q_10 ** ((T -... | 6873b85986e11d3f88e05a0793f4e8de7d1a2292 | 680,338 |
def array2latex(X, header=1, hlines=(), floatfmt='%g', comment=None, hlinespace=None, mode='tabular', tabchar='c'):
""" Convert numpy array to Latex tabular """
ss = ''
if comment is not None:
if isinstance(comment, list):
for line in comment:
ss += '%% %s\n' % str(line)
... | 83cbe9a3492d2eb88654a88b8f270daf820cd148 | 680,339 |
def get_path_from_string(path):
"""Returns asset path from path string"""
path = path.replace("/lol-game-data/assets", "")
path = path.replace("/v1", "")
path = path.replace("/ASSETS/Missions", "")
path_list = path.split("/")
path = path.replace("/"+path_list[-1], "")
return path | dee4ee78a72fc1081190a8dc90dbf12620f0d9a9 | 680,340 |
def int_to_rgb(int_):
"""Integer to RGB conversion"""
red = (int_ >> 24) & 255
green = (int_ >> 16) & 255
blue = (int_ >> 8) & 255
return red, green, blue | 2b93f91e3050da7500152c2c5adddd0cc575597b | 680,341 |
def model_uname(value):
"""Returns a model name such as 'baking_oils'"""
words = value._meta.verbose_name.lower().replace("&", "").split()
return "_".join(words) | 91ae8e36ea38eb559551c6a7d0f1cc44ffbbb08d | 680,342 |
import subprocess
def _coffeescript_compile(inpath):
"""Returns compiled coffeescript given a path to a .coffee file.
"""
try:
return subprocess.check_output((
'coffee',
'--compile',
'--print',
'--no-header',
inpath,
))
except... | fd8acc700288dc2a0b0f428b6e36fd9060cdc389 | 680,343 |
import re
def chunk_paf(paf_record):
""" Takes a PafRecord object or a full cs string and returns a list of fields from its cs string """
if type(paf_record) == str:
cs = paf_record
else:
cs = paf_record.tags["cs"]
separable_cs = re.sub(r'(?<!\A)([-:*+])', r',\1', cs)
return separa... | 227ab6b995850ac27c0cd1c0ad3bc70a6e7e2a4d | 680,344 |
def heatmap_figsize(nrow, ncol=None):
"""Generate size tuple for heatmap based on number of rows and columns"""
if ncol is None:
ncol = nrow
return ncol * 0.3 + 3, nrow * 0.3 | 5bbe753368e14f388e140fc0e1866503e3b9673d | 680,345 |
def get_task_info(experiment_length, task_color):
"""Get Task Info.
Generates fixed RSVPKeyboard task text and color information for
display.
Args:
experiment_length(int): Number of sequences for the experiment
task_color(str): Task information display color
Return get_task... | ff764bcf4a76dc9b641b38eafce53af60e770b2d | 680,346 |
import subprocess
def run_setupcon():
"""
helper that runs setupcon to activate the settings, taken from
oem-config (/usr/lib/oem-config/console/console-setup-apply)
"""
ret = subprocess.call(["setupcon","--save-only"])
subprocess.Popen(["/usr/sbin/update-initramfs","-u"])
return (ret == ... | 011a79f0a6737ec1a4195c3f492d6a634c32e8c4 | 680,347 |
import argparse
def parse_args():
"""Parse arguments.
Returns:
args: The parsed arguments.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'--num_copies',
dest='num_copies',
type=int,
help='Number of copies to run.',
... | dc2610b32ce10b4456d860059d83d09b60b49082 | 680,348 |
import pickle
def load_pickle(name: str):
"""
Description:
:param name: str, file name without file extension
:return: obj
"""
handle = open(name + ".pickle", 'rb')
obj = pickle.load(file=handle)
handle.close()
return obj | 01e6057a9cc94f6e751dabe9d25132076e87362e | 680,350 |
import platform
def get_rightclick_btn():
"""
Returns the identifier for the right mouse button used by tkinter
as a string.
"""
system = platform.system().lower()
if system == "linux":
return "2"
elif system == "darwin":
return "2"
elif system == "windows":
return "3"
return "3" | 72ff84669bc31668762b3200cbf9e23c3053465b | 680,351 |
def getBit(val, idx: int) -> int:
"""Gets a bit."""
return 1&(val>>idx) | 330c64f5e3ddb50608ded76a21dc52e56ca5485c | 680,352 |
def ocp_settings_ready(provider):
"""Verify that the Application Settings are complete."""
return bool(provider.authentication) | 401264df0ddecb705aba4c57322e95ba569a3366 | 680,353 |
import subprocess
import click
def get_available_printers():
"""Get the list of available printers."""
try:
pr = subprocess.run(
["/usr/bin/lpstat", "-a"], check=True, capture_output=True
)
printers = pr.stdout.decode("UTF-8").splitlines()
printers = [p.split(" ")[0... | 70513f88db2960ca9721fac1707e3c2783800c47 | 680,354 |
def genblast(query_genes, database, outfile, basename=""):
""" """
inputs = [query_genes, database]
outputs = [outfile]
options = {
'cores': 1,
'memory': '4g',
'account': 'NChain',
'walltime': '04:00:00'
}
if basename=="":
basename = outfile.split("/")[-1... | 648529bfa064d197975693bfb68b71003a498893 | 680,355 |
def islink(path):
"""Test for symbolic link.
On WindowsNT/95 and OS/2 always returns false
"""
return False | 3f98aae8525f0837f87ee5266365551eac3a7684 | 680,356 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.