content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import shlex
def parse_bed_track(line):
"""Parse the "name" field of a BED track definition line.
Example:
track name=146793_BastianLabv2_P2_target_region description="146793_BastianLabv2_P2_target_region"
"""
fields = shlex.split(line) # raises ValueError if line is corrupted
assert fields[... | 0a01dec05aec13d73e38388e8e87b817f52e58f3 | 650,869 |
from typing import List
def parameter_order(config) -> List[str]:
"""
Return the order in which the parameters occur in the given dockerfile.
This is needed for optimising the order in which the images are built.
"""
order = list()
for line in config.dockerfile:
order += [
... | 4f02e4c04c9afb936699323714d3d9c2e0cc2317 | 650,871 |
import json
def read_config(filepath):
"""
Read the config from a given config file.
:param filepath: The path to the config file.
:type filepath: str
:return: The json deserialized list.
:rtype: list
"""
file = open(filepath, 'r')
file_content = file.read()
config_list = json... | eb5bf005b021fcbd7300a0d9325d8e4e34a22215 | 650,873 |
def sample_proxs(z, y, step=1):
"""
computes prox_(step * f)(z)
where
f(z) = 0.5 * (z - y) ** 2
"""
return (z + step * y) / (1 + step) | 83dbb236a207a8eb9b27a235de89d6a1da334208 | 650,880 |
def to_dictionary(words):
"""
Helper function to convert list of words into a dictionary.
"""
return dict([(word, True) for word in words]) | f5af7e5d4a2789e8a53f1dc1b443a3acae2aa32b | 650,882 |
def get_info_link(content, html=False):
"""Return info popover link icon"""
return (
'<a class="sodar-info-link" tabindex="0" data-toggle="popover" '
'data-trigger="focus" data-placement="top" data-content="{}" {}>'
'<i class="iconify text-info" data-icon="mdi:information"></i>'
... | 66e0d514c9c0b892d906db21ee2dbb3631fb6394 | 650,885 |
def python_format(a, prec, align=''):
"""Format an array into standard form and return as a string.
args:
a: the array
prec: the precision to output the array to
align: anything that can go before the . in python formatting
"""
format_ = (f' {{:{align}.{prec}E}}' * a.shape[1] + ... | bc5027370843ec2e921da9b9c619d216109c3cec | 650,888 |
import re
def is_image_set_grouped(pipeline):
"""
Report if the pipeline will group image sets. Returns **True** if image sets will be grouped.
* pipeline: a list where each item is a line from a CellProfiler `*.cppipe` file.
"""
is_grouped_bool = False
for line in pipeline:
... | 1e0a102c1adc26cf5d44d357b4663c3bfb2a5327 | 650,892 |
import struct
def read_uint32(buffer: bytearray) -> int:
""" Read an unsigned 32-bit integer, read bytes are consumed.
"""
res, = struct.unpack('<I', buffer[:4])
del buffer[:4]
return res | 2977916a05fd65e32f3543f4ad0ca14f371b212c | 650,896 |
import math
def atan2(x, y):
"""Get the arc tangent of x, an angle in radians.
The signs of x and y are used to determine what quadrant the angle is in.
The range of result values is [-π, π]
"""
return math.atan2(x, y) | f4fd7da227becee6cc0d16117d02eae6e352e6e1 | 650,899 |
def get_segment_times(csv_df, breaks=None, no_energy=False, music=False, noise=False):
"""
Filter an InaSeg output CSV of segmented time ranges.
The parameters `no_energy`, `music`, and `noise` are optional bools which
filter for the "noEnergy", "music", "noise" labels in segmented time ranges.
The... | 130b2da85ba9c28f1aea709bd5b297c7cdb63f53 | 650,904 |
from datetime import datetime
def is_current(record,year):
"""
Utility function to check whether a record is valid for the current year.
Since records contain different information about dates, as appropriate,
there are multiple conditions that must be tested.
a) if a record contains only a YEAR,... | 7c8f7689fb0169895d9d6bbb1db902b730f23879 | 650,906 |
def apply_formatter(formatter, *args, **kwargs):
"""
Used by QAbstractModel data method
Configures a formatter for one field, apply the formatter with the new index data
:param formatter: formatter. If can be None/dict/callback or just any type of value
:param args:
:param kwargs:
:return:
... | 1a7b5294845b86cdf64d3985bf8e6a12734fe2ce | 650,907 |
from typing import List
def readable_list(seq: List[str]) -> str:
"""
Return a grammatically correct human readable string (with an Oxford comma).
All values will be quoted:
[foo, bar, baz]
becomes
"foo," "bar," and "baz"
"""
# Ref: https://stackoverflow.com/a/53981... | 7a006c9026cb9f52fd710b8c40cdfd0a4d0b33ae | 650,909 |
import re
def _grep_prop(filename, prop_name):
"""
Look for property in file
:param filename: path to file and file name.
:param prop_name: property to search for in file.
:return: property value or None.
"""
fdata = open(filename, "r").read()
obj = re.search("^{0} = ['|\"](.+)['|\"]$"... | 7e604f0a1069ee93bee0486802a2d516318fef4b | 650,910 |
def q_zero(bits=8):
"""
The quantized level of the 0.0 value.
"""
return 1 << (bits - 1) | bb4ea5bfb8a7e31b125195e17cc2412eb27d9589 | 650,911 |
from typing import Union
def object_type(object_ref: Union[type, object]) -> type:
"""Get type of anything.
Args:
object_ref (type, object): Object or type
Returns:
type: Type of given object
"""
return object_ref if isinstance(object_ref, type) else type(object_ref) | bd306913e8e884c89fa5dec863ee316a5d0f1456 | 650,914 |
def _read_params(test_file_name):
"""Return expected errors, warnings, and return value for test file."""
with open(test_file_name) as f:
exp_ret_val = 0
exp_errors = []
exp_warnings = []
for index, line in enumerate(f.readlines()):
ret_mark = "// Return:"
... | 3ee6278505ffe062b19ff7fdd0846e0de320dd48 | 650,915 |
from datetime import datetime
def date_str_from_datetime_str(datetime_str):
"""Convert a datetime string to a date string, e.g. 2020-07-04 12:00:00 to 2020-07-04"""
try:
return datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
except ValueError:
return datetime_str | 7337bbc3e93e431924d2d1d4b27d291ce3e355c6 | 650,917 |
def calculate_max_series(series):
"""
Calculate the maximum of a series
:param series: list of values where we want to know the maximum of.
:return max(series): highest value in the series
"""
assert type(series) is list and len(series) != 0
return max(series) | de8ba05f580e2de4ca6e0737e5db61352bf1e266 | 650,919 |
from typing import List
def parentheses_status_eliminate(string: str) -> str:
"""Check is expression string has balanced parentheses (using stack elimination).
In every iteration, the innermost brackets get eliminated (replaced with empty string).
If we end up with an empty string, our initial one was ba... | 9cfd7d6c2fb25e0e98fa8f9dd770a51b65d2b982 | 650,925 |
def query_transform(context, include_page=False, **kwargs):
"""
Returns the URL-encoded querystring for the current page,
updating the params with the key/value pairs passed to the tag.
E.g: given the querystring ?foo=1&bar=2
{% query_transform bar=3 %} outputs ?foo=1&bar=3
{% query_transform ... | 4e1361b174a910dd5e2fceef2eaec5bbbf89387b | 650,926 |
def kequivalent(springs, config):
"""
Given a list of spring constant values and their configuration,
returns the equivalent spring constant
"""
if config == 'parallel':
return sum(springs)
elif config == 'series':
return 1 / sum((1 / n for n in springs))
else:
raise... | e8fcb140dc916fd218f622ca7b85b1915895f71c | 650,927 |
import torch
def uncertainty_separation_parametric(mu, var):
"""Total, epistemic and aleatoric uncertainty
based on a parametric (normal) variance measure
M = length of input data x, N = number of distributions
Args:
mu: torch.tensor((M, N)): E(y|x) for M x and N distr.
var: torch.t... | 35211b6b7d66cce2a5fa2c62b35fde4c38bdaed2 | 650,940 |
def unset_nth_bit(n: int, i: int) -> int:
"""
Unset the n-th bit.
>>> bin(unset_nth_bit(0b11111111, 0))
'0b11111110'
>>> bin(unset_nth_bit(0b11111110, 0))
'0b11111110'
"""
return n & ~(1 << i) | b8d23d849ac06e34df0c79846d85adf87e8e3fe2 | 650,946 |
def _get_category_bounds(category_edges):
"""Return formatted string of category bounds given list of category edges"""
bounds = [
f"[{str(category_edges[i])}, {str(category_edges[i + 1])})"
for i in range(len(category_edges) - 2)
]
# Last category is right edge inclusive
bounds.appe... | 6891a29d3a20ebd9c6f84e700a39fe55db3e8134 | 650,947 |
def rma(data, length):
"""Rolled moving average
Arguments:
data {list} -- List of price data
length {int} -- Lookback period for rma
Returns:
list -- RMA of given data
"""
alpha = 1 / length
romoav = []
for i, _ in enumerate(data):
if i < 1:
romo... | a852c85efec5262bd17c38651db8798667865b7d | 650,949 |
def numberSeparators(number, separator=' '):
"""
Adds a separator every 3 digits in the number.
"""
if not isinstance(number, str):
number = str(number)
# Remove decimal part
str_number = number.split('.')
if len(str_number[0]) <= 3:
str_number[0] = str_number[0]
e... | b0f56403708bc489b94b83f7f8bcffe6db29b564 | 650,950 |
def youtube_mocker(mocker):
"""Return a mock youtube api client"""
return mocker.patch("videos.youtube.build") | d00a93fdd722ec3a75d5979d1aae7fecf29ea38d | 650,952 |
def twoNumberSum(array, targetSum):
"""
twoNumberSum finds the two numbers whose sum is equals to targetSum with the
binary search strategy.
array: the collection of numbers that can sum the target number.
targetSum: the target number to find.
returns a list with the two nu... | 16737c859a76267729571526847bbaa098d8d8a0 | 650,955 |
def getContinuousRuns(x):
"""
Given a 1D array, find all of the continuous runs
of 1s, and count the numbers with a certain length
:param x: 1D array
:returns Runs: A frequency distribution dictionary of
the form {length:counts}
"""
Runs = {}
(IN_ZEROS, IN_ONES) = (0, 1)
stat... | b6fea1eee29bf4eb8c947e55de34410298a13fc6 | 650,956 |
def ask_value(message):
"""
Ask user to type some value. Ask again if no answer.
Arguments:
- message (string): message to display
Return (string): value typed by user
"""
answer = input(message)
if answer == '':
return ask_valu... | ae937cc38c2f7402548f43465f6210a2a64dea66 | 650,960 |
def get_ip_from_raw_address(raw_address: str) -> str:
"""
Return IP address from the given raw address.
>>> get_ip_from_raw_address('91.124.230.205/30')
'91.124.230.205'
>>> get_ip_from_raw_address('192.168.1.15/24')
'192.168.1.15'
"""
return raw_address.rsplit('/')[0] | 07d9fa9ae41f0c84e109d925114f56a1efccbe66 | 650,969 |
import math
def get_foldrate_at_temp(ref_rate, new_temp, ref_temp=37.0):
"""Scale the predicted kinetic folding rate of a protein to temperature T, based on the relationship ln(k_f)∝1/T
Args:
ref_rate (float): Kinetic folding rate calculated from the function :func:`~ssbio.protein.sequence.properties... | c90586cfb0500f82f247444c7767943126a58292 | 650,984 |
def safeOpen(filename):
"""Open a utf-8 file with or without BOM in read mode"""
for enc in ['utf-8-sig', 'utf-8']:
try:
f = open(filename, 'r', encoding=enc)
except Exception as e:
print(e)
f = None
if f != None:
return f | 59c391e8df2fba38f2620fc579286a13061553bf | 650,987 |
def get_ip(request):
"""
Returns ip address or None if the address is in an unexpected format
"""
ip_address = request.META['REMOTE_ADDR']
return ip_address | 02eaedeb9555cbac06c13208d3f74f8de8e48dfd | 650,991 |
def reduce_next_sentence_label_dimension(batch):
"""Change next_sentence_labels's shape from (-1, 1) to (-1,).
Args:
batch: A dictionary mapping keys to arrays.
Returns:
Updated batch.
"""
batch['next_sentence_labels'] = batch['next_sentence_labels'][:, 0]
return batch | 32731bd22eb28693e336ca981d897feaacd8c816 | 650,993 |
def binary_search(array, val):
"""Binary search."""
sorted_array = sorted(array)
i = 0
j = len(array) - 1
while i <= j:
mid = (i + j) // 2
if sorted_array[mid] == val:
return mid
if sorted_array[mid] < val:
i = mid + 1
else:
j = mid... | e0dc1386f9b5c2f8896df0c92419b125ff566add | 650,994 |
def _get_network_layer_sizes(net_params):
"""Infer the architecture of the simply connected network from the parameters"""
dense_params = [p for p in net_params if len(p) > 0]
all_dense_layer_sizes = [p[1].size for p in dense_params]
dim_in = all_dense_layer_sizes[0]
dim_out = all_dense_layer_sizes[... | ea6ab4b6306d36241adfe41e6cd6b9df98b9cfee | 650,995 |
from typing import Tuple
def convert_to_pixel_coords(location: Tuple[float, float],
center_of_image_in_global: Tuple[float, float],
center_of_image_in_pixels: Tuple[float, float],
resolution: float = 0.1) -> Tuple[int, int]:
"""
... | 2af3010ba3ceec8d75e62b47182ff92f62580c20 | 650,997 |
def params_from_cmd(args):
"""Extract the parameters for prepare_training_data from the command line and return a dict"""
params = {
"maps_list": args.maps_list,
"xyz_limits": args.xyz_limits,
"output_dir": args.output_dir,
"slices": args.slices_per_axis,
}
return params | 803f3937c747ea15c052e07878c9709905055e26 | 651,000 |
def spherical(r_1, r_2, E_1, E_2, vu_1, vu_2, P_guess=None):
"""Returns the contact parameters for two spheres in contact or for a sphere in contact with a flat surface. In the case of a flat surface, enter None for the radius.
Parameters
----------
r_1 : {None, float}
Radius of sphere... | b09ad3851e144b00343c76a03a6ac2cba61983c0 | 651,004 |
import posixpath
def split_entry_ext(path):
"""Like os.path.splitext, but take off .tar too.
Taken from `pip._internal.utils.misc.splitext`.
"""
base, ext = posixpath.splitext(path)
if base.lower().endswith('.tar'):
ext = base[-4:] + ext
base = base[:-4]
return base, ext | 5e8e412db5b6790123313fb6e5fc34f32a85d839 | 651,007 |
def encode_proto_bytes(val: str) -> bytes:
""" Encodes a proto string into latin1 bytes """
return val.encode('latin1') | 26e46ebec820defdd2226c7446b0b878e6eca3eb | 651,012 |
def compute_shape(coords, reshape_len=None, py_name=""):
"""
Computes the 'shape' of a coords dictionary.
Function used to rearange data in xarrays and
to compute the number of rows/columns to be read in a file.
Parameters
----------
coords: dict
Ordered dictionary of the dimension na... | 6bbbcc85c70614d7f17265b0ebe28657b5c318be | 651,014 |
import re
def check_uuid(uuid):
"""Check if the string contains a proper UUID.
Supported format: 71769af6-0a39-4242-94be-1f84f04c8a56
"""
regex = re.compile(
r'^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z',
re.I)
match = regex.match(uuid)
return b... | f44ec3b98453795011b27a9f778a98389f85ae6e | 651,016 |
def joinstr( sep, *args ):
"""Join the arguments after converting them to a string"""
return sep.join( map( str, args ) ) | eb2bf997b78182dc6fb2d4e2153d219077d16086 | 651,021 |
def filter_dataframe(df, user=None, begin=None, end=None, rename_columns={}):
"""Standard dataframe preprocessing filter.
This implements some standard and common dataframe preprocessing
options, which are used in very many functions. It is likely
simpler and more clear to do these yourself on the Dat... | 27513297b1915ae0b8840f8245c5e60fd89dc31c | 651,022 |
def tax_input_checker(typed_input):
"""
Returns true if the input string cannot be converted to a float, and false if otherwise
"""
try:
f = float(typed_input)
except ValueError:
return False
return True | a69dbec5b61ef28e615389d63be22ee252ffde55 | 651,023 |
import random
import string
def gen_id(value, count=16):
"""Jinja2 filter to generate a random ID string"""
random.seed(value)
letters = string.ascii_uppercase
return ''.join(random.choice(letters) for i in range(count)) | e6b1ff862435c9a7a5664501d29ed01ab03ba27c | 651,027 |
def check_wide_data_for_blank_choices(choice_col, wide_data):
"""
Checks `wide_data` for null values in the choice column, and raises a
helpful ValueError if null values are found.
Parameters
----------
choice_col : str.
Denotes the column in `wide_data` that is used to record each
... | a9564026133dea68f17ee9b099feec409828707a | 651,028 |
import inspect
from typing import Type
def is_class(the_class: Type) -> bool:
"""
Returns true if the object passed is a class
:param the_class: the class to pass
:return: true if it is a class
"""
return inspect.isclass(the_class) | 0e1be0609a9a0fdbd9677469fef5ee8aa79df181 | 651,029 |
def card_html_id(card):
"""Return HTML id for element containing given card."""
return f'c{card:02d}' | 27f884b9bb407f5f862d1748323eb1eb982178f9 | 651,030 |
import threading
def daemon_thread(target, *args, **kwargs):
"""Makes a daemon thread that calls the given target when started."""
thread = threading.Thread(target=target, args=args, kwargs=kwargs)
# NOTE(skudriashev): When the main thread is terminated unexpectedly
# and thread is still alive - it wi... | 0534ea32cdaa2fd1de18c56530049932bf8961b4 | 651,033 |
def _get_var_name(bdd, u):
"""
Given a variable index u in the BDD, return the variable
Name
"""
var_index = bdd["t_table"][u][0]-1
return bdd["var_order"][var_index] | 2d32cf56ea53d4583264baaadbea6d7a81eedecf | 651,035 |
def check_dictionary_values(dict1: dict, dict2: dict, *keywords) -> bool:
"""Helper function to quickly check if 2 dictionaries share the equal value for the same keyword(s).
Used primarily for checking against the registered command data from Discord.
Will not work great if values inside the dictionary ca... | 46b537ea1353c29c9ada561a0469b8f6658501c3 | 651,036 |
import re
def well_formatted_reps(exercises: list) -> list:
"""Filter out badly formatted reps from the list of exercises"""
good_format = lambda exc: re.match(r'\d+-\d+', exc[1])
return list(filter(good_format, exercises)) | aa174fe965503d879cb8192e6a1fe06ef8dd52de | 651,038 |
def storage_max_constraint_rule(backend_model, loc_tech, timestep):
"""
Set maximum stored energy. Supply_plus & storage techs only.
.. container:: scrolling-wrapper
.. math::
\\boldsymbol{storage}(loc::tech, timestep) \\leq
storage_{cap}(loc::tech)
"""
return bac... | a7b21b62da20f0c57d9a86706d13794f9f0bed75 | 651,043 |
import torch
def nll(x_pred, x_true, log_p, t_pred=None, t_xz=None, hidden=None):
""" Negative log likelihood """
return -torch.mean(log_p) | c5b57041a3cf2d17cc182bdce602ba23684a2dfb | 651,044 |
def score(word, f):
"""
word, a string of length > 1 of alphabetical
characters (upper and lowercase)
f, a function that takes in two int arguments and returns an int
Returns the score of word as defined by the method:
1) Score for each letter is its location in the alphabet... | bd70e138c6f5508371fc8b25926caee638e3b37c | 651,051 |
def pick_icon(icon):
"""Convert Dark Sky API icon data-point to weather-icons.css format"""
icon = "wi-forecast-io-" + icon
return icon | 5811ce298fbb8dc3840f2b6bcf63405278baeb9a | 651,052 |
def stripdefaults(target, removeempty=list(), removeexact=dict()):
""" Make output dicts smaller by removing default entries. Keys are
removed from `target` in place
Args:
target (dict): dictionary to remove entries from
removeempty (list): Remove keys in this list from target if the key
... | 120727952cbfb8e8393374dfbd1b7e37c04fd071 | 651,053 |
def prep_s3(biodata_bucket, run_bucket, output_folder):
"""Prepare configuration for shipping to S3.
"""
return {"type": "S3", "buckets": {"run": run_bucket, "biodata": biodata_bucket},
"folders": {"output": output_folder}} | 7dbcef7a250bfe5f0fc2a41d779a6cedad074732 | 651,055 |
def apparent_extract_to_real_extract(original_extract, apparent_extract):
"""
Apparent Extract to Real Extract in degrees Plato
:param float original_extract: Original degrees Plato
:param float apparent_extract: Apparent degrees Plato of finished beer
:return: Real degrees Plato of finished beer
... | 2e55fa2f4b1ca3b0f2689db49da8c43438993aa3 | 651,056 |
def envs_to_exports(envs):
"""
:return: line with exports env variables: export A=B; export C=D;
"""
exports = ["export %s=%s" % (key, envs[key]) for key in envs]
return "; ".join(exports) + ";" | ac4d4d187e189cc5432b12fa0891ba97403a06c7 | 651,058 |
from typing import List
def _index_of_first_non_option(tokens: List[str]):
"""
Find the index of the first token that doesn't start with `-`
Returns len(tokens) if none is found.
"""
return next(
(index for index, token in enumerate(tokens) if token[0] != "-"),
len(tokens),
) | 74c6eb41b7fa46a7edf5e151f22fe1dd4503f3b5 | 651,059 |
def to_list(str_rep_list: str) -> list:
"""
Convenience function to change a string representation of a Python list into an actual list object.
:param str str_rep_list: String that represents a Python list. e.g. "['0.5', '2.0']"
:return: The parsed representative string.
:rtype: list
"""
in... | 2c15a7285ce82dad8e21c769b75d46322e1acfe2 | 651,063 |
import stringprep
def b1_mapping(char):
"""Do RFC 3454 B.1 table mapping.
:Parameters:
- `char`: Unicode character to map.
:returns: u"" if there is `char` code in the table, `None` otherwise.
"""
if stringprep.in_table_b1(char):
return u""
else:
return None | 1ea68669bfc6508f909cc255f72b97be3f1bd23e | 651,066 |
from functools import reduce
def operate(func, *dicts):
"""Apply func to values of *dicts and return the result."""
result = [value for d in dicts for value in d.values()]
result = reduce(func, result, 1)
return result | 8be9a0f415ef21a82d88334bbe859c62f619feaf | 651,068 |
def get_altitude_from_level(level_number):
"""Get geopotential altitude from level number.
Args:
level_number (int): Number of level.
Returns:
float: Altitude in meters above mean sea level.
"""
# Altitudes (heights above mean sea level) corresponding to barometric altitude levels... | 2a015d91c787b14491a8952127850d648b3aad1c | 651,071 |
def parse_subcommand(command_text):
"""
Parse the subcommand from the given COMMAND_TEXT, which is everything that
follows `/iam`. The subcommand is the option passed to the command, e.g.
'wfh' in the case of `/pickem wfh tomorrow`.
"""
return command_text.strip().split()[0].lower() | 56fce623c9a51b0c64e8600d2121f6ee531bc4b1 | 651,072 |
def _account_for_bubble_fields(sg_entity_type, field_name):
"""Detect bubble fields and return the proper entity type and field name.
:param str sg_entity_type: The intput entity type name. If the field name
is a bubbled field notation, this value will be replaced by the
parsed entity type in t... | 677f7d22a2a0422b5f424bddc05c5be054004563 | 651,075 |
def _get_index(indices, index_name):
"""
Get Index from all the indices.
:param indices: DED indices list
:param index_name: Name of the index
:return: DED Index
"""
for index in indices:
if str(index) == index_name:
return index | 6a6704d6b91d80c57d748414b0947e65a6c2697e | 651,076 |
def stan_init(m):
"""Retrieve parameters from a trained model.
Retrieve parameters from a trained model in the format
used to initialize a new Stan model.
Parameters
----------
m: A trained model of the Prophet class.
Returns
-------
A Dictionary containing retrieved parameters of... | b3da4c8b7383a61982ab9673a52dc1c40a58365a | 651,081 |
from datetime import datetime
def _human_readable_delta(start, end):
"""
Return a string of human readable time delta.
"""
start_date = datetime.fromtimestamp(start)
end_date = datetime.fromtimestamp(end)
delta = end_date - start_date
result = []
if delta.days > 0:
result.appe... | d11af629f1bb9db238616d3eb847d205f5238512 | 651,086 |
def get_subclasses(c):
"""Get all subclasses of a class.
Args:
c (type): Class to get subclasses of.
Returns:
list[type]: List of subclasses of `c`.
"""
scs = c.__subclasses__()
return scs + [x for sc in scs for x in get_subclasses(sc)] | 9c4977a091e0de85daab284a7d7778a88d79ac1f | 651,088 |
def data_from(file_: "str") -> list:
"""Returns data from given file."""
data = []
with open(file_, "r") as f:
for line in f.readlines():
data.append(line.replace("-", " ").replace(":", "").split())
return data | 1e84bdf32487e994c635af00b0b48963f515b17f | 651,089 |
def process_request_items(items):
"""takes a list of 2-tuples
returns dict of list items
uses first value of tuple as key, and
uses second value of tuple as value
"""
request_dict = {}
for item in items:
request_dict[item[0]] = item[1]
return request_dict | 1ecb6ecf1b4cc937181a6fcdf39de130be8d9c19 | 651,092 |
def bbox_crop(x, bbox):
"""
Crop image by slicing using bounding box indices (2D/3D)
Args:
x: (numpy.ndarray, shape (N, ch, *dims))
bbox: (list of tuples) [*(bbox_min_index, bbox_max_index)]
Returns:
x cropped using bounding box
"""
# slice all of batch and channel
... | a7e9f5b805c363a7efaee0491a42c2960a2f69f5 | 651,093 |
import requests
import json
def request_dataset_metadata_from_data_portal(data_portal_api_base: str, explorer_url: str):
"""
Check the data portal metadata api for datasets stored under the given url_path
If present return dataset metadata object else return None
"""
headers = {"Content-Type": "ap... | d18c364c4d76d1eebde54e44277ce56823a505b5 | 651,096 |
def add_currency_filter_to_query(query, currency):
"""
Adds the currency filter to the query
:param query: the query dictionary
:type query: dict
:param currency: currency type
:type currency: str
:return: the query dictionary
:rtype: dict
"""
if "filters" not in query["query"]:... | a69579e37914064d8d6327f74db929b4827c41f6 | 651,098 |
def swe_headerfile_name(dt, infile_type):
"""Return SWE headerfile name for a given datetime"""
dtstr = dt.strftime('%Y%m%d')
if infile_type.upper() == 'UNMASKED':
return 'zz_ssmv11034tS__T0001TTNATS{}05HP001.txt.gz'.format(dtstr)
elif infile_type.upper() == 'MASKED':
return 'us_ssmv11... | ced0ea1dfd518fab1148c36677738702d8377a8e | 651,099 |
import torch
def to_concatenated_real(input, flatten=None, dim=-1):
"""Map real tensor input `... x [2 * D]` to a pair (re, im) with dim `... x D`."""
assert flatten is None
return torch.cat([input.real, input.imag], dim=dim) | 369d7d444e038f67ea066233982abb39231dd432 | 651,100 |
def get_books_by_publisher(data, ascending=True):
"""Returns the books by each publisher as a pandas series
Args:
data: The pandas dataframe to get the from
ascending: The sorting direction for the returned data.
Defaults to True.
Returns:
The sorted data as a pandas series... | e1f309c7e2796bb22d611af403871c9971e43e81 | 651,103 |
import socket
def from_address(address):
"""
Reverse resolve an address to a hostname.
Given a string containing an IPv4 or IPv6 address, this functions returns
a hostname associated with the address, using an LRU cache to speed up
repeat queries. If the address does not reverse, the function ret... | 87b739edc1795bedbcc8f0cbc337f9a17364b6e9 | 651,109 |
def update_route_events(veh, timeind):
"""Check if the next event from a vehicle's route_events should be applied, and apply it if so.
route_events are a list of events which handles any lane changing behavior related to
a vehicle's route, i.e. route events ensure that the vehicle follows its route.
Ea... | 3a79f2372c5ef3c40c0bb4e74b966c1b9927db4f | 651,112 |
def modified_dict(input_dict, modification_dict):
"""Returns a dict, with some modifications applied to it.
Args:
input_dict: a dictionary (which will be copied, not modified in place)
modification_dict: a set of key/value pairs to overwrite in the dict
"""
output_dict = input_dict.copy()
output_dict... | e67e366552702df523b4f3dfdd262674ac3a9340 | 651,113 |
from typing import Optional
def parse_bool(value: str, default: Optional[bool] = None) -> Optional[bool]:
"""
Parse bool from some quintly tables being a string with the value "1" or "0"
Args:
value (str): The value from the quintly dataframe
default (Optional[bool]): Default value in cas... | 3251c486002aaf933131f11ef2d60c49f3ce317b | 651,115 |
def notes(*num, sit=False): # Function to return a dictionary and check all the conditions
"""
=> Program that checks the quantify of school grades, highest, lowest, the class mean and the student's situation
:param num: variable that receive the amount of notes
:param sit: (optional) if wish know the... | dcc3833756045eae4a1e6e863e4a782403663512 | 651,118 |
def convert_units(typ,constant,f,t):
"""Converts units
type should be one of them
'metric','time'
f and t should be one of them:
'pico','nano','micro','mili','centi','deci','base','deca','hecta','kilo','mega','giga','tera'
Attributes
----------
constant: int
constant numb... | c4737204db5316264be69c54d26a3640de05f7f3 | 651,119 |
import textwrap
def wrap(text, width, *args, **kwargs):
"""
Like :func:`textwrap.wrap` but preserves existing newlines which
:func:`textwrap.wrap` does not otherwise handle well.
See Also
--------
:func:`textwrap.wrap`
"""
return sum([textwrap.wrap(line, width, *args, **kwargs)
... | 555b157a253750b3e2239df700a72efd5efa897c | 651,120 |
def example_image_shape(example):
"""Gets the image shape field from example as a list of int64."""
if len(example.features.feature['image/shape'].int64_list.value) != 3:
raise ValueError('Invalid image/shape: we expect to find an image/shape '
'field with length 3.')
return example.featu... | b067b311d201a47bc5035f7ddf9de9fb0605e088 | 651,121 |
def _eval_expr(expr, vals, x):
"""
This function tries calling expr.eval. Calls expr.cpp_object().eval
if the first fails. This is for FEniCS 2018.1.0 compatibility.
"""
try:
expr.eval(vals, x)
except AttributeError:
expr.cpp_object().eval(vals, x)
return None | e7453847748fc9936d54232e79f7ec87203472f1 | 651,130 |
def format_zet(state, speler, zet):
"""Opmaak van de status, speler en de zet."""
return "State: {0:<20} {1:<20} Move: {2}".format(str(state),
str(speler),
str(zet)) | 8395ca4a739c8dce151eda2e0f7bda5639b0749f | 651,132 |
from datetime import datetime
def voto(ano_nascimento):
"""
Recebe o ano de nascimento introduzido e calcula a idade do usuario,
utilizando a data atual.
:param ano_nascimento: recebe o ano de nascimento
:return: idade e status do voto
"""
idade = datetime.today().year - ano_nascimento
... | 0eaed43851da6db705e71ebe035c82b2e0a54efa | 651,135 |
def discard_search_results(searchId: str) -> dict:
"""Discards search results from the session with the given id. `getSearchResults` should no longer
be called for that search.
Parameters
----------
searchId: str
Unique search session identifier.
**Experimental**
"""
return... | 79a24e2e62754bb3a8a8d19684a93d8175aa92e8 | 651,137 |
from bs4 import BeautifulSoup
def parse_sgm_file(sgm_data):
"""
Returns a dictionary with titles + articles of an SGM file
:param sgm_data: Data read from an SGM file
:return: A dictionary mapping titles to article contents
"""
soup = BeautifulSoup(sgm_data, features="html5lib")
texts = ... | ceafdb6dac3677c93e4829e47324519f516bdf33 | 651,141 |
def range_overlap(ranges):
"""Return common overlap among a set of [left, right] ranges."""
lefts = []
rights = []
if ranges:
for (left, right) in ranges:
lefts.append(left)
rights.append(right)
max_left = max(lefts)
min_right = min(rights)
if min... | f8f8a907e6847dc308a537dab5033b8c49149674 | 651,142 |
from typing import Tuple
from typing import Optional
def get_homogeneous_type(type_dict) -> Tuple[Optional[str], bool]:
"""
Returns
-------
Optional[str]
Homogeneous-type, if any.
Ex) 'dict', 'list', 'str', 'int', 'float', 'bool', 'None', or None
bool
Whether optionally typ... | 06de05926a79b2d0c311f7bb177b54fd2341e8cd | 651,143 |
def _quote_wrap(value):
"""Wrap a value in quotes."""
return '"{}"'.format(value) | 8a5cb862c1b374b7d82c50072fe84b91a7989bbe | 651,146 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.