content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
import sys
import locale
import codecs
def is_supported():
"""Check whether operating system supports main symbols or not.
Returns
-------
boolean
Whether operating system supports main symbols or not
"""
if os.getenv("DISABLE_UNICODE_OUTPUT"):
return False
encod... | 13c46b98dfeb9aeb86502d52af329b8c37073d17 | 640,381 |
import urllib.request
def get_htmls(urls, timeout):
"""get htmls from urls array.
args:
urls([str]): urls string array.
timeout(int): seconds
return:
[url, html]
url: str
html: str
"""
ret = []
for url in urls:
try:
with urllib.reques... | 3a687ce8b46d8952dd5d2d78338f74393c8d57d6 | 640,382 |
def main(n):
"""Calculates the sum of all numbers that can be written as the sum of
the <n> powers of their digits.
Args:
n (int): nth power
"""
pv = {v: v**n for v in range(10)}
match = []
for num in range(2**n, 10**(n+1)):
digits = (int(dg) for dg in str(num))
sum_... | 7254d7c34fe40a6765f7e51532279dde71200816 | 640,383 |
import argparse
import sys
def procargs() :
"""Add arguments to the argument parser and parse the standard input"""
p = argparse.ArgumentParser( description="Merge XML files together.")
p.add_argument("-o", dest='outfile', help="output file", default=sys.stdout,
type=argparse.FileType('w') )
p.add_argume... | e9b805c09d380e9f9c6eea48564a2ab0759c58c9 | 640,384 |
def has_proper_name(user=None):
"""Whether user has enough data with which to form a proper name.
:param user: Django user object
:returns: True, False, or None (if unknown)
:rtype: bool | None
.. note::
User must be authenticated or function will return None.
"""
ret = None
... | e632c7ef6637f910188a5969b3be5ba2e85b415e | 640,385 |
from typing import List
def double_every_other_main(items: List[int]) -> List[int]:
"""Doubles every second integer in a list starting
Returns: a list of doubled items.
Examples:
>>> double_every_other_main([1, 2, 3, 4]) == [1, 4, 3, 8]
"""
return [item * 2 if index % 2 else item for ind... | 36c4939ad77f4b50bc38290bb32521a081dac3e4 | 640,387 |
def tap(x, label=None):
"""Prints x and then returns it."""
if label:
print('%s: %s' % (label, x))
else:
print(x)
return x | edf5b258b2bd28b6b8100192fee4dd5ff6fb9387 | 640,388 |
import re
def ParseHostPort(address):
"""Parses the provided address string as host:port and
returns a tuple of (str host, int port).
"""
host_port_re = re.match(r"([a-zA-Z0-9-\.]+):([0-9]{1,5})$", address)
if not host_port_re:
raise TypeError("bad host:port: %s" % address)
host = host_port_re.group(1... | f34ab3ff27b3fb16a4d2f00d070b94ce0e35399f | 640,389 |
def get_data(fname):
"""
:param fname:
:return:
"""
a = []
f = open(fname)
for line in f.readlines():
if line.strip() != "":
a.append(float(line))
f.close()
return a | 5a4d7340f9d5b676863c8ea2273e8b7926a07f42 | 640,390 |
def _get_results(executor, input):
"""retrieves distributed results, causing the pipeline to execute"""
if isinstance(input, list):
return executor.gather(input)
elif isinstance(input, tuple):
return [_get_results(executor, i) for i in input]
else:
return input.result() | 96a6ed73df51bc55f74f6ec3e1086ab6da744907 | 640,391 |
def compute_murphree_stage_efficiency(mu, alpha, L, V):
"""
Return the sectional murphree efficiency, E_mv.
Parameters
----------
mu: float
Viscosity [mPa*s]
alpha: float
Relative volatility.
L: float
Liquid flow rate by mol.
V: float
Vapor flow r... | 01a6b269454fda2fabaf84a8eb1d53b7beed8d16 | 640,392 |
def busca_binaria(vetor, item):
"""
:param vetor: lista que será utilizada na busca.
:param item: item que será buscado na lista.
:return: O indice do elemento buscado, caso ele não existir retorna None.
"""
inicio = 0
fim = len(vetor) - 1
while inicio <= fim: # Caso o item nao esteja... | 3f940ca82eb81532fe4806ea2bd13eecf96a1a15 | 640,393 |
def fuselage(Sts,qm,Ltb):
""" Compute weifht estimate of human-powered aircraft fuselage
Assumptions:
All of this is from AIAA 89-2048, units are in kg. These weight estimates
are from the MIT Daedalus and are valid for very lightweight
carbon fiber composite structures. This may n... | 0acf6ad50dba85cd9f8ccc7602200b67f5ef4b60 | 640,394 |
def split_list(alist, wanted_parts=1):
"""Split a list of intervals in n parts in order to be multiprocessed."""
length = len(alist)
return [alist[i*length // wanted_parts: (i+1)*length // wanted_parts]
for i in range(wanted_parts)] | 515d44a17b74847008c04e3f3dba080ddc3e883e | 640,395 |
from decimal import Decimal
def euler_totient(num, factors):
"""
Given a number n and all its distinct prime factors, compute φ(n).
The insight is that for every distinct prime factor p of a number n, the portion of numbers coprime to A "decays" by exactly (1/p).
"""
totient = Decimal(num)
fo... | 3a13f622ed11b69ae0c3c54b06f00b1752f3d135 | 640,396 |
from datetime import datetime
import os
def mkdir():
"""makes a unique directory to store the files"""
drctry = str(datetime.now())
os.makedirs(drctry)
return drctry | a916585fabbfb49c538dff09d5cd007af7a14419 | 640,397 |
def count_alive_neighbours(_neighbours: list, _cells: dict) -> int:
""" Determine how many of the neighbouring cells are currently alive. """
alive: int = 0
count = 0
"""Checks the list of neighbours and counts the amount that is alive"""
for c in _neighbours:
if _cells[c] is not None and _... | 9a1fa2027d38178e998f530d35f451b5416ad5e1 | 640,398 |
from typing import List
def get_bit_index(number: int) -> List[int]:
"""Get bit indices from number.
Args:
number: A number (greater than 0).
Returns:
List of bit indices.
Examples:
number: 4 (`100` in 2 ary number), Returns: [3]
number: 6 (`110` in 2 ary number), Re... | aa33c6a3cdd0657f5d571e41bb19ff8d4761694f | 640,399 |
def another(a):
"""
:type a: dict of sample.supertypes.original.A,int
:rtype: dict of sample.supertypes.original.A,int
"""
return a | bea949c89398f5cef464519bfe0866aa7b9bdc5c | 640,400 |
import argparse
def parse_args() -> argparse.Namespace:
"""
Parse command line arguments
@return an object containing parsed arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-c", "--city-count",
type=int, default=100,
help="the number of cities in... | cf2d29403164768f49821035411314c9a7a941e1 | 640,401 |
def is_valid_hex_str(hex_str):
"""
Function to check given string is valid hex string or not
Parameter
- hex_str is string
Returns True if valid hex string otherwise False
"""
try:
int(hex_str, 16)
return True
except ValueError:
return False | 2fefd0e514f026267cef1f9f812e83019c8e3a86 | 640,402 |
import requests
def process_image(ID, filename, method):
"""
POST request the user to process the image
Args:
ID (str): user name
filename (str): filename that should exist in database
method (str): processing method
Returns:
r6.json() (str): Confirmation that image w... | 1e36f2fce60a962f4909dd9bd35962be64dd0b81 | 640,404 |
def quantized_rotation(img, factor):
"""
Rotate an image counterclockwise by an integer factor times 90 degrees.
"""
if factor % 4 == 0:
pass
elif factor % 4 == 1:
img = img.transpose(-2, -1).flip(-1)
elif factor % 4 == 2:
img = img.flip(-2).flip(-1)
elif factor % 4 =... | 686f27106f0561725434ed7cd9915862d785d09f | 640,405 |
def byte2str(e):
"""Return str representation of byte object"""
return e.decode("utf-8") | 1d7ef5858be2144dcb8edbb85511bc5bf056a56d | 640,406 |
def remove_whitespace2(original: str) -> str:
"""
>>> remove_whitespace2("I Love Python")
'ILovePython'
>>> remove_whitespace2("I Love Python")
'ILovePython'
>>> remove_whitespace2(' I Love Python')
'ILovePython'
>>> remove_whitespace2("")
''
"""
return or... | 34c8b229fb9741bef1484d95744c4a3ee3f0c310 | 640,407 |
import sys
def py2cmd(code: str,
*additional_arguments):
"""Helper to invoke some Python code through a cmdline invocation of
the Python interpreter.
This should be more portable in some cases.
"""
return [sys.executable, '-c', code] + list(additional_arguments) | abc1f2e2914b10f1282d7c9d8bd5a4136d07c3a5 | 640,408 |
import torch
def generate_all_anchors(anchors, H, W):
"""
Generate dense anchors given grid defined by (H,W)
Arguments:
anchors -- tensor of shape (num_anchors, 2), pre-defined anchors (pw, ph) on each cell
H -- int, grid height
W -- int, grid width
Returns:
all_anchors -- tensor of ... | a7a7a09eca5bbd0a4de8874d3d056651455c47ac | 640,409 |
import argparse
def ProcessArguments(argv):
"""Processing script arguments."""
parser = argparse.ArgumentParser(
description=('This script is used by nightly client to test gdb. '
'DO NOT run it unless you know what you are doing.'),
usage='test_gdb_dejagnu.py options')
parser.add... | 893e69a63d6734c7345d3a536460891b4c396a2f | 640,410 |
def strip_product(header_list):
"""input a list of tag-type values and return list of strings with surrounding html characters removed"""
string_list = ['' for item in range(len(header_list))]
for item in range(len(header_list)):
string_list[item] = str(header_list[item])[53:-14]
return string_... | d1ced266aad67f5a56391342bb1ab8cf6d57ad2f | 640,411 |
def _make_path(keys, value, ext, version=None):
"""Generate a path to a lookup table or metadata"""
if isinstance(keys, (list, tuple)):
keys = '/'.join(keys)
version_str = ''
if version:
version_str = '.{0}'.format(version)
path = '{keys}/{value}{version}{ext}'.format(
... | 065caf2c849e6dc10b4658463ede1143afac1764 | 640,412 |
from bs4 import BeautifulSoup
import string
import re
def get_readable_text(raw_html):
"""
Arguments:
- `x`:
"""
raw_html = bytes(raw_html, 'utf-16').decode("utf-16", 'ignore')
_cleantext = BeautifulSoup(raw_html).text
# paragraphs = _cleantext.split("\n+")
paragraphs = [s.strip() fo... | 1769bb21000013202dc22b4413f1669a84e74ea4 | 640,413 |
def calculateEHP(df, time_window, sz_id_col, sf_col):
"""
Calculate Estimated Human Presence (EHP).
See chapter 3.3 in the article + chapter S2.3, Figure S2 and Table S3 in the supplementary materials of Järv et al. 2017.
"""
# Time Window
tw = time_window + 't'
# Calculate (absolu... | 8475f241bbaebe91d27511a5e390fc94b44bea0f | 640,414 |
import numpy
import math
def jsonify(data):
""" Make a dictionary with numpy arrays JSON serializable """
if type(data) == numpy.ndarray:
data = data.tolist()
if isinstance(data, list):
for item in data:
data[data.index(item)] = jsonify(item)
if isinstance(data, dict):
... | a58dbc8446dd04ebf867bff274c7dda974877a19 | 640,415 |
def store_listings(db, listings):
"""
Store listings in database.
Listings already contained in the database are ignored.
Returns the number of listings that were stored.
"""
cursor = db.cursor()
tuples = [(x, y['street'], y['number'], y['suburb'], y['rent'],
y['area']) for x... | 9f589d50f00a37953fef1c4492ee5d56072ea0b4 | 640,416 |
def getLatexColorCode(val, colorNumbers, colorNames):
"""Creates a Latex color gradient.
:param val: (float) a value for which color will be computed.
:param colorNumbers: (list[float]) three numbers describing the minimum, middle, and maximum of the color scale.
:param colorNames: (list[float]) names ... | e55547a4a83f584edd9df486169f22bcff43392e | 640,418 |
def valid_command(val, valid=[]):
"""Validate given command among accepted set."""
#pylint: disable=dangerous-default-value
assert val in valid, 'invalid command: %s' % val
return val | 5f9781e427faf7ea61773300457539b5bb963c0e | 640,419 |
import inspect
def _get_callable(obj, of_class = None):
""" Get callable for an object and its full name.
Supports:
* functions
* classes (jumps to __init__())
* methods
* @classmethod
* @property
:param obj: function|class
:type obj: Callable
:param of_class: Class that thi... | 9b62e0de62a5a8a2592820f7d6e183395921f838 | 640,420 |
def substr(word, pos, length):
"""Return the substr of word of given length starting/ending at pos; or None."""
W = len(word)
if pos >= 0 and pos+length <= W:
return word[pos:pos+length]
elif pos < 0 and abs(pos)+length-1 <= W:
return word[W+pos+1-length:W+pos+1]
else:
return... | 4aa758d9e26ddd0ea10585c9be82ef35f34ffe4a | 640,421 |
def df_sql_check(df):
"""
"""
if not df.index.is_unique:
return False
if not df.columns.is_unique:
return False
return True | 370c34e9ee298f143c755fdcfc594c6574c46674 | 640,422 |
def board_spacing(edges, size):
"""Calculate board spacing"""
space_x = (edges[1][0] - edges[0][0]) / float(size-1)
space_y = (edges[1][1] - edges[0][1]) / float(size-1)
return space_x, space_y | 07eef3d3664bd424623ddd09fe4f17e62cd7f290 | 640,423 |
def spacing(space, IPA):
"""
Assign space based on its location
Parameters
----------
IPA : bool
A flag used to determine the type of alphabet
space : str
The type of space chosen by user
Returns
-------
list
a list of spaces for prefixes, suffixes, and word... | 00c9c08b207ef27064a0ee1ec97bc72305a1af08 | 640,424 |
import threading
def is_main_thread():
"""
check if current thread is main thread or not
:return:
"""
return threading.current_thread().__class__.__name__ == '_MainThread' | e9a476be4fb83bdc87b3b05794496dc3ed352ff2 | 640,425 |
def extract_term_from_category(json_object):
"""
returns the term from a json representation
Args:
@param json_object: JSON representation
"""
if json_object.has_key('term'):
return json_object['term']
else:
return None | 31cf41e26a8322b20aaa61c2f3d1dcd4dbe72abd | 640,426 |
def process_comment(line):
"""处理注释"""
py_line = line.replace('/', '#')
return py_line | 678d23efa9127a7aa7f0a6a45e943d24afba0457 | 640,427 |
def insert_roi(conn, cur, exp_id, series, offset, size):
"""Inserts an ROI into the database.
Args:
conn (:obj:`sqlite3.Connection): Connection object.
cur (:obj:`sqlite3.Cursor): Cursor object.
exp_id (int): ID of the experiment.
series (int): Series within the experiment. ... | 94fbc438a381d273c89c724bf07f080373063f64 | 640,428 |
import re
def normalize_name(name, separator="_"):
"""Normalizes a name by replacing all non-alphanumeric characters with underscores."""
return re.sub("[^A-Za-z0-9_]+", separator, name) | fa186c1601657d960ba6630ab508883228b40452 | 640,429 |
def _unscale(tensor, minimum, maximum):
"""Rescale a scaled tensor from range (-1, 1) back to its original range
Parameters
----------
tensor : torch.Tensor or torch.autograd.Variable
Tensor to rescale with range (-1, 1) of shape BxCxHxW
mimimum : torch.Tensor
Minimum used to scale the tensor of shap... | 782b50091c0a6f07f915d41ec0a32447151e6d5e | 640,430 |
import random
def pick_words(word_count, word_maxlength):
"""Pick random words"""
# Load text file of all English words
all_words = open('words_alpha.txt', 'r').readlines()
word_list = []
# Choose random word and check if below length limit
while len(word_list) < word_count:
picked_w... | a0130234db1a5d71dc7ec386b6e85b22b23a4f28 | 640,432 |
def get_self(request):
"""
this function returns request's user if any
:param request: request object
:return: User, error_code
"""
return (request.user, None) if \
request.user.is_authenticated else (None, 'not_authenticated') | 40c3dfe5d3dc364ead09cc5d9e8eeca4c0c5ecb8 | 640,433 |
def check_compliance(R):
"""Check the compliance of roughness calc. to Daniel and Weber article
"Psychoacoustical roughness: implementation of an optimized model", 1997.
Check the compliance of the input data R to figure 3 of the article
using the reference data described in the dictionary article_ref.... | 48bb8250a5948c30d28b96911c42dedef5da92ac | 640,434 |
def compose1(h, g):
"""Return a function f, such that f(x) = h(g(x))."""
def f(x):
return h(g(x))
return f | 2b09e83a0a8c6813572e2f99596a2a41c4390e73 | 640,435 |
import argparse
def parse_arguments():
"""
Parse arguments for Variant calling pipeline inputs generation
:return: argparse.ArgumentParser object
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-o',
'--output_file_name',
help='Filename for yaml file to be ... | fbd178dc1149d9b88d5034a051ccc38ebc0b6eaf | 640,436 |
def external_superset_url():
"""The URL under which the Superset instance can be reached by users e.g. https://superset.bi.example.com"""
return 'http://localhost:8088' | 0d85db2025a38e8e550891169176434b1ca87bcd | 640,438 |
def compare_on_files(fork1, fork2):
"""
Args:
fork1: ProjectFork
fork2: ProjectFork
Return:
The common degree: intersection / union
A list contains the common path of the two forks.
"""
return 1.0 * len(set(fork1.file_list).intersection(set(fo... | 28af0c25f38da31090bab769041bc8ef8af93221 | 640,439 |
from pathlib import Path
def fixture_checksum_file(fixtures_dir: Path) -> Path:
"""Return the path to file to test checksum"""
return fixtures_dir / "26a90105b99c05381328317f913e9509e373b64f.txt" | cec0b7751e94dd8214140458e18f5445a2cb87f5 | 640,440 |
def isInString(position, text):
"""
Checks whether the sign from a certain position in text is in string
or not.
@param {number} position.
@param {string} text.
@return {boolean} True if sign is in string.
False if it's not.
"""
for quote i... | f61e1868affea41d6309101706b99910b6eb9a05 | 640,441 |
def normalize_interface(name):
"""Return the normalized interface name
"""
if not name:
return
def _get_number(name):
digits = ''
for char in name:
if char.isdigit() or char in '/.':
digits += char
return digits
if name.lower().startswith... | 6fb97de7ab0a37d01ea9426d16e06c6dfdb171da | 640,442 |
def localhost(request):
"""Return a host manager representing localhost."""
# NOTE: Do not use ansible_adhoc as a dependent fixture since that will assert specific command-line parameters have
# been supplied. In the case of localhost, the parameters are provided as kwargs below.
plugin = request.confi... | 8a037bcec323ddb2d70e23fc9b4419ece075052c | 640,443 |
def clamp(value, minimum, maximum):
"""Clamp value within a range - range doesn't need to be ordered"""
if minimum > maximum:
minimum, maximum = maximum, minimum
if value < minimum:
return minimum
if value > maximum:
return maximum
return value | cf5e599bbfed0a7b122230600883ef5db5d8b1cf | 640,444 |
from typing import Iterable
import os
def all_files_exist(filenames: Iterable):
"""
Return True if all files in a list exist.
:param filenames: A list of file paths.
:return:
"""
isthere = (os.path.isfile(i) for i in filenames)
return all(isthere) | 21475abc758c472cc23b01cd55e57aa24bf39a57 | 640,445 |
def create_query_string(graph_name: str, keyword: str):
"""
This methods generates the query string for the keyword-search in put.
:param graph_name: graph to be queried, default is "default graph",
like "<http://localhost:3030/60d5c79a7d2c38ee678e87a8/60d5c79d7d2c38ee678e87a9>"
:param keyword:... | 4c22524195222bcfb515a160db770b68b893b17d | 640,446 |
def get_acl_advcl_errors(in_file, acl_advcl_file):
"""26.03.20
Short summary.
Args:
in_file (string): Description of parameter `in_file`.
ccomp_xcomp_file (string): Description of parameter `no_roots_file`.
Returns:
None
"""
acl_count = 0
advcl_count = 0
error_... | 7cfbdd6f5e5ff4fd222e17d4d570ebeb3a7163cc | 640,447 |
def invicto_mas_largo(goles_diccionarios: list, goles_adversario: list) -> int:
""" Invictos
Parámetros:
goles_diccionarios (list): Los goles anotados por Diccionarios F.C en cada una de las fechas. Se
garantiza que cada elemento de la lista es un entero no negativo.
... | 2c28d1fff5f949bb528afc9b0ce28816277f5800 | 640,448 |
def _fk_colspec(fk, metadata_schema):
"""Implement a 'safe' version of ForeignKey._get_colspec() that
never tries to resolve the remote table.
"""
colspec = fk._get_colspec()
if metadata_schema is not None and colspec.count(".") == 1:
# need to render schema breaking up tokens by hand, sinc... | 800083015dcff73dfcb6213a1c1fc20144f8fd76 | 640,449 |
import struct
def create_bufferView(
operator,
context,
export_settings,
glTF,
data_buffer,
target,
alignment
):
"""
Creates and appends a bufferView with the given parameters.
:type target: str
"""
if data_buffer is None:
return -1
... | a428fd9fbc816be57c340ea7dbf41d4d3f16f257 | 640,450 |
import hashlib
def get_file_md5(file_path):
"""
获取文件的MD5值
:param file_path:
:return:
"""
with open(file_path, 'rb') as file:
temp_md5 = hashlib.md5()
temp_md5.update(file.read())
hash_code = str(temp_md5.hexdigest()).lower()
return hash_code | abe5c3276ba44b24d0e18385721b4eca1ae0be5c | 640,451 |
def operator_at_traversal_path(path, op):
"""Construct traversal instructions for Postgres from a list of nodes; apply op as last step
like: '%s->%S->%s->>%s' for path={a: {b: {c: value } } }, op='->>'
Don't use this unless extract_value_at_path and contains_key_at_path don't work for you
"""
fmt_s... | 29fdc872b7524304d04901cfd372ec44c11fc0d2 | 640,452 |
from typing import Optional
import re
def extract_with_pattern(text: str, pattern: str) -> Optional[str]:
"""
Return the first found result of a given pattern in the string or None if not found
E.g: ('Test _t Test _t', '_t') -> '_t'
Args:
text: string to find the match
pattern: patter... | 33df16be02f4e1ece4fe3ea9e0f122cbb5f0a2f2 | 640,453 |
import six
def _annotator_error_msg(ex):
"""
Formats a human readable error message.
:param ex:
:return:
"""
if isinstance(ex, six.string_types):
return ex
return '\n' + ex.__class__.__name__ + ': ' + str(ex) + '\n\n' | 890e6105a2b932e7f7b0280befdb6bb4cf3dd454 | 640,454 |
from typing import List
def restore_ip_addresses_back(s: str) -> List[str]:
"""
:param s:
:return:
"""
def left_addresses(left_s: str, deep: int) -> List[str]:
len_left: int = len(left_s)
# print(left_s, deep)
if deep > 3: # 255.255.255.255.255
return []
... | 3efb68813d57f4a6747b645068b61fe772518429 | 640,455 |
import importlib
def _populate_ground_truth(
target_name,
spec):
"""Populates the ground truth values in a spec."""
# We do a delayed import to avoid parsing sometimes huge ground truth files.
# Also, this lets us do the import programmatically based on the passed name.
module_name = 'hmc_swindles.tar... | 27841aecd618fc0d7aecde3d0f240b7f9cb0e7f2 | 640,456 |
import os
def check_path(path):
""" Check if the path is a directory or a file and return a list of the file in the path """
list_path = []
try:
if os.path.isdir(path):
list_path = list(map(lambda x: os.path.join(path, x), os.listdir(path)))
else:
list_path.append(... | d9ff26f00d233b1fa85962af04d5590885b7136a | 640,458 |
def label_smoothed_nll_loss(lprobs, target, epsilon, ignore_index=None, reduce=True):
"""compute labeled smoothed nll loss
Returns:
loss: the actual loss to be optimized (after smoothing), with
shape (batch) if reduce is true else (batch, seq_len)
nll_loss: the NLL loss with shape (... | 7438656e0bbdfc43fc2c6d29b792e038a795d6cd | 640,459 |
import sys
import os
def is_bundled():
"""Determines whether the current Python executable is a `.par` bundle."""
return sys.argv[0].endswith(".par") or not os.getenv("RUNFILES_MANIFEST_FILE") | c66460b02152e3312bd38a1d02611291649f0a68 | 640,460 |
def FirstValidDatum(data, default=None):
"""Gets the first valid datum or default.
Args:
data (list[event_data.EventDatum]): list of event data.
default (object): returned in case no no valid datum was found.
Returns:
event_data.EventDatum|object: first valid datum or default value.
"""
for datu... | 60a65696d62fffd205750efcda52a2df8cf8301c | 640,461 |
import argparse
def get_arguments():
"""Parse all the arguments provided from the CLI.
Returns:
A list of parsed arguments.
"""
parser = argparse.ArgumentParser(description="DeepLabLFOV Network Inference.")
parser.add_argument("--dataset-path", type=str,
help="Path t... | fae9dc91014dc37f7800f61965070b694f12ec0e | 640,462 |
def _getoffsets(lineno, lineindex, data):
"""Return the (start, end) byte offsets for a given 1-based line number."""
offset = 0
if 1 <= lineno < len(lineindex):
offset = lineindex.select(lineno - 1)
else:
raise IndexError
nextoffset = lineindex.select(lineno)
# there is at least one newline, but there may be... | f03408ec2ed7432a38e0f21c217b72b04cdfaa85 | 640,464 |
from typing import Sequence
from typing import Any
from typing import Optional
from typing import Type
def has_types_sequence(item: Sequence[Any]) -> Optional[tuple[Type[Any], ...]]:
"""Returns types contained in 'item'.
Args:
item (Sequence[Any]): item to examine.
Returns:
Optional[... | 0cd65e1d4f10fd4a1aa83ed83d71d7e09f8e8eae | 640,465 |
def makeCommDataDict(data):
"""
returns a dictionary of attributes from the comment
"""
data_dict = {}
#get awards if any
if data['total_awards_received']:
data_dict['total_awards_received'] = data['total_awards_received']
else:
data_dict['total_awards_received'] = 0
... | 6e6d7a8367e8259a63bb460ed10a8b7d03b838ed | 640,467 |
import numpy
def unbinning(binnedArray, binsize, norm=True):
"""
:param binnedArray: input ndarray
:param binsize: 2-tuple representing the size of the binning
:param norm: if True (default) decrease the intensity by binning factor. If False, it is non-conservative
:return: unBinned input ndarray
... | e23ae5822f2172582b6c524bbbcfc80c6053e58f | 640,468 |
def get_okta_group_name(prefix, account_id, role_name):
"""
Return an Okta group name specific to an account.
The format of the group name is '<prefix>_<account_id>_role'.
"""
group_name = prefix + "_" + account_id + "_" + role_name
print(f"get_okta_group_name() result is {group_name}")
retu... | 8723bab3addceaf905f889c3239156289314a46d | 640,469 |
def generate_char_set(classes, repeat_times):
"""returns a full list of characters for the user to input"""
return [c for c in classes for i in range(repeat_times)] | d7785509744686bca8f7876209455401af62853f | 640,470 |
def get_pipe_nightdir():
"""
Return the name of the subdirectory containing per-night files.
Returns (str):
The name of the subdirectory.
"""
return "night" | e3b4fe399d3827d6d61792718171078e9321331e | 640,471 |
def distribute_surplus(candidates, exhausted, quota):
"""
Returns the given list of Candidates with the surplus votes from the
Candidate with the most surpluss votes transfered to their next
preference.
"""
max_surplus = max([c.surplus(quota) for c in candidates])
bigge... | 4fc0daf53adebc929e338cd870f9a775dcbf6a7f | 640,472 |
def synth_hangul(string):
"""Convert jamo characters in a string into hcj as much as possible."""
raise NotImplementedError
return ''.join([''.join(''.join(jamo_to_hcj(_)) for _ in string)]) | 68cad2aadd78fb2cd2a27ef97be4e484c361fe7d | 640,473 |
def is_ufshost_error(conn, cloud_type):
"""
Returns true if ufshost setting is not resolvable externally
:type conn: boto.connection.AWSAuthConnection
:param conn: a connection object which we get host from
:type cloud_type: string
:param cloud_type: usually 'aws' or 'euca'
"""
ufshost... | 6f48a3792a9860635406f1310d7c4a5ef158d175 | 640,474 |
def count_ops_by_type(node, op_type: str, start: int, limit: int = 50):
"""
:param op_type: type of operation (ex. 'producer_reward_operation')
:param start: start queries with this block number
:param limit: limit queries until start-limit+1
"""
count = {}
for i in range(start, start-limit,... | a411f9ede6fc43cbb72f51b1eb2413c827002406 | 640,475 |
import numpy as np
def numpy_train_test_split(data_folder, train_set, test_set):
"""
create target classes for training and test data using numpy
"""
train = np.loadtxt(data_folder+train_set, skiprows=1, delimiter=',')
x_train = train[:, 1:]
y_train = train[:, 0, np.newaxis] - 1.
... | 650378e7f76822fd49d12735dd0356f92b2bc8bf | 640,476 |
def get_separator(handle):
""" get the column separator (assumes same on all lines)
"""
current = handle.tell()
line = handle.readline()
handle.seek(current)
if line.count('\t') > line.count(' '):
return '\t'
else:
return ' ' | 57033e4a14a0189666dcb484119c2e6a3566a658 | 640,477 |
def cycle_checker(head):
"""Check if the Singly Linked List is cyclic.
Returns boolean value based on the result
"""
marker_1 = head
marker_2 = head
flag = False
while marker_2 != None and marker_2.next_node != None:
marker_1 = marker_1.next_node
marker_2 = marker_2.next_no... | 6367a9651074a423295cabfef5942a1d14291719 | 640,478 |
def gcd(a, b):
"""
Euclidean alg
"""
r = {0: a, 1: b} # remainders
q = {} # quotients
m = 1
while r[m] != 0:
q[m] = r[m - 1] // r[m]
r[m + 1] = r[m - 1] - (q[m] * r[m])
m += 1
m -= 1
return r[m] | 329179b66d87532e1e2d1d8c7bf7521f98f992be | 640,479 |
import re
def remove_comments_from_sql(sql: str) -> str:
"""
Removes comments from SQL query
:type sql str|None
:rtype: str
"""
return re.sub(r"\s?/\*.+\*/", "", sql) | 2c86ee8e10dd888e892258667587d3c976ea48a0 | 640,480 |
import codecs
import sys
import unicodedata
def read_utf8(filepath):
"""read_utf8() is a function that reads text in as UTF-8 NFKD normalized text strings from filepath
:param filepath: the filepath to the text input file
"""
try:
f = codecs.open(filepath, encoding='utf_8', mode='r')
excep... | 8e9ce92b22922355d934a59807ed3daa4048285d | 640,481 |
def _fields_as_tuple(field):
"""
Common representation of UnischemaField for equality and hash operators.
Defined outside class because the method won't be accessible otherwise.
The only difference is that the type name of the `codec` field is returned
so that the codec object ID won't differentiat... | dae626eb2e930343d69b1ced99c016f99f48bc9a | 640,482 |
def get_domain_name():
"""
Returns the domain name of the current configuration from a config file
Returns
-------
string
the domain name
"""
with open("/var/www/logic_webapp/webapp_config") as file:
line = file.readline()
domain = line.split("=")[1].rstrip() # ... | 00ca5acfcb1d1842a439a27d5591f326e9ebebcf | 640,483 |
import time
def write_generator_lines(conctimes, concaz, concel, concva, concve, az_flags, el_flags):
"""
Produces a list of lines in the format necessary to upload to the ACU to complete a
generated scan. Params are the outputs of generate.
Params:
conctimes (list): List of times starting a... | 2fb671e5111a9b8ee7ca7f64f107e69a69a4dc2c | 640,485 |
def _loh_to_vcf(cur):
"""Convert LOH output into standardized VCF.
"""
cn = int(float(cur["C"]))
minor_cn = int(float(cur["M"]))
if cur["type"].find("LOH"):
svtype = "LOH"
elif cn > 2:
svtype = "DUP"
elif cn < 1:
svtype = "DEL"
else:
svtype = None
if s... | 2f527251efafaa358b8e84cf2c2afb0a0f7b6653 | 640,486 |
def binarysearch(minim,maxim,function, flips_to_true=True):
"""
function needs to return a boolean whether the solution is ok
this implementation is for function that starts with false for minim and flip to true
for TTTTFFFF, pass set flips_to_true flag to false. This flag is important to set correc... | 6f54f55f4a4e9bf4fee941fa772719a6289e3113 | 640,487 |
from typing import List
def get_preprocessor_command(
rootname: str,
basename: str,
includes: List[str],
filename: str,
slides: bool) -> List[str]:
"""Calculate preprocessor command, based on file name and slide switch."""
command = [
'slide_preprocessor',
... | 89758b04b7259d8e2ca8c68c889bb265d6618b3c | 640,488 |
from typing import Dict
from typing import Any
from typing import Optional
def to_dot(
config: Dict[str, Any],
prefix: Optional[str] = None,
separator: str = '.',
function_to_name: bool = True,
) -> Dict[str, Any]:
"""Convert nested dictionary to flat dictionary.
:param config:
The po... | 5d08d669c7e9758177b3bcc178581dfef33a9eab | 640,489 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.