content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def gen_closure():
"""
Just prints out the closure tags for the audit file (to a list)
Returns:
A list of strings to close a SQL audit file for nessus.
"""
out = []
out.append(' ' )
out.append(' </group_policy>')
out.append('</check_type>')
out.append(' ')
return out | 84b3cf190b7365c14326694d24ebde6c1873c325 | 32,057 |
import sys
from io import StringIO
def __get_exec__(commands):
""" Execute a command, trick Python into writing to our stream instead of STDOUT, and return the contents of our stream """
stdout_stream = sys.stdout
string_stream = StringIO()
try:
sys.stdout = string_stream
exec(com... | a77c55a168b6f761af325cbaa389d6dc0ba63e9f | 32,059 |
def field_isomorphism_factor(a, b):
"""Construct field isomorphism via factorization."""
p = a.minpoly.set_domain(b)
_, factors = p.factor_list()
for f, _ in factors:
if f.degree() == 1:
root = -f.rep[(0,)]/f.rep[(1,)]
if (a.ext - b.to_expr(root)).evalf(chop=True) == 0:... | ae04232763d2bbce98e62952b38121446a5b40c7 | 32,060 |
def numerifyId(string):
"""
Given a string containing hexadecimal values that make up an id, return a new id that contains all digits and no letters.
"""
for i in range(0, len(string)):
if string[i] < "0" or string[i] > "9":
string = string[:i] + "{}".format(ord(string[i]) % 10) + st... | 25407581b9f60f260c01cc7339ed670ce6edc412 | 32,066 |
import csv
def load_state_manifest(state_manifest_in):
"""
Load dict of Roadmap ChromHMM states
"""
states = []
with open(state_manifest_in) as infile:
reader = csv.reader(infile, delimiter='\t')
for state, name in reader:
code = '_'.join([state.replace('E', ''), name... | 23b287c5cfd5611bb9b3c8374c3d5dff6d6487fe | 32,068 |
def electionsWinners(votes, k):
"""Find number of candidates that have chance to win election
Args:
votes(int): List of number of votes given to each candidate so far.
k(int): Number of voters who haven't cast their vote yet.
Return:
Number of candidates that still have... | 8daa21263b9098db47204e9842e4169b7e3ede4d | 32,069 |
import math
def round_up_to_multiple(x, base):
"""Round up the given number to the nearest multiple of the given base number."""
return math.ceil(float(x) / float(base)) * base | 09ef5da40f94bd713bfab3cd5e610f952bf0bf92 | 32,070 |
def get(self, url, **kwargs):
"""Sends a GET request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
"""
kwargs.setdefault('allow_redirects', True)
return self.request('GET', url, **kwargs) | 8b63a8e62d8185048448f93e6511b8069bc295c6 | 32,071 |
def rotate(items: list, k: int) -> list:
"""Rotate a list by k elements."""
items = items[k:] + items[:k]
return items | c649f79d4ce3d501a9042288e6f83369a7899a84 | 32,073 |
import math
def f(t):
"""
:param t: Аргумент функции
:return: значение заданной по варианту функции от t
"""
return math.log(t) - 1 | 624337e49085fc8680e22832bab535c68a9cadc9 | 32,074 |
def _resolve_combined_names(predecessors):
"""Creates a unique name from the list of :class:`UmiBase` objects
(predecessors)
Args:
predecessors (MetaData):
"""
# all_names = [obj.Name for obj in predecessors]
class_ = list(set([obj.__class__.__name__ for obj in predecessors]))[0]
... | e92401909a372ec0d6359575b64091fef76a90a2 | 32,075 |
def get_lines_len(word_sizes):
"""return the length of all the lines that are 0 weperated"""
line_lens=[]
current_line_len=0
for dim in word_sizes:
if dim==0:
line_lens.append(current_line_len)
current_line_len=0
else:
current_line_len+=dim[0]
ret... | 7afa1f4109b77932f6125cf50d5e51cd37db2011 | 32,076 |
import os
import subprocess
from datetime import datetime
def get_commit_time():
"""Get the timestamp of the last commit on the project."""
try:
cmd = ["git", "log", "-1", "--format=format:%ct",
os.path.dirname(__file__)]
proc = subprocess.check_output(cmd)
time_str = da... | 3667acf4c23f8d4f75b8bb9e7a7ffbd1988b64f3 | 32,077 |
from typing import Dict
from typing import Any
def _get_fp_len(fp_params: Dict[str, Any]) -> int:
"""
Return the length of the fingerprint with the given parameters.
Parameters
----------
fp_params : Dict[str, Any]
Parameters to get the fingerprint length from
Returns
-------
... | 944e952ad07fa0fa5ea11d5bff8e46b98c1ab87e | 32,078 |
import requests
def get_trades():
"""Retrieve the latest set of trades."""
resp = requests.get("https://api.thetagang.com/trades")
return resp.json()['data']['trades']
# with open('trades', 'rb') as fileh:
# return json.load(fileh)['data']['trades'] | 5e25ea7170181bed34a4e7d3a260cbed9d2ba161 | 32,079 |
def flatesteam_feed(Q_feed, r_steam):
"""
Calculates the flow rate steam of boiler.
Parameters
----------
Q_feed : float
The heat load feed of heat exchanger, [W] [J/s]
r_steam : float
The heat vaporazation of dist [J/kg]
Returns
-------
flatesteam_feed : float
... | ad4a0aa995c9333d70b8fbd003bb03f8bb231018 | 32,081 |
def make_hyperlink(text, target):
""" Makes hyperlink out of text and target and retuns it
https://stackoverflow.com/questions/44078888/clickable-html-links-in-python-3-6-shell
"""
return f"\u001b]8;;{target}\u001b\\{text}\u001b]8;;\u001b\\" | 4e9b3f69e5d6c48afed5261f7cf70fbee785f8ab | 32,084 |
def load_constants():
"""Returns constants frequently used in this work"""
params = {'vtl_max': 20 , #Max translation speed in AA/s
'm_Rb': 7459, # Proteinaceous mass of ribosome in AA
'Kd_cpc': 0.03, # precursor dissociation constant in abundance units
... | cc5a25875c95676d2cb89a14ff11a8291af0e586 | 32,085 |
def task_wrapper(pid, function, batch, queue, *args, **kwargs):
"""
Wrapper to add progress bar update
"""
result = []
for example in batch:
result.append(function(example, *args, **kwargs))
queue.put(f'update{pid}')
return result | 8191ea4875f642c172a3a5d22742f66187067298 | 32,086 |
from typing import List
import os
def get_all_json_paths(dir_path: str) -> List[str]:
"""Gets all json paths from a given directory."""
paths = [os.path.join(dir_path, f) for f in os.listdir(dir_path)]
return [p for p in paths if p.endswith(".json") and os.path.isfile(p)] | ca3c2e1152f39d8db233448f39c532ab99ad3b1c | 32,087 |
def convert_to_ids(dataset, vocabulary):
"""Convert tokens to integers.
:param dataset a 2-d array, contains sequences of tokens
:param vocabulary a map from tokens to unique ids
:returns a 2-d arrays, contains sequences of unique ids (integers)
"""
return [[vocabulary[token] for token in sample... | 153094a0fcc57880193a441fde0927010b583d19 | 32,088 |
def getColumnLocations(columnNumber):
"""
Return a list of all nine locations in a column.
:param int rowNumber: Column
:return: List of tuples
:rtype: list
"""
return [(row, columnNumber) for row in range(9)] | 8a7876284327c52badc15ba26a28856018790341 | 32,089 |
def transform_date(date):
"""Encodes date and timke into url format.
:param date: Date and time.
:type date: str
:return: encoded date.
:rtype: str
"""
index = date.find(' ')
date = (date[:index] + 'T' + date[index + 1:] +
":00.12345+00:00").replace(':', '%3A').replace('+',... | 03de08bdb7e15bf74c8ae61eef90ca861e0aef0e | 32,090 |
from typing import Dict
import torch
def clone_tensors(tensors: Dict[int, torch.Tensor]) -> Dict[int, torch.Tensor]:
"""
Clones all tensors in dictionary.
Args:
tensors (dict): Dictionary of tensors with string keys.
Returns:
New dictionary with cloned tensors.
"""
return {id... | af5ae8f368c450d34ec412bd769abe03d77fd257 | 32,091 |
def lstripw(string, chars):
"""Strip matching leading characters from words in string"""
return " ".join([word.lstrip(chars) for word in string.split()]) | 17b7bffd3e6f5e02cc184c1976eeedd93ebb4f3e | 32,092 |
import logging
import os
import json
def load_featured(filename):
"""Load featured themes from a previously saved featured.json"""
log = logging.getLogger('load_featured')
log.info('Started load_featured, opening %s' % filename)
data = {}
if os.path.isfile(filename):
with open(filename, "... | 1e332c3c8f0bf9470608ff2db4b360e816a32d2a | 32,093 |
def is_folder_url(url_parts):
"""
Determine if the given URL points to a folder or a file:
if URL looks like:
- www.site.com/
- www.site.com
then ==> Return True
if URL looks like:
- www.site.com/index.php
- www.site.com/index.php?id=1&name=bb
- www.site.com/index.php/id=1&nam... | c5ba46005e6c82cbbcb2ef914947b5a154bdd3b0 | 32,094 |
def formatear_camino(pila):
"""Convierte una lista de ciudades en un string separado por ->"""
return " -> ".join(map(str,pila)) | 3b85be818e8202e1b3626ce2020d91dd687e5383 | 32,095 |
import re
def check_word(word, string):
"""
function will check if the word exists in a string
uses word boundary for search
word: is the word to be searched
string: string to perform the operation on
"""
regexStr = re.search(r'(\b%s\b)' % word, string)
if regexStr is n... | da0f559b714bff6ec7a41a892e4c313a4eef13c0 | 32,096 |
def GetSettingTemplate(setting):
"""Create the template that will resolve to a setting from xcom.
Args:
setting: (string) The name of the setting.
Returns:
A templated string that resolves to a setting from xcom.
"""
return ('{{ task_instance.xcom_pull(task_ids="generate_workflow_args"'
').... | 8d8c1c7b58d91b1d0a9561fa504887e725416fae | 32,097 |
import subprocess
import json
def nix_prefetch_git(url, rev):
"""Prefetches the requested Git revision (incl. submodules) of the given repository URL."""
print(f'nix-prefetch-git {url} {rev}')
out = subprocess.check_output(['nix-prefetch-git', '--quiet', '--url', url, '--rev', rev, '--fetch-submodules'])
... | 57624f63317df2541fa1e16ed3f8332612a6bd30 | 32,099 |
def get_nombre_articles(page, dico_balise) -> int:
"""
Permet d'avoir le nombre d'articles par page dans la catégorie surlignage.
:param page : parsing d'une page HTML correspondant à la catégorie surlignage.
:param dico_balise : fichier JSON contenant les balises et les Xpath.
:return : le nombre d... | 540a86c6ec84affee72a06e8e75b60ee23b49b6d | 32,100 |
import ast
def evalTF(string):
"""
Given a string, evaluates that string and returns True or False depending
if the string is "true" or "false", and most-important, case insensitive
@throws Exception if string is not evaluable
@param string to check if true or false
@return True if string is "true", false ... | 3dadb12d40814d2c7f62776a6a9497ee701d31d1 | 32,101 |
import traceback
def __eval_all_locators(input_list, return_exec=False, return_exec_name="evaluated_locators"):
"""
:param input_list: :type list of namedtuple(locator,key,value). An example of this is the ValueFinder tuple
:param return_exec: :type boolean: flag for whether to return a code string that c... | 0947478f84c8e10220eff6522b4804e269d850df | 32,102 |
import inspect
import re
def getargspec(fn):
"""
Similar to Python 2's :py:func:`inspect.getargspec` but:
- In Python 3 uses ``getfullargspec`` to avoid ``DeprecationWarning``.
- For builtin functions like ``torch.matmul`` or ``numpy.matmul``, falls back to
attempting to parse the function docst... | 3aa76a3915e42e9f90f0326c37b94d434eed588a | 32,103 |
import platform
def format_build_command(command):
"""Format a command string so that it runs in the Anroid build environment.
Args:
command: Command to format.
Returns:
Command modified to run in the Android build environment.
"""
environment = []
if platform.system() == 'Darwin':
environme... | 4a0eb92d85f99c01c14a94b8df4fd996d9c23ba2 | 32,104 |
import os
def document_function_ace(function):
"""returns the function documentation in the style of ace"""
str_list = []
# Title
str_list.append("\n## ace_{}_fnc_{}\n".format(function.component, os.path.basename(function.path)[4:-4]))
# Description
str_list.append("__Description__\n\n" + '\n... | c289a73c6de505782bf3fc411723366d9f769660 | 32,105 |
def create_additive_function(increment):
"""
return the addition of a fixed value as a function
:param increment: float
value that the returned function increments by
:return: function
function that can increment by the value parameter when called
"""
return lambda value: value ... | b7432eaa11dcea49bb98ec2c6d3e0cc9dd979145 | 32,108 |
def insertionSort(array):
"""
input: array of integers
return : sorted array
"""
for i in range(1, len(array)):
target = array[i]
hole = i
while hole > 0 and array[hole - 1] > target:
array[hole] = array[hole - 1]
hole = hole - 1
array[hole] ... | ab7d76a0f03c4f78e8673082d95599ffdf0909a5 | 32,109 |
import random
def split_unseen(data, rand=False, prop_dev=0.2, rnd_sd=1489215):
"""
Split data into completely separate sets (i.e. non-overlap of headlines and bodies)
Args:
data: FNCData object
rand: bool, True: random split and False: constant split
prop_dev: float, target prop... | 9d77b11c0f77de5ead90fb6674e9f8a54f362156 | 32,110 |
def get_dense_network_shapes(n_layers, hidden_size, n_features, n_outputs):
"""
Helper function to generate the input/output shapes for the layers of a densely connected network
:param n_layers: Number of hidden layers in the network
:param hidden_size: How many hidden neurons to use
:param n_featur... | ea5e74fcdc3fe0b923f1377e202284f0576bff87 | 32,112 |
def list_type_check(lst, data_type):
"""
Checks if each element of lst has a given type.
:param lst: List = list of objects
:param data_type: type = estimated type for the objects
:return: bool = true if all objects in list have the type data_type
"""
return all([type(e) == data_type for e i... | e0c774ddf09a843e5f2f52f7cbf1e332f3f862ad | 32,113 |
import collections
def characters(info, error, otext, tFormats, *tFeats):
"""Computes character data.
For each text format, a frequency list of the characters in that format
is made.
Parameters
----------
info: function
Method to write informational messages to the console.
error... | d8e4cf16a3df05c18394483fc008fb453b6ab352 | 32,116 |
def initialize_from_function_name(state_name, env):
""" Initializes a handle from its name and the environment it has
been defined in"""
result = {}
optionals = ['pre_func', 'post_func', 'enter_func']
mandatorys = ['func']
for optional in optionals:
if (value := env.get(f'{optional}_... | 83237b5dcb4fbd77ab53d731b651251e9e375b24 | 32,117 |
import os
def get_cmplog_build_directory(target_directory):
"""Return path to CmpLog target directory."""
return os.path.join(target_directory, 'cmplog') | 2bf2922d0ca11621043971a27bf5e0dd0d931aab | 32,120 |
def get_cournot_problem(alpha, beta, q):
"""Get cournot problem."""
qsum = q.sum()
P = qsum ** (-alpha)
P1 = -alpha * qsum ** (-alpha - 1)
return P + (P1 - beta) * q | 56fac2f38968242897d7c90027657f4e9a3df88e | 32,121 |
from typing import List
import pkg_resources
def read_csv(path: str, keep_headers: bool = False) -> List:
"""
Reads a csv file by splitting by "\n" and then "," -- creating a 2d list
"""
path = pkg_resources.resource_filename(__name__, path)
with open(path, "r") as f:
data = f.read()
d... | 69aa799910eb3cd52b970472df0a18033086105f | 32,122 |
import xml.dom.minidom
def format_xml(xml_str: str, exceptions: bool=False):
"""
Formats XML document as human-readable plain text.
:param xml_str: str (Input XML str)
:param exceptions: Raise exceptions on error
:return: str (Formatted XML str)
"""
try:
return xml.dom.minidom.pars... | 517dcd73dfeebaeb4828be2e57e3ab02042001fd | 32,126 |
def make_tree(table):
"""
Makes Huffman's binary tree from analysis table
"""
def tree_maker(table):
if len(table) == 1:
return table
new_table = sorted([(table[0][0] + table[1][0], table[0], table[1])] + table[2:], key = lambda entry: entry[0])
return tree_maker(new_table)
return tree_maker(table)[0] | 5352fd3d02e59ed3cb3e68cb52d285d505186132 | 32,127 |
def read_index(fhandle):
"""Reads an already open index file and returns a list of tuples (groupname, list fo lines)"""
result = []
current_label = None
current_value = []
for line in fhandle:
line = line.strip()
if line.startswith('[') and line.endswith(']'):
if current... | a43f2571a5e581afbe5edfa8feef643c8bd13118 | 32,128 |
def sub(x,y):
"""
Returns the difference x-y
Parameter x: The value to subtract from
Precondition: x is a number
Parameter y: The value to subtract
Precondition: y is a number
"""
return x-y | 9c7d9fcef236dff3e5d4b9840c082cbeacc9c7e5 | 32,129 |
def excel_column_label(n):
"""
Excel's column counting convention, counting from A at n=1
"""
def inner(n):
if n <= 0:
return []
if not n:
return [0]
div, mod = divmod(n - 1, 26)
return inner(div) + [mod]
return "".join(chr(ord("A") + i) for i... | 1555dcc33420d107c9aa74ce4d7f0395ae6b3029 | 32,130 |
def lectureArbre():
""" Lit un fichier et de créer une liste correspondant à l'arbre indiqué. """
fichier = open("fichiers/arbre.txt", "r") # ouverture du fichier en lecture
arbre = []
try:
arbre = eval((fichier.readline()).strip("\n"))
except NameError:
print("Erreur dans le fi... | 67d42f5f94ea6c4d96ee3f50e1289f7635a8b457 | 32,133 |
def find_data_source_url(a_name, url_prefs):
"""Return the url prefix for data source name, or None."""
for row in url_prefs:
if row[0] == a_name:
return row[1]
return None | d91960040d4e572ff4c882a53f6ce66460253d9c | 32,135 |
def hourglass(my_arr):
"""
Takes in my_arr (6x6 array) and returns hourglass elements
in a list of list
"""
s_glass = []
for i in range(len(my_arr) - 2):
for j in range(len(my_arr) - 2):
h_glass = []
h_glass += my_arr[i][j:3+j]
h_glass.append(my_arr[i+... | 05e7d48261a991e5d030c8c156583057c935ffc0 | 32,136 |
import torch
def predict(img_data, model,device, topk):
"""
Classify image
"""
model.to(device)
model.eval()
inputs = img_data.unsqueeze(0)
inputs = inputs.to(device)
output = model(inputs)
ps = torch.exp(output).data
ps_top = ps.topk(topk)
idx_class... | 64b492e1222638fa4b0662c035524f2ec8d30a7f | 32,137 |
def tile(tensor, dim, repeat):
"""Repeat each element `repeat` times along dimension `dim`"""
# We will insert a new dim in the tensor and torch.repeat it
# First we get the repeating counts
repeat_dims = [1] * len(tensor.size())
repeat_dims.insert(dim + 1, repeat)
# And the final dims
new_d... | a8386c5ed8d6f89f226d64271a8fbddbf0ead543 | 32,138 |
def get_lowest_bits(n, number_of_bits):
"""Returns the lowest "number_of_bits" bits of n."""
mask = (1 << number_of_bits) - 1
return n & mask | 086a48a359984bf950e44e49648bfcac05382c84 | 32,140 |
def search_step(f, x_k, alf, p_k):
"""
This function performs an optimization step given a step length and step direction
INPUTS:
f < function > : objective function f(x) -> f
x_k < tensor > : current best guess for f(x) minimum
alf < float > : step length
p_k < tensor > : s... | 51d634ef8a6196a884a0c2ec855fb785acf65db5 | 32,141 |
def split_str(string):
"""Split string in half to return two strings"""
split = string.split(' ')
return ' '.join(split[:len(split) // 2]), ' '.join(split[len(split) // 2:]) | 01268b6c47a4181c7a2e04cacf7651a8c0c81c50 | 32,143 |
from typing import Tuple
def get_default_span_details(scope: dict) -> Tuple[str, dict]:
"""Default implementation for get_default_span_details
Args:
scope: the asgi scope dictionary
Returns:
a tuple of the span name, and any attributes to attach to the span.
"""
span_name = (
... | 6177c4f32c5837752cce9c8b346350b480bfdcd2 | 32,144 |
import numpy
def lpc2spec(lpcas, nout=17):
"""
Convert LPC coeffs back into spectra
nout is number of freq channels, default 17 (i.e. for 8 kHz)
:param lpcas:
:param nout:
:return:
"""
[cols, rows] = lpcas.shape
order = rows - 1
gg = lpcas[:, 0]
aa = lpcas / numpy.tile(gg... | 92e7dcb63a3d48a0275450debd594154a224718b | 32,148 |
def process_name_strings(language_data, df):
"""
Returns a dictionary of names for each of the different items specified in the DataFrame (df).
The key denotes the row_number of each item. A nested dictionary is the value, with each language code as the key, and the value the name.
If a language does no... | f77fd8a83c524f0bca8b0c8c15c2216437492e1f | 32,150 |
def convert_list_type(x, type=int):
"""Convert elements in list to given type."""
return list(map(type, x)) | 36957a24aaeff11cedd2dcb0715c757b2c627083 | 32,151 |
def getExperimentAccuracy(list_of_results):
"""Returns a simple accuracy for the list of Result objects."""
num_correct, num_total = 0, 0
for result in list_of_results:
if result.isCorrect():
num_correct += 1
num_total += 1
return num_correct / num_total | 8276e06a41a1105700232ed1ccfb38bd2b3d5063 | 32,152 |
import json
def parser(chunks):
"""
Parse a data chunk into a dictionary; catch failures and return suitable
defaults
"""
dictionaries = []
for chunk in chunks:
try:
dictionaries.append(json.loads(chunk))
except ValueError:
dictionaries.append({
... | 385b73026c079b635b6e33b35bfd8f5ebb453f64 | 32,154 |
def torch_diff(tensor,n=1, dim=-1):
"""
tensor : Input Tensor
n : int, optional
The number of times values are differenced. If zero, the input
is returned as-is.
axis : int, optional
The axis along which the difference is taken, default is the
last axis.
"""
nd = ... | 02277b8d881ec3bc2806f6ddd06acef8d26f83ac | 32,155 |
import time
import random
def get_data():
"""
Obtiene datos a enviar.
:return: diccionario con los datos de las variables
:rtype: dict
"""
data_list = []
now = time.time()
for inverter in range(2):
for var in range(3):
data = {}
data["timestamp"] = now +... | da9ee0fef6c55e1af02dca223fc7e978c340f3b6 | 32,156 |
from datetime import datetime
import time
def get_date():
""" Returns the current date. Format: Month day, year.
Example: January 15, 2020
"""
MONTHS = ("January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "December")... | 71848adf618f2e339f7e3f0cc56d629a78e947f8 | 32,158 |
def filter_deinterlace():
"""Yadif deinterlace"""
return "yadif=0:-1:0" | 06d4e7f20ed4c6af2cb0f2525847184484301423 | 32,160 |
def update_dict(d, e, copy=True):
"""
Returns a new dictionary updated by another dictionary.
Examples
--------
Consider a dictionary `d` which we want to update:
>>> d = {0: 'a', 1: 'b'}
Now consider the dictionary for update:
>>> e = {1: 'c', 2: 'd'}
We can update the `d` as follows:... | 4cd3f53c651be577b45a35aaacfef658b852faf3 | 32,161 |
from pathlib import Path
import re
def rglob(self: Path, regex=".*"):
"""Like path.glob, but uses a regex to match Paths"""
return (f for f in self.glob("*") if re.match(regex, str(f))) | f16d8d0c5bb990d8faac0e7ad56c5b9157c4c9a4 | 32,162 |
def vlan_range_expander(all_vlans):
"""
Function for expanding list of allowed VLANs on trunk interface. Example: `1-4096` -> range(1, 4097). Can be used when trying to figure out whether certain
VLAN is allowed or not. Reverse function is ``vlan_range_shortener``.
:param all_vlans: Either list (`["1-1... | 5224436c8bf10509df6d8ad52321e7dd9214792a | 32,163 |
import torch
def to_cuda(data):
"""
put input data into cuda device
"""
if isinstance(data, tuple):
return [d.cuda() for d in data]
elif isinstance(data, torch.Tensor):
return data.cuda()
raise RuntimeError | af9820bccbce3369357bf7c5b853efe3e88e052a | 32,164 |
def sliding_point_cloud(df, width):
"""
Returns a sliding window point cloud from a list (or dataframe) of points.
width (int or np.timedelta64): if int, window goes by iloc. if timedelta, window goes by time.
"""
if type(width) == int:
ind = list(df.index)
dfdict = df.T.apply(tuple... | 1446f37eff8722bb8732c8854260c1587040dfac | 32,165 |
from typing import Optional
import ast
def get_version_using_ast(contents: bytes) -> Optional[str]:
"""Extract the version from the given file, using the Python AST."""
tree = ast.parse(contents)
# Only need to check the top-level nodes, and not recurse deeper.
version: Optional[str] = None
for c... | 690d4d04fd17263b90fa51a982519f685f9622a4 | 32,167 |
def _arg_scope_func_key(op):
"""Returns a key that can be used to index arg_scope dictionary."""
return getattr(op, '_key_op', str(op)) | b713202ef1d53650996041bd15655b58f348423a | 32,168 |
def load_html(html_file: str):
"""Used to load html file from template dir and pass into homepage string."""
with open(html_file, "r") as f:
html_stream = f.read()
return html_stream | 99b5c2d51172cac33bab32454a67c84eefe9021d | 32,169 |
def complement(sequence):
"""
Params:
* *sequence(str) *: DNA sequence, non ATGC nucleotide will be returned unaltered
Returns:
* *sequence.translate(_rc_trans)(str) *: complement of input sequence
"""
_rc_trans = str.maketrans('ACGTNacgtn', 'TGCANtgcan')
return sequence.translate(_rc... | 2e0419c865968e0e24a8bae87c020158fc14768c | 32,170 |
def fallback_key_exists(verbose, fallback_language, obj_id, key, object_json):
""" Checks if there was source language to be translated from """
if fallback_language in object_json:
return True
if verbose:
print(f"No {fallback_language} reference for {obj_id} string '{key}'"
f"... | 29bfa4bc3cf39de127d5c07a4e70abd152b7ec28 | 32,171 |
def ptoc(width, height, x, y, zxoff, zyoff, zoom):
"""
Converts actual pixel coordinates to complex space coordinates
(zxoff, zyoff are always the complex offsets).
"""
zx_coord = zxoff + ((width / height) * (x - width / 2) / (zoom * width / 2))
zy_coord = zyoff + (-1 * (y - height / 2) / (zoom... | a0d49a0180b620f08b478a0b5ee9a313e1da468e | 32,172 |
def calc_standard_yield(crop): # Standard yield per year
""" Taken from table from Shao Economic Estimation Tool (2017)"""
if crop == 'lettuce':
return 78.5 # kg/m2/year
else:
raise RuntimeError("Unknown crop: {}".format(crop)) | 1aa1edb085e29f1c217e4acc5a0c9f98b8aa0629 | 32,173 |
def _maybe_convert_to_int(value):
"""Returns the int representation contained by string |value| if it contains
one. Otherwise returns |value|."""
try:
return int(value)
except ValueError:
return value | 2e67c4a8f6aa3ef5a0f982c85127f37b60f979ad | 32,174 |
def try_helper(f, arg, exc=AttributeError, default=''):
"""Helper for easy nullable access"""
try:
return f(arg)
except exc:
return default | 5f1d97a1d138981831ee00b1f71b97125ff40370 | 32,175 |
def get_centroid_idx(centroids, c):
"""
Returns the index of a given centroid c. Assumes that centroids
is the ndarray of shape (k, d) where k is a number of centroids
and d is a number od dimensions.
"""
return centroids.tolist().index(c.tolist()) | 08eae6aaa3ac7933c5f8bca08a9c1c75da26daf0 | 32,176 |
import os
def expand( filePath, fileName=None ):
"""Combine a directory and file name and expand env variables and ~.
A full path can be input in filePath. Or a directory can be input
in filePath and a file name input in fileName.
"""
if fileName:
filePath = os.path.join( filePath, fileName )
... | 033b439127719500ff140602900f3fa50b106d6c | 32,177 |
def undo_pad(data, pad_size):
"""Remove padding fromt edges of images
Parameters
----------
data : array-like
padded image
pad_size : array-like
amount of padding in every direction of the image
Returns
-------
data : array-like
unpadded image
"""
... | 873feb3cf4daaf6153dfe87662ba10b531ba222f | 32,178 |
import glob
import os
def get_csv_names(output_url, suffix):
"""
This function goes to a folder location and returns a list
of all the names of the csvs within it.
Input:
output_url - the file directory to look in
suffix - the suffix of the csv name
Output:
csv_names - a ... | 05920446bfa8c0f9f88416b8a623a50445c02aac | 32,180 |
import warnings
def null_observation_model(arg):
"""
A callable that returns ``arg`` directly. It works as an
identity function when observation models need to be disabled
for a particular experiment.
"""
warnings.warn(
"`null_observation_model` is deprecated. "
"Use `<Measure... | 05edc6846617400fca9ab5dc1f0614237372bc8e | 32,181 |
def df_to_vega(df):
""" Convert a Pandas dataframe to the format Vega-Lite expects.
"""
return [row[1].to_dict() for row in df.reset_index().iterrows()] | 6ecbddde38cfc1420370c70a48161e21efd79980 | 32,183 |
import torch
def angle(x, eps=1e-11):
"""
Computes the phase of a complex-valued input tensor (x).
"""
assert x.size(-1) == 2
return torch.atan(x[..., 1] / (x[..., 0] + eps)) | 8cfbf6c9aefddfcb7de5af3d1fca89f7fb3dfd32 | 32,184 |
def progressive_step_function_maker(start_time, end_time, average_value, scaling_time_fraction=0.2):
"""
Make a step_function with linear increasing and decreasing slopes to simulate more progressive changes
:param average_value: targeted average value (auc)
:param scaling_time_fraction: fraction of (en... | 066ae4415c942248511c04b6732f98587f2f524f | 32,186 |
import re
def ratio_caps(text: str, ratio: float) -> bool:
"""
Checks the ratio of capital letters to words in a sentence
##TO DO: better way to clean. placeholder for removing DISTRIBUTION
STATEMENTS/jargon fragments
"""
if len(re.findall(r"[A-Z]", text)) / len(text.split()) < ratio:
... | b8f6a140ab51a188134bafb58d3eb06eecffd213 | 32,188 |
import os
def _get_exec_path(exec_name):
""" If the HOTKNOTS environment variable is set, use that as the directory
of the hotknots executables. Otherwise, have Python search the PATH directly. """
if 'HOTKNOTS' in os.environ:
return os.environ['HOTKNOTS'] + '/bin/' + exec_name
else:
return exec_name | 0caf332f85195f4e2d2aaa4ce9581f8360ea5899 | 32,189 |
def win_for_player(board, player_token):
"""
Four in a row, column or a diagonal
:param board:
:param player_token: 'r' / 'y'
:return:
"""
for r in range(6):
for c in range(7):
if board[r][c] == player_token and r <= 2:
if board[r + 1][c] == board[r + 2][... | 9fae699021fdc0d7169d30e0edec18161bd2ae8c | 32,192 |
import argparse
import os
def recources_exist(
argv: argparse.Namespace,
resources: str
) -> bool:
"""Проверяем существование необходимых для работы файлов и папок"""
if not os.path.exists(resources):
print("Не найдена папка ресурсов!")
print("Заканчиваю работу")
return False
... | c7b1e7780e6f4c36d0fafb4ec6ccfb1d64d6e37d | 32,193 |
def _GetVocabulary(vocab_filepath):
"""Maps the first word in each line of the given file to its line number."""
vocab = {}
with open(vocab_filepath, 'r') as vocab_file:
for i, line in enumerate(vocab_file):
word = line.strip('\r\n ').split(' ')[0]
if word:
vocab[word] = i
return vocab | 2db9fd70180e9fc2c64e604609fc007a533f2aa9 | 32,194 |
import argparse
def prepare_options():
"""
Prepare the option parser.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("filename", nargs='+')
return parser | 99957b4f235f62702f528a823bb1625d6f4d8acb | 32,196 |
def filter_to_region(node, contig=None, coords=None):
"""Return True iff a node is within a given region (and region is specified)."""
((seq, coord), miss) = node
if contig and seq != contig:
return False
if coords and coord < coords[0]:
return False
if coords and coord > coords[1]:
... | bbbde3a35d464883de4e92c62f2a574eda11ff2f | 32,197 |
def is_setuptools_enabled(pkginfo):
"""Function responsible to inspect if skeleton requires setuptools
:param dict pkginfo: Dict which holds the package information
:return Bool: Return True if it is enabled or False otherwise
"""
entry_points = pkginfo.get("entry_points")
if not isinstance(entr... | 1faf21c804aa0b0a5b681d09ca4577d15a264ae7 | 32,198 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.