content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def fail_addr():
"""An address that nothing is listening on
"""
return '192.0.0.0', 1000 | 30533ba4565acb44b827af62740acdd088251893 | 687,534 |
def classify(model, filepath):
""" return a dictionary formatted as follows:
{
'predicted y': <'2016' or '2020'>,
'log p(y=2016|x)': <log probability of 2016 label for the document>,
'log p(y=2020|x)': <log probability of 2020 label for the document>
... | 5039d39473c36a9df228ad87fe2bfcc3921889b2 | 687,535 |
def unique_paths_with_obstacles(obstacle_grid: list[list[int]]) -> int:
"""
>>> print(unique_paths_with_obstacles([[0,0,0],[0,1,0],[0,0,0]]))
2
>>> print(unique_paths_with_obstacles([[0,1],[0,0]]))
1
>>> print(unique_paths_with_obstacles([[0,1,0],[0,0,0],[0,0,1]]))
0
"""
# If the ob... | de854da00b5c7e8608dbc7f8a4d352fc61956f28 | 687,536 |
import csv
def allstrands(allstrandfile,redux=False):
"""reads sequence identifiers and sequences from CSV into a dictionary."""
strandsdict={}
csvfile = open(allstrandfile)
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
data = csv.reader(csvfile, dialect)
# ... process ... | c49e4005af9d60050567d3e50833cd4c03ff7164 | 687,537 |
def get_parameter_value(parameters, parameter_name, value_key='value'):
"""Returns the parameter value.
:param parameters: parameter list
:param parameter_name: parameter name
:param value_key: parameter key containing the value
:rtype : str
"""
for item in parameters:
if item['name... | cb54d7c20d3a9a6790e0c16c0c78e0e05d24f9d9 | 687,538 |
def get_frequency_by_index(index: int) -> int:
"""
-> 0 1 2 3 4 5 6 7 8 ...
<- 0 1 -1 2 -2 3 -3 4 -4 ...
"""
sign: int = -1 if index % 2 == 0 else 1
return ((index + 1) // 2) * sign | badb2bf83177643c955d4c157c6f4514302fc1b1 | 687,539 |
def authorization_error(error) -> str:
"""Unauthorized request."""
return error | f66b5bea96402b945faf9f3fe72243cca2b45e51 | 687,540 |
import inspect
import six
import re
def expand_docstring(**kwargs):
"""Decorator to programmatically expand the docstring.
Args:
**kwargs: Keyword arguments to set. For each key-value pair `k` and `v`,
the key is found as `${k}` in the docstring and replaced with `v`.
Returns:
Decorated function... | fef19e81def3c27cac5e90d310363489a8251f20 | 687,541 |
def evaluate_type(value):
"""Evaluates the type in relation to its value
Args:
value : value to evaluate
Returns:
Evaluated type {integer,number,string}
Raises:
"""
if isinstance(value, list):
evaluated_type = "array"
elif isinstance(value, dict):
evalu... | 109253f7e66e69d82f67e2b762e8afcd8f3c8020 | 687,542 |
def unique_vals(rows, column_number):
"""Find the unique values from a column in a dataset based on column number"""
return set([row[column_number] for row in rows]) | e009ae12b8c3f56168ab5849b30a3b655500faf2 | 687,543 |
import re
def get_u_boot_test_base():
"""
Get the text base of u-boot from the .config file
"""
r = re.compile('CONFIG_SYS_TEXT_BASE=(.*)')
with open('.config', 'r') as f:
for l in f.readlines():
m = r.search(l)
if m:
return m.group(1) | 82fac3ca7d372478fd329536b99cf4288a34e4f9 | 687,545 |
def collapse_repeats(sequence):
"""Collapse repeats from sequence to be used for PER"""
result = []
prev = None
for x in sequence:
if x == prev:
continue
result.append(x)
prev = x
return result | d9d9ff8bffbd6104ff109a55682525c701be9166 | 687,546 |
def _load_data_spacy(data_path, inc_outside=True):
"""
Load data in Spacy format:
X = list of sentences (plural) / documents ['the cat ...', 'some dog...', ...]
Y = list of list of entity tags for each sentence
[[{'start': 36, 'end': 46, 'label': 'PERSON'}, {..}, ..], ... ]
inc_outside = Fal... | 11613013174abba8847aceb88cec932a5ab71312 | 687,547 |
def mult_frag(a, b):
"""
Multiply two lists.
:param a: First list
:param b: Second list
:return: The result of multiplying the two lists
"""
p = zip(a, b)
result = 0
for (a, b) in p:
result += a * b
return result | b94c7570252a2addb94f853d200e24fc5325aaaf | 687,548 |
import inspect
def get_command_callargs(command_name: str):
"""get callargs from a vsdownload function"""
return inspect.getcallargs(eval(f"vsdownload.{command_name}")) | b02c584a2de3637d611f267c715ba619f8f99374 | 687,549 |
def is_valid_trajectory(ext):
""" Checks if trajectory format is compatible with GROMACS """
formats = ['xtc', 'trr', 'cpt', 'gro', 'g96', 'pdb', 'tng']
return ext in formats | 2673343cb15886ea056a408c29ae9f23e2eb9e53 | 687,550 |
def to_str(s):
"""
将字节数组转成成字符串
:param s: 字节数组
:return: 字符串
"""
if bytes != str:
"""
这里的比较在python2中是True,在Python3中是False
"""
if type(s) == bytes:
return s.decode('utf-8')
return s | 1dd9e69a07243ec62e4d31861e201fff72e0d4e7 | 687,551 |
import math
def HermitianHat (tempo,dilat,posic ):
"""Retornar um array das posições de uma OndaLet(Chápeu de Hermitian) em relação ao tempo
Argumentos:
tempo: um Numpy Array com os pontos do sinal que serão exibido
dilat: O valor de dilatação da Wavelet
posic: O valor da posição ... | d42744ded948c837eedb90362c13229a14f0002c | 687,552 |
def GetClr(idx=0, scheme=1): # color
"""
Get ordered color
=================
"""
if scheme==1:
C = ['blue', 'green', 'magenta', 'orange', 'red', 'cyan', 'black', '#de9700', '#89009d', '#7ad473', '#737ad4', '#d473ce', '#7e6322', '#462222', '#98ac9d', '#37a3e8', 'yellow']
elif scheme==2:
... | 15d1dfa67d95ed71adfb5a7e69544087ef21c68f | 687,553 |
import math
def to_precision(x,p):
"""
returns a string representation of x formatted with a precision of p
Based on the webkit javascript implementation taken from here:
https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp
"""
x = float(x)
if x == 0... | b383752ae6c07b737f219e1a5ce1bc4915eeb08d | 687,554 |
def get_resolvers():
""" Get local system resolvers """
resolvers = []
try:
with open( '/etc/resolv.conf', 'r' ) as resolvconf:
for line in resolvconf.readlines():
line = line.split( '#', 1 )[ 0 ];
line = line.rstrip();
if 'nameserver' in l... | 38d2ad49e857d48180925f99abf6ef18b57b6fb4 | 687,555 |
def is_hilbert_number(n):
"""
Simply check whether n is positive and the remainder of n is equal to 1
modulus 4.
"""
return n > 0 and n % 4 == 1 | b55825b446282343cb87e3d6c83036a6bc9f1a6a | 687,556 |
def string_to_list_only_digit(word):
"""
Take each character of the 'word' parameter and return a list
populated with all the characters. The if clause allows only
the digits to be added to the list.
:param word: string
:return: list of digit inside 'word'
"""
return [c for c in word if ... | 9c5078e16515d93d0e3bb35376ee93c60119e71d | 687,557 |
def flatten_beam_dim(x):
"""Flattens the first two dimensions of a non-scalar array."""
if x.ndim == 0: # ignore scalars (e.g. cache index)
return x
return x.reshape((x.shape[0] * x.shape[1],) + x.shape[2:]) | 4480ef5421407030f5cf217883600dbd4e63e196 | 687,558 |
def calc_stuff(value, *args):
"""Do some calculations"""
result = {"this": value}
return result | 64d34f985e434a67e2ee29c411c41a414aa64b3b | 687,559 |
def calendars_config_track() -> bool:
"""Fixture that determines the 'track' setting in yaml config."""
return True | e877fad2b55ede8c066b838365fb0acf98484d87 | 687,560 |
import subprocess
def get_git_data(repo):
"""Return the hash and date of the current git commit."""
out_sha = subprocess.run(['git', 'rev-parse', 'HEAD'], cwd=repo,
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
out_date = subprocess.run(['git', 'show', '-s', '--format=%ci'], cwd=repo,
... | 9241afb522d67c05c41f122ab9ad8464c46a4cbc | 687,561 |
def get_oxygen(data, index=0):
"""
Determines the oxygen rating by recursively removing all values with the least sum per bit for each bit.
:param data: Array of binary numbers as Stings.
:param index: Starting index for the recursion.
:return: The last remaining binary number of the complete input... | 04f028fc207123b1cce1cbae5026b6c8c8faabc6 | 687,562 |
import os
def get_override_paths():
"""Get the override config path(s). Consults the envrionment vairiable
RFB_SITE_PATH, RFB_SHOW_PATH, and RFB_USER_PATH
Returns:
str: The path(s) to the override config files
"""
paths = []
# first, RFB_SITE_PATH
RFB_SITE_PATH = os.environ.... | ee3fe428ca67f830b52e565a3c1abc878d920296 | 687,563 |
import pty
import os
def port(request):
""" http://allican.be/blog/2017/01/15/python-dummy-serial-port.html """
_, slave = pty.openpty()
return os.ttyname(slave) | 27309041894143080e0254c2af2de88dd02befff | 687,565 |
def verificar_arquivo(nome_arquivo='passwords'):
"""Verifica se o arquivo que conterá as senhas já existe.
Keyword Arguments:
nome_arquivo {str} -- (default: {'passwords'})
Returns:
[bool] -- [Se já existir recebe True, senão recebe False]
"""
try:
arquivo = open(n... | db035dd3b191118c831cc7f735e7bddd0d3a3c11 | 687,566 |
def get_fields_with_datatype(
dataset_ids: list, field_info: dict, data_format: str
) -> dict:
"""
Returns the column name and its data type by looking up stream and log_fields json file.
If a mapping column name is not present in log_fields.json it returns
the column name as `col<idx>` and its dat... | ffbb112078abee51d769d44f80a6a200e9404322 | 687,567 |
import struct
def int_array_return(raw_bytes, specifier='I'):
""" Convenience function that splits a command return into a tuple of
evenly-spaced arguments.
Args:
specifier -- A single letter specifying the way the integer is to be
encoded. Should be one of the format let... | 828601aeb7f44c348a32b070463757ee98703856 | 687,568 |
def corr(x, y):
"""
Correlation of 2 causal signals, x(t<0) = y(t<0) = 0, using discrete
summation.
Rxy(t) = \int_{u=0}^{\infty} x(u) y(t+u) du = Ryx(-t)
where the size of x[], y[], Rxy[] are P, Q, N=P+Q-1 respectively.
The Rxy[i] data is not shifted, so relationship with the continuous
... | 81bf68fa32fc8ade3f349aa6e851c4a1fbce928b | 687,569 |
def pRDP_asymp_subsampled_gaussian_best_case(params, alpha):
"""
:param params:
:param alpha: The order of the Renyi Divergence
:return: Evaluation of the pRDP's epsilon
See Example 20 of Wang, Balle, Kasiviswanathan (2018)
"""
sigma = params['sigma']
prob = params['prob']
n = param... | 9dabb8ba68c065d6346aeb775cffc72029ab9d4a | 687,570 |
import string
def make_title(line):
"""
Edits the given line so that it can be used as a title.
Edit operations include removing unnecessary punctuations and converting the text into title case
:param line: line of the poem chosen as the title
:return: title of the poem
"""
# Removing pun... | 15b91f0c8918122a201490603dc707be15053eac | 687,571 |
from typing import Counter
def filter_min(counter: Counter, min_freq: int):
""" Filter counter by min frequency """
return Counter({t: c for t, c in counter.items() if c >= min_freq}) | 56b77dc486ad41fc7004b1db10f85a4813f835b3 | 687,572 |
def stack_map(topology):
"""Return dict mapping node ID to stack type
Parameters
----------
topology : Topology
The topology
Returns
-------
stack_map : dict
Dict mapping node to stack. Options are:
source | receiver | router | cache
"""
stack = {}
for v... | b33531bd931428d8214dd5e969e057a5159a4b2a | 687,574 |
def add(I1, I2):
"""Calculate the addition of two intervals as another interval
Keyword arguments:
I1 -- the first interval given as a tuple (a, b)
I2 -- the second interval given as a tuple (c, d)
"""
(from1, to1) = I1
(from2, to2) = I2
return (from1 + from2, to1 + to2) | 77a0b4a336da94e7b7d1690e750a82ee333efb3d | 687,575 |
def _is_lt_position(first: tuple, second: tuple, position):
"""Compare the tuple at given position."""
if len(first) > position and first[position] is not None:
if len(second) > position and second[position] is not None:
return first[position] < second[position]
return False # canno... | 74df79c3da2f3d5c9b1e39a1c1651eb79ab90727 | 687,576 |
import re
import warnings
def clean_address(problem_address):
"""Format the address so it is usable by the geocoder.
Parameters
----------
problem_address: str
The address that needs to be cleaned.
Returns
-------
str: The cleaned address.
"""
# clean the Apartment info ... | f45d5e70331fe82580cb7ed559b67181e18e4838 | 687,577 |
import timeit
def _time_func(f, N, k=3, msg=True):
"""Basic version of IPython's %timeit magic"""
t = min(timeit.timeit(f, number=N) for _ in range(k))
t_per = t / N
if msg:
if t_per < 1e-6:
units = 'ns'
t_per *= 1e9
elif t_per < 1e-3:
units = 'µs'
... | d973b8bfcbf5277bd011f299268f30bb34724d7b | 687,578 |
def mk_time_info_extractor(spec):
"""
Returns a function that will extract information from timestamps in a dict format.
The specification should be a list of timetuple attributes
(see https://docs.python.org/2/library/time.html#time.struct_time) to extract,
or a {k: v, ...} dict where v are the tim... | 808382a459064a31e95c481b16c66f92a0e70a16 | 687,579 |
def validate(identifier):
"""Validates a student id from the Pontifical Catholic University of Chile
Args:
identifier: student identifier (string or number)
Returns:
True if it is valid, False otherwise
"""
if not identifier:
return False
identifier = str(identifier)
... | 0d58b8659774852894d96efeb6ad9acef6c05d13 | 687,580 |
def _get_default_outcome_dict(args):
"""Litani's default behavior if the user does not specify an outcome table.
This is not a constant dict as it also depends on whether the user passed in
command-line flags that affect how the result is decided, like
--ignore-returns etc.
"""
outcomes = []
... | 1c17fdb015b21acdd3807830492b1e282e52993c | 687,581 |
def has_feature(df, feat):
"""Adds a boolean feature if a feature exists or now"""
return df[feat].notna().astype(int) | a33f01fce5e1369b8dd60a100de318dce5d6bb9e | 687,582 |
import sys
def is_platform_little_endian() -> bool:
"""
Checking if the running platform is little endian.
Returns
-------
bool
True if the running platform is little endian.
"""
return sys.byteorder == "little" | c8bf7647114fc649164f6e29f326fb7ae1437013 | 687,583 |
def intcomma(number, locale='en_US'):
""" """
if -999 < number < 999:
return str(number)
result = str()
print(number)
while number:
number, digit = divmod(number, 10)
print(digit, end=' ')
print()
return result | 7c69b56bf6938a01e74a39dc069b98087f3c8704 | 687,585 |
def get_unique_notes_in_channel(notes_in_channel):
""" Utility function to get an ordered set of unique notes in the channel """
all_notes = []
for notes in notes_in_channel:
all_notes.append(notes.note)
return sorted(set(all_notes)) | 898490d74811d36f9fbd37f62ed043336b0accdb | 687,586 |
def timetuple(s):
"""htime(x) -> (days, hours, minutes, seconds)"""
s = int(s)
d, s = divmod(s, 86400)
h, s = divmod(s, 3600)
m, s = divmod(s, 60)
return (d, h, m, s) | bef78c744a5e5c8ef0c045ee045047a00b655761 | 687,587 |
def get_whitespace_cnt(line):
""" Return a count of leading tabs/spaces as (tab_cnt, space_cnt). """
tab_cnt = 0
space_cnt = 0
testline = line
while testline.startswith('\t'):
tab_cnt += 1
testline = testline[1:]
testline = line
while testline.startswith(' '):
space_c... | 719e2db0f045b30f715170ee1aec0e24bab87134 | 687,588 |
import re
import os
import tempfile
def replace_patterns_in_file(file_path, patterns, once=True):
"""Replace regular expressions in a file.
Args:
file_path: File to act on.
patterns: Can take several formats:
- (str, str) replaces first pattern by second string.
- [(st... | cdae03da7c408ba742b2c333caeaae4492c57a6a | 687,589 |
def numero_digitos(n):
"""
recursão com operações adiadas
"""
if n< 10:
return 1
else:
return 1+ numero_digitos(n//10) | 6f5081a71928702dca89c3454bc9c8930f6b940c | 687,590 |
def combine_words(word_rm: str, next_word: str, text_tokenized: list[str]) -> tuple[str, list[str], bool]:
""" Combines two words that were separated by a hyphen to form a new one. """
word: str = word_rm + next_word
text_tokenized.append(word)
return word, text_tokenized, True | 4a1b4be373f4df67d6926368068474f0b208f270 | 687,591 |
def are_strings_in_subdict(mapper, subdict, strings_of_interest, string_for_mapper):
"""
Search an element of a sub-dictionary to determine whether a particular string is present in it. Mostly for use in
calculating outputs in the model runner module.
Args:
mapper: Dictionary describing the pur... | e4e30748c9311e33f2ebb0ff4c034e99a17b2c0b | 687,592 |
import os
import yaml
import sys
def config_read(config_file="~/.piavpn"):
"""Read config in yaml format.i
---
server_url:
server_ip:
namespace:
"""
try:
with open(os.path.expanduser(config_file), "r") as file:
config = yaml.load(file, Loader=yaml.FullLoader)
excep... | 45cbf16d5afaddd32a349677efee3a1da272fea2 | 687,593 |
import numpy
def get_class_labels(y):
"""
Unique labels within list of classes
Args:
y: (N,) list of labels
Return:
a (M,) no.ndarray of unique labels
"""
return numpy.unique(y) | 9b8a990286475e8ec8c6d7c6c2ad7234da26804d | 687,594 |
import re
def argv_to_pairs(argv):
"""Convert a argv list to key value pairs. For example,
-x 10 -y 20 -z=100
{x: 10, y: 20, z: 100}
"""
arg_dict = {}
i = 0
while i < len(argv):
if argv[i].startswith('-'):
entry = re.sub('-+', '', argv[i])
items = entry.s... | e375d2cfc835d33c44f3646e41668852fb8be6d7 | 687,595 |
def _pixel_distance(a_x1, a_x2, b_x1, b_x2):
"""Calculates the pixel distance between bounding box a and b.
Args:
a_x1: The x1 coordinate of box a.
a_x2: The x2 coordinate of box a.
b_x1: The x1 coordinate of box b.
b_x2: The x2 coordinate of box b.
Returns:
The pixel distanc... | 3ebfd8576240ad662c7c41ebae22733b2354f01b | 687,596 |
def stress_calculation(self):
"""
"""
#
output = []
output.append("\n")
output.append("{:}\n".format(88*"_"))
output.append("\n")
output.append(" STRESS CALCULATIONS\n")
output.append("\n")
output.append("Pipe ID Sh [N/mm2] SL [N/mm2] Fx ... | 1345330e1d141bba58db370fc0823b20a147c927 | 687,597 |
def global_mean(ratings):
"""
:param ratings: initial data set (sparse matrix of size nxp, n items and p users)
:return: the global mean of the non zero ratings of the matrix
"""
# compute mean over non zero ratings of the train
mean = ratings[ratings.nonzero()].mean()
return mean | 55eb4eea0ef1347254dfa98dc59e1737f97198df | 687,598 |
def rapi_controller_get_district_by_id(district_id): # noqa: E501
"""Returns a district object with the specified ID
# noqa: E501
:param district_id:
:type district_id: int
:rtype: District
"""
return 'do some magic!' | 3a63b2e4c56c78e18db8442755568b75309b8e1e | 687,599 |
def extract_function_from_command(command):
"""
Extracts and returns the function used in the current command.
for example: `lc.ln(a,52)` -> ln
:return: function name
"""
function_name = command.split(".")[1]
end_index = function_name.index("(")
function_name = function_name[:end_index]... | d4f1859b6e1026f700f097c1b871444ed8b6b535 | 687,600 |
from typing import Tuple
def _partition_satellite_input(
line: Tuple[str, str],
num_partitions: int = 2) -> int: # pylint: disable=unused-argument
"""Partitions Satellite input into tags (0) and rows (1).
Args:
line: an input line Tuple[filename, line_content]
num_partitions: number of partition... | 5e49ce2de504fffed10069b1812fcb2224de1277 | 687,601 |
def cleanup_vm_data(vm_data, uuids):
""" Remove records for the VMs that are not in the list of UUIDs.
:param vm_data: A map of VM UUIDs to some data.
:type vm_data: dict(str: *)
:param uuids: A list of VM UUIDs.
:type uuids: list(str)
:return: The cleaned up map of VM UUIDs to data.
:... | e433b450ceb608bcc094581ee040c180f370b0f8 | 687,602 |
def extract_solution(G, model):
""" Get a list of vertices comprising a maximal clique
:param G: a weighted :py:class:`~graphilp.imports.ilpgraph.ILPGraph`
:param model: a solved Gurobi model for maximum clique
:return: a list of vertices comprising a maximal clique
"""
clique_node... | 3625a16bea6366a0107c8b3bf1ba8361e5fac9d6 | 687,603 |
import random
def random_horizontal_flip(image, bboxes):
"""
Randomly horizontal flip the image and correct the box
:param image: BGR image data shape is [height, width, channel]
:param bboxes: bounding box shape is [num, 4]
:return: result
"""
if random.random() < 0.5:
_, w, _ = i... | 2a865b32a9ed94fdee35b4b075313a5e9d733e90 | 687,605 |
def make_graph(values, lower_limit=0.0, upper_limit=100.0, style="blocks"):
"""
Draws a graph made of unicode characters.
:param values: An array of values to graph.
:param lower_limit: Minimum value for the y axis (or None for dynamic).
:param upper_limit: Maximum value for the y axis (or None for... | e83fd64890b41eb8d8d05d88cad19dfdda061725 | 687,606 |
def do_two(Sol=341.0, epsilon=0.55, albedo=0.3):
"""
Calculate equlibrium fluxes for a two-layer atmosphere
Parameters
----------
Sol: float
day/night averaged TOA shortwave flux (W/m^2)
epsilon: float
longwave emissivity of layers 1 and 2
albedo: float
... | f19b1381d543b52af51a5fe29ad767ae0efb2023 | 687,607 |
def intersect_ray_plane(o,w,p,n):
"""[Compute the intersection point between a ray and a plane]
Args:
o ([ndarray]): [ray origin]
w ([ndarray]): [ray direction]
p ([ndarray]): [plane origin]
n ([ndarray]): [plane normal vector]
Returns:
[ndarray]: [intersection point... | 9878afb4438aff91ead49cc9c15ed4042f909688 | 687,609 |
def widget_generator(klass, fields):
"""
Takes in a class and a list of tuples consisting of field_name and an attribute dictionary
:param klass: Class of the input widget
:param fields: List of tuples mapping field names to attribute dictionaries
:return: A dict of input widget instances
"""
... | 5e09950148f902ace17b6f52e06ee0f16760c195 | 687,610 |
def prep_irreg_asc_event_lines(lines, ev_name):
""" uses quotes to force annoying events into usable chunks
use sparingly - not super fast right now
"""
new_lines = []
if ev_name == 'MSG':
# name, onset, label, content
# easy - just break content into a third, quoted column
f... | 0d2bcf21155a2ee5c19f6f3287e90ad153814a2e | 687,611 |
def cap_allele(allele, cap=5):
""" Cap the length of an allele in the figures """
if len(allele) > cap:
allele = allele[:cap] + '*'
return allele | 92bd675d98369fbb0201e1aa436ef94b45aefa51 | 687,612 |
def py2_replace_version(argv):
"""
Workaround for Python 2.7 argparse, which does not accept empty COMMAND
If `-V` or `--version` present and every argument before it begins with `-`,
then convert it to `version.
"""
try:
ind = argv.index('--version')
except ValueError:
try... | 09039442a242f98771569491500f08e9b8d58ecc | 687,613 |
from typing import Any
import inspect
def from_object(obj: Any) -> bool:
"""Returns True, if the docstring of `obj` is the same as that of `object`.
Args:
name: Object name.
obj: Object.
Examples:
>>> class A: pass
>>> from_object(A.__call__)
True
>>> from... | 3f31bf4a13341a6952ecd1460cf7200d23f4edcb | 687,614 |
def rhs_replace(rhs, sublist, replacement):
"""Replace occurrences of sublist in rhs with replacement."""
sublist = tuple(sublist)
rhs = tuple(rhs)
if len(sublist) > len(rhs):
raise ValueError
if not sublist:
raise ValueError
new_list = []
idx = 0
while idx < len(rhs):
if rhs[idx:idx + len(s... | 9af00d6098536dbc032470e53bce87db1d07f5df | 687,615 |
import argparse
def create_parser() -> argparse.ArgumentParser:
"""Creates parser for input arguments.
Structuring the argument parsing code like this eases automated testing.
"""
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)... | 10320547af2b6888f991d49b7aa791b91d24d385 | 687,616 |
from typing import Tuple
def bruteforce(t:str, p:str) -> Tuple[int, int]:
""" Returns location, & no. of comparisons both of type int """
comps, offset, rv = 0, 0, None
while (rv == None) and not(offset > len(t) - len(p)):
for i in range(len(p)):
comps += 1
if (p[i] != t[i+... | f33e72f54de4fccea5616bbd3202e27ee8691416 | 687,617 |
import importlib
import pkgutil
def get_submodule_names(module_name):
"""
Returns a list of the module name plus all importable submodule names.
"""
module = importlib.import_module(module_name)
submodule_names = [module_name]
try:
module_path = module.__path__
except AttributeErr... | a3939cee553f0ecf462df25f9535eb7485db5abe | 687,618 |
def two_bytes_to_int(hi_byte: int, low_byte: int) -> int:
"""
Converts two bytes to a normal integer value.
:param hi_byte: the high byte
:param low_byte: the low byte
:return: converted integer that has a value between [0-65535]
"""
return ((hi_byte & 0xFF)*256) + (low_byte & 0xFF) | 979f59ebb860c2294eaa644609345f1146e6dc0b | 687,620 |
import os
def test_pidE(pid): # returns errinfo, too
""" Check For the existence of a unix pid ... possibly a string. """
try:
pid = int(pid)
os.kill(pid, 0)
except OSError as exc:
return False, exc.errno, os.strerror(exc.errno)
else:
return True, '', '' | 8e5b61e98ce94961b057df0798d59459dc9388cb | 687,621 |
from typing import List
import tempfile
def concatenate_data_files(data_files: List[str]):
"""Create temp file to hold all concatenated results for this test."""
outfile = tempfile.NamedTemporaryFile()
for filename in data_files:
with open(filename) as infile:
outfile.write(str.encode... | 27d6f3c07f83199d4d6c8514ac9686c2a91bc35c | 687,622 |
def cached(key):
""" Cache the results of a conversion in the data set.
"""
def wrapper(function):
def wrapped(d,g,i):
if key not in d:
d[key] = function(d,g,i)
return d[key]
return wrapped
return wrapper | 2d396650f25f768d9314544f6eda5f5340e3614e | 687,623 |
def time_interval_since(date_1, date_2):
""" Calculate seconds between two times
Arguments:
date_1 -- datetime object #1
date_2 -- datetime object #2
Output:
Num of seconds between the two times (with a sign)
"""
return (date_1 - date_2).total_seconds() | 6a5f11b0e2705a4e577e037ba43dfed6bda06be4 | 687,624 |
def PySequence_Check(space, w_obj):
"""Return 1 if the object provides sequence protocol, and 0 otherwise.
This function always succeeds."""
return int(space.issequence_w(w_obj)) | 0c7ec7b4c311fad77c83e39d27c0395b9cab36b3 | 687,625 |
from datetime import datetime
def convert_to_datetime(globus_time):
"""
Converts a time given in Globus format to datetime.
Globus format for time is as follows:
YYYY-MM-DD HH:MM:SS+00:00
"""
# use space separator to seperate date and time
times = globus_time.split(" ")
date_part ... | 4e2945eb084aaa0b5dc64a77c1d2988ae9f83445 | 687,626 |
def brook(x):
"""Brook 2014 CLUES subhalo mass function.
Keyword arguments:
x -- array of peak subhalo halo masses
"""
tr = ((x/1.e10)/38.1)**-0.89
return tr | f4b98303a8181e0a03dcf4ed604373e10f429640 | 687,627 |
import torch
def gauss(x, c, sigma):
"""
isotropic
"""
return torch.exp(-0.5 * torch.norm(x - c, dim=-1)**2 / sigma**2).unsqueeze(-1) | 0b9bddad6df2e93f2fd02e51918d43c6c03a2765 | 687,628 |
def sum67(nums):
"""Solution to the problem described in http://codingbat.com/prob/p108886
Ex:
>>> sum67([1, 2, 2])
5
>>> sum67([1, 2, 2, 6, 99, 99, 7])
5
>>> sum67([1, 1, 6, 7, 2])
4
:param nums: list
:return: int
"""
sum = 0
between_6_and_7 = False
for n in n... | a035a1443378d33852b6bbdc785a97210af0c866 | 687,629 |
def GetArcsIn(target):
"""All incoming arc types for this specified node."""
arcs = {}
for triple in target.arcsIn:
arcs[triple.arc] = 1
return arcs.keys() | 68db1302ae205252bc7a2ba903f9bc7cb40de297 | 687,630 |
def convert_decimal_to_dms(elem):
"""Convert latitude/ longitude decimal form to dms form
Keyword arguments:
elem -- latitude or longitude in decimal form
"""
d = int(elem)
m = int((elem - d) * 60)
s = int((elem - d - m/60) * 3600)
return (d, m, s) | 69d2932163bbea02ee2144503e847a411b74137f | 687,631 |
import inspect
def _get_argspec(func):
"""Helper function to support both Python versions"""
if inspect.isclass(func):
func = func.__init__
if not inspect.isfunction(func):
# Init function not existing
return [], False
parameters = inspect.signature(func).parameters
args = ... | 21ce8dcb470e2458309785b0bac2c5d23f10e269 | 687,632 |
import pickle
def get_temp_data(filename, directory='temp', extension='.temp'):
"""get temp data from disk"""
if '.temp' not in filename:
filename += extension
try:
with open(directory + '/'+ filename, 'rb') as f:
data_file = pickle.load(f)
f.close()
pr... | b8dde5ca72b1774c26a2020a2dcf9a561b133aed | 687,633 |
def read_config():
"""
read JSON config file for topic options
"""
topic_data = {
'platform_type': ['buoy','station','glider'],
'ra': ['aoos','caricoos','cencoos','gcoos','glos','maracoos','nanoos','neracoos','pacioos','secoora','sccoos'],
'platform': ['a','b','c','d','e','f','g'... | d972dd866cfcf47a37000c8917658076e7ffb165 | 687,634 |
def fileinfo_clean(table):
"""
Delete entries in table that have been previously marked for removal.
Params:
table {fileinfo} - table to delete entries from
Returns:
deleted (int) - number of entries deleted
"""
deleted = 0
for k, v in {**table}.items():
if v.flag... | 45143f1de4cb9695ef00a63294d78f52e1f0b555 | 687,635 |
def calculate_accumulation_distribution(open, high, low, close, volume):
"""
Calculates changes in accumulation/distribution line.
A/D = ((Close - Low) - (High - Close))/(High - Low)
Args:
open: Float representing exchange rate at the beginning of an interval
high: Float representing th... | d9f6bf6966f854082262313d5d6a7e51711af9b6 | 687,636 |
from datetime import datetime
def datetime_name(output_name):
"""Creates a filename for the output according to the given format."""
now = datetime.now()
return f'{output_name}-{now.strftime("%Y-%m-%d-%H-%M")}.csv' | 43662f53042d5a1f9b8c395c8965b093eb6fb65e | 687,637 |
def boxes_required(qty, box_capacity=6):
"""
Calculate how many egg boxes will be required for a given quatity of eggs.
:param qty: Number of eggs
:param box_capacity: How many eggs will fit in a box
:return: The number of boxes that are required
"""
return int(qty / box_capacity) + 1 | fe0604b7da779244189a5f32be6ab293e4ae79ca | 687,638 |
def get_info(path):
"""
Read token from file in path.
Whole file will be read.
"""
with open(path) as file:
return file.read() | d83ca4f2c43b9b7691ab3506ffe692b528b8816b | 687,639 |
def create_metadata(array, transform, driver='GTiff', nodata=0, count=1, crs="epsg:4326"):
"""Creates export metadata, for use with
exporting an array to raster format.
Parameters
----------
array : numpy array
Array containing data for export.
transform : rasterio.transform affine obj... | c1b4e6479bc62e0a9322a645baa307ced1d8d469 | 687,640 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.