content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import List
def build_location_line(split_ids: List[str], keys: List[str], delimiter: str) -> str:
"""
Builds the locations and lines based on the configuration.
:param split_ids: The split IDs
:param keys: The locations or lines keys position to join from IDs
:return: The joined loca... | fbcace1da1e0bd737531f8dcfbda5644958d5d6e | 19,330 |
def get_view_model(cls):
"""
Get the model to use in the filter_class by inspecting
the queryset or by using a declared auto_filters_model
"""
msg = 'When using get_queryset you must set a auto_filters_model field in the viewset'
if cls.queryset is not None:
return cls.queryset.model
... | 7f0d3141eba794778679d0c30bfdcddbc145f63d | 19,334 |
def strategy_largest_first(G, colors):
"""
Largest first (lf) ordering. Ordering the nodes by largest degree
first.
"""
nodes = G.nodes()
nodes.sort(key=lambda node: -G.degree(node))
return nodes | 0ef116896b8e43712887888dcc79af197f7a9d17 | 19,336 |
import math
def prime_pi_upper_bound(n):
"""
Return an upper bound of the number of primes below n.
"""
ln = math.log(n)
return int(n / (ln - 1 - (154/125) / ln)) | 1a7330f50bc14e4ba20f6efedad48d55a4ccbd01 | 19,340 |
def find_animals_groups(df):
"""given a dataframe, return animals and groups dataframes based on population of
each row (> 1 == group)"""
pop_sums = df[
["Population _Male", "Population _Female", "Population _Unknown"]
].sum(axis=1)
groups = df[pop_sums > 1]
animals = df[pop_sums == 1]
... | 02a8376dcdb7abf2e3df39672650bfac8adc7c64 | 19,343 |
def word_capital(text):
"""
Capitalizes the first character of each word, it converts a string into
titlecase by making words start with an uppercase character and keep the
remaining characters.
"""
if text and len(text) > 0:
return ' '.join([s[0].upper() + s[1:] for s in text.split(' ')... | fbb20324204f62344af5b76f74fad98810f6fee0 | 19,346 |
def yields_from_leung_nomoto_2018_table10(feh):
"""
Supernova data source: Leung & Nomoto, 2018, ApJ, Volume 861, Issue 2, Id 143, Table 10/11
The seven datasets are provided for Z/Zsun values of 0, 0.1, 0.5, 1, 2, 3 and 5.
Using Zsun = 0.0169 the corresponding FeH values are -1, -0.301, 0.0, 0.301, 0.4... | 4a03971e14c80d013259afefdbece6e2c67ccdf8 | 19,349 |
def describe(path):
"""
Returns a human-readable representation of path.
"""
return "/" + "/".join(str(p) for p in path) | 7b6ba2f17379bfca88d79eb15db35a3bff183720 | 19,354 |
def _get_transform_y(element):
"""
Extracts the translateY for an element from its transform or assumes it to be 0
:return: an int representing the translateY value from the
transform or 0 if there is no transform present
"""
return element.get('transform').get('translateY') or 0 | 5c1c00843148ae384604d71c46aceaa2904a6497 | 19,358 |
def _p_r_log_helper(x, a, b, alpha, beta, n, p):
"""
Step function used with the pollard rho discrete log algorithm
"""
if x % 3 == 1:
f = ((beta * x) % p, a, (b + 1) % n)
elif x % 3 == 0:
f = ((x * x) % p, (2 * a) % n, (2 * b) % n)
else:
f = ((alpha * x) % p, (a + 1) % n... | 092f7111d3b7fb8ce8a4ba27775bdf89cb99308f | 19,362 |
def _isascii(string):
"""Tests if a given string is pure ASCII; works for both Python 2 and 3"""
try:
return len(string) == len(string.encode())
except UnicodeDecodeError:
return False
except UnicodeEncodeError:
return False | 1ef5c22b15b4953b8b9bba8ad9f5d2da0c68ee03 | 19,368 |
def get_high_cardinality_features(X, threshold=50):
"""Get features with more unique values than the specified threshold."""
high_cardinality_features = []
for c in X.columns:
if X[c].nunique() > threshold:
high_cardinality_features.append(c)
return high_cardinality_features | 4ab222c12a68c2ce259b9de41998d649d80b30ef | 19,370 |
from typing import Dict
import base64
import json
def encoded_to_json(encoded_string: str) -> Dict:
"""
Transform your encoded string to dict.
Parameters
----------
encoded_string: str
your string base64 encoded.
Returns
-------
Dict
your string cast to a dict.
""... | 37ab5fe52db9f25926f30d0e763177c8f399ff4b | 19,374 |
def createBatchSystem(config, batchSystemClass, kwargs):
"""
Returns an instance of the given batch system class, or if a big batch system is configured, a batch system
instance that combines the given class with the configured big batch system.
:param config: the current configuration
:param batch... | afff2df95a353c3138b137ccbfe5e16f22843589 | 19,379 |
def sort_in_wave(array):
"""
Given an unsorted array of integers, sort the array
into a wave like array.
An array arr[0..n-1] is sorted in wave form
if arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >=
"""
n = len(array)
for i in range(n - 1):
if i % 2 == 0 and array[i] < array[i+1]:
array[i], array[i+... | 1904a8715d2b6a8b8cbd29ed7a129ca45b1d57d0 | 19,380 |
import re
def any_match(expressions, value):
"""
Return true if any expression matches the value
"""
for exp in expressions:
if re.match(exp, str(value)):
return True
return False | 34e7aac238be92769965390a702f9a61741f9289 | 19,385 |
def subtract(a, b):
"""Subtraction applied to two numbers
Args:
a (numeric): number to be subtracted
b (numeric): subtractor
Raises:
ValueError: Raised when inputs are not numeric
"""
try:
return a - b
except:
raise ValueError("inputs should be numeric") | 7cfa9607145fb1713309fcb2e543a3a528aa26f1 | 19,389 |
def retr_smaxkepl(peri, masstotl):
"""
Get the semi-major axis of a Keplerian orbit (in AU) from the orbital period (in days) and total mass (in Solar masses).
Arguments
peri: orbital period [days]
masstotl: total mass of the system [Solar Masses]
Returns
smax: the semi-maj... | 3b5833151888490cd632b8d9a76d5bfcb268a42c | 19,390 |
def title_case(sentence):
"""
Convert a string ti title case.
Title case means that the first character of every ward is capitalize..
Parameters
sentence: string
string to be converted to tile case
Returns
-------
ret: string
Input string in title case
Examples
-----... | b4e2b58c2270af6022aaa82bbae5099ed7d07ea8 | 19,394 |
def is_duckument_type(obj):
"""Internal mapping type checker
Instead of using `isinstance(obj, MutableMapping)`, duck type checking
is much cheaper and work on most common use cases.
If an object has these attritubes, is a document:
`__len__`, `keys`, `values`
"""
doc_attrs = ("__len_... | 31aa4066d5810bb088720f96c889b36e6015583e | 19,400 |
import re
def getPrefix(name):
"""
Get common prefix from source image file name.
"""
result = re.search(r'([0-9]{2}[A-Z]{3}[0-9]{8})[-_]', name)
return None if not result else result.group(1) | 633223a5ff29005f815a29dfcaed5900c8449b83 | 19,401 |
def field_to_attr(field_name):
"""Convert a field name to an attribute name
Make the field all lowercase and replace ' ' with '_'
(replace space with underscore)
"""
result = field_name.lower()
if result[0:1].isdigit():
result = "n_" + result
result = result.replace(' ', '_')
... | b6aa8a55f660648e3d259a6b6df0f560550c7d8a | 19,406 |
def get_words_list() -> list[str]:
"""Returns a list of words from the file wordle-answers-alphabetical.txt."""
with open("wordle-answers-alphabetical.txt", "r", encoding="utf-8") as file:
words = file.read().splitlines()
return words | fa14e3ac576f93d92e6453df36010f1b51b2082b | 19,414 |
def find_idx(words, idx):
"""
Looks for the named index in the list. Test for the index name surrounded
by quotes first, if it is not present then the error will return the index name without quotes
"""
try:
return words.index('"' + idx + '"')
except ValueError:
return words.inde... | 4c76fcd752de0545cea77def672d1555c071815f | 19,415 |
def is_unicode_list(value):
"""Checks if a value's type is a list of Unicode strings."""
if value and isinstance(value, list):
return isinstance(value[0], str)
return False | c6c88770be2d1e75f800b3c22ec52a9a17384d73 | 19,416 |
import binascii
def hexarray_to_str(hexa):
"""Convert hex array into byte string."""
hstr = ''.join(["{:02x}".format(h) for h in hexa])
return binascii.unhexlify(hstr) | 59af9dad6833bb417cb9c29f60c498b8452951d7 | 19,418 |
def filter_resources(resource, filter_name, filter_value):
"""Filter AWS resources
Args:
resource (object): EC2 resource
filter_name (string): Filter name
filter_value (string/list): Filter value(s)
Returns:
List: Filtered AWS resources
"... | d72f091af78ec73a81a50dc02cbeefde94de58d9 | 19,419 |
def toggle_manual_match_form(method):
""" Hide/show field based on other values """
# This one is for manually picking years.
# 1=override (manual match). 0= auto match
# Test
if method == 1:
return "visible"
return "hidden" | 9ba3b63898f4a3c4a0bba19abe77ae218ae23275 | 19,424 |
def calculate_stimulation_freq(flash_time: float) -> float:
"""Calculate Stimulation Frequency.
In an RSVP paradigm, the inquiry itself will produce an
SSVEP response to the stimulation. Here we calculate
what that frequency should be based in the presentation
time.
PARAMETERS
... | 069165f62416a79a0ba59893c9a61d8c99d3c903 | 19,431 |
def parse_ants(antstr):
"""Split apart command-line antennas into a list of baselines."""
rv = [s.split('_') for s in antstr.split(',')]
rv = [(int(i[:-1]), int(j[:-1]), i[-1]+j[-1]) for i,j in rv]
return rv | 438abdf11acaebdc471d6d9e6f007e4d27b3f293 | 19,434 |
def clean_text(x):
"""Helper function to clean a string."""
x = str(x)
x = x.lower()
x = x.strip()
x = " ".join(x.split()) # removes extra whitespace between words
return x | 74dbb5e07c42c668cdbe380670e87e81f4678407 | 19,439 |
def getIncomparable(rs1, rs2):
"""
Return the set of problem IDs which are only solved by rs1
:param rs1: result set of the 1st approach
:param rs2: result set of the 2nd approach
:return: a set {pid, stim}
"""
inc = set()
for pid in rs1.keys():
r2 = rs2[pid]
if r2 is Non... | a8b4baa5fc43b2d9f136c63f5aabe624149a9d47 | 19,441 |
def get_n_overlapping_chunks(data_size, chunk_size, chunk_overlap):
"""Compute the number of overlapping chunks
Args:
data_size (int)
chunk_size (int)
chunk_overlap (int)
Returns:
The number of chunks.
"""
hop_size = chunk_size * (1 - chunk_overlap)
return int((... | 8ada086145d136638e5ba7703cc2095ee696fbd0 | 19,443 |
def maybe_map(apply_fn, maybe_list):
"""
Applies `apply_fn` to all elements of `maybe_list` if it is a list,
else applies `apply_fn` to `maybe_list`.
Result is always list. Empty list if `maybe_list` is None.
"""
if maybe_list is None:
return []
elif isinstance(maybe_list, list):
... | 13f61f0d7c6592dc4ea3cce091635f5119f1a70c | 19,448 |
from datetime import datetime
def format_timestamp(dt_object):
"""Formats a datetime object into a Joplin timestamp."""
return(int(datetime.timestamp(dt_object))*1000) | e728a4da2c5148a4e815af1485fc77029ef03fd0 | 19,450 |
from typing import List
def _find_index(distance_along_lane: float, lengths: List[float]) -> int:
"""
Helper function for finding of path along lane corresponding to the distance_along_lane.
:param distance_along_lane: Distance along the lane (in meters).
:param lengths: Cumulative distance at each en... | 7a36cd603d266653155e089eb0e72099210601f5 | 19,452 |
def find_submission_body_end(submission_body: str) -> int:
"""Finds the end of the story's body by stripping edits and
links at the bottom.
Returns:
the index at which the story's body ends.
"""
markers = [
'-Secrets',
'EDIT:',
'Edit:',
'Continued in [part',... | d4c533ebf322956304e38eced409a9a1c043e37c | 19,468 |
def valuefy(strings, type_cast=None):
"""
return a list of value, type casted by type_cast list
return type: list if values
By default, type cast is int
"""
vals_string = strings.split('_')
if type_cast is None:
type_cast = [int]*len(vals_string)
return [t(e) for e, t in zip(vals... | 36bc5a6ff64826877bd4f434a0e540f72c4aeb9e | 19,469 |
import pickle
def read_pickle(file):
"""Read a pickle file"""
with open(file, "rb") as handle:
return pickle.load(handle) | d074df20a4b035137efb8c1fc52f6e9fcdda7add | 19,474 |
import re
def remove_tags(sent: str) -> str:
"""
Replace every tag with "_".
Parameters
----------
sent: str
Input string on CoNLL-U format.
Returns
-------
str:
Processed string.
"""
return re.sub(
r"(^\d+(?:\-\d+)?\t*(?:[^\t]*)\t(?:[^\t]*)\t)(\w+)",
... | 9966ab60bcf1b9db19da23f48e7cc52b6dfdf580 | 19,480 |
def non_negative_int(argument):
"""
Converts the argument into an integer.
Raises ValueError for negative or non-integer values.
"""
value = int(argument)
if value >= 0:
return value
else:
raise ValueError('negative value defined; must be non-negative') | b5c447055305141144934a484efc28ee07a7c6fe | 19,482 |
def _reverse_input_einsum_eq(equation):
"""
Reverse the input order of the einsum eqaution
e.g.:
input : "nchw,nwhu->nchu"
returns : "nwhu,nchw->nchu"
"""
input_output_strings = equation.split('->')
assert len(input_output_strings) == 2, "invalid equation"
input_strings = input_outpu... | f8c2900b6592f04fdc72b85c5ffdaba4b3b34952 | 19,493 |
def select_regions(localqc_table, genomeinfo, resolution, elongation=150, maxdisp=2.5):
"""
Select regions to display based on their dispersion and their read count intensity
:param localqc_table: LocalQC regions file
:param genomeinfo: Dictionary of chromosomes' size
:param resolution: ... | adc1fd762165fd7d6170605ac11be92f370baeb1 | 19,496 |
def halosInMassRange(massColumn, minMass, maxMass, VERBOSE=True):
""" Returns the selection array which has 'True' values for halos with masses in the range 'minMass' to 'maxMass'. The masses are given by the argument 'massColumn'. """
if VERBOSE:
print(
"Selecting the halos with masses in t... | 361e7faffaf2133e222859fdbb8431704af52099 | 19,498 |
def get_P_Elc_audio_microsystem_with_md_listening(P_Elc_audio_microsystem_with_md_rtd):
"""聴取時の消費電力を計算する
Parameters
----------
P_Elc_audio_microsystem_with_md_rtd : float
定格消費電力, W
Returns
----------
P_Elc_audio_microsystem_with_md_listening : float
聴取時消費電力, W
"""
... | 20e2c58ef3c019236e131d637e19f0a50acc55de | 19,505 |
def lerp(a, b, i):
"""Linearly interpolates from a to b
Args:
a: (float) The value to interpolate from
b: (float) The value to interpolate to
i: (float) Interpolation factor
Returns:
float: Interpolation result
"""
return a + (b-a)*i | 8422222416668a70feb2a75790a25d7ab1f0af14 | 19,512 |
def strip_datetime_for_db_operations(dt):
"""
Some of our queries get very slow unless we remove the timezone info
before we put them into sql.
"""
return dt.replace(tzinfo=None) | 4cf19578afdb213f2f57a845f711ebbb96b869f6 | 19,513 |
def response(update=None):
"""
Emulates JSON response from ulogin serivce for test purposes
"""
data = {
'network': 'vkontakte',
'identity': 'http://vk.com/id12345',
'uid': '12345',
'email': 'demo@demo.de',
'first_name': 'John',
'last_name': 'Doe',
... | 8a29ba65c38d5833e1474486135a9648f860a9a6 | 19,519 |
from pipes import quote
def make_input_json_cmd(bam_fn, json_fn, sample):
"""CMD which creates a json file with content [['path_to_bam', 'sample']], which will later
be used as pbsv call input.
"""
c0 = 'echo [[\\\"{}\\\", \\\"{}\\\"]] > {}'.format(quote(bam_fn), quote(sample), quote(json_fn))
ret... | 5d50ea49027f6b7110193fed22a2990cc978c545 | 19,523 |
def iter_first_value(iterable, default=None):
""" Get first 'random' value of an iterable or default value. """
for x in iterable:
if hasattr(iterable, "values"):
return iterable[x]
else:
return x
return default | 7fac2cbbe1a6923a1f737b0a86b208a62cfe6d50 | 19,524 |
import requests
def download_tigrfam_info(tigrfam, api_endpoint):
"""
Download TIGRFAM from API endpoint.
"""
return requests.get(api_endpoint+tigrfam).text | 4573fed797c3f3e6b16330fb7dd41aa57b156db1 | 19,525 |
def is_palindrome_permutation(input_string):
"""Checks to see if input_string is a permutation of a palindrome
Using bool (is even?) instead of int value reduces space usage.
Parameters
----------
input_string : str
String to check
Returns
-------
bool
True if input_st... | 4867a94bd9051f07b04e60288739b3e98333fbda | 19,529 |
def convert_box_xy(x1, y1, width, height):
"""
Convert from x1, y1, representing the center of the box to the top left
coordinate (corner).
:param x1: the x coordinate for the center of the bounding box
:param y1: the y coordinate for the center of the bounding box
:param width: with of the bou... | 7524dd86f8c8ebff84cd9da0e75abd0b580547a0 | 19,531 |
def _get_tuple_state_names(num_states, base_name):
"""Returns state names for use with LSTM tuple state."""
state_names = [
("{}_{}_c".format(i, base_name), "{}_{}_h".format(i, base_name))
for i in range(num_states)
]
return state_names | 8d96508174ec4893e9a9812d75471303ff972248 | 19,535 |
def _position_is_valid(position):
"""
Checks if given position is a valid. To consider a position as valid, it
must be a two-elements tuple, containing values from 0 to 2.
Examples of valid positions: (0,0), (1,0)
Examples of invalid positions: (0,0,1), (9,8), False
:param position: Two-element... | f7f277a472ea7046b6029a657215fa7006a4d808 | 19,542 |
def getInv(wmap):
"""
Get the inverse map of a dictionary.
:param wmap: Dictionary
:returns: Dictionary which is an inverse of the input dictionary
"""
inv_map = {}
for k, v in wmap.items():
inv_map[v] = inv_map.get(v, [])
inv_map[v].append(k)
return inv_map | 441bfa8e543a3aa24494d290e1e3cf6baa81437e | 19,553 |
def optimal_noverlap(win_name,win_len):
"""
This function is intended to support scipy.signal.stft calls with noverlap parameter.
:param win_name: (str) name of the window (has to follow scipy.signal.windows naming)
:param win_len: (int) lenght of the FFT window
:return : (int) optimal overlap in po... | d98db08a9e08b6639a38a324799d1141e65b1eb4 | 19,554 |
def _prefix_range(target, ge, le):
"""Verify if target prefix length is within ge/le threshold.
Arguments:
target {IPv4Network|IPv6Network} -- Valid IPv4/IPv6 Network
ge {int} -- Greater than
le {int} -- Less than
Returns:
{bool} -- True if target in range; False if not
... | 536eea3be670e21065f5cd81b5f0e268d564c559 | 19,559 |
def _get_nodes_perms_key(user, parent_id=None) -> str:
"""
Returns key (as string) used to cache a list of nodes permissions.
Key is based on (user_id, parent_id) pair i.e we cache
all nodes' permissions dictionary of folder.
If parent_id == None - we will cache all root documents of given user.
... | fb3875a53c17b6a818f9bb97738a47222733af70 | 19,561 |
from typing import OrderedDict
def train(model, dataloader, criterion, optimizer, device='cpu', t=None, best_acc=None):
"""One iteration of model training. Intentionally kept generic to increase versatility.
:param model: The model to train.
:param dataloader: Dataloader object of training dataset.
:... | f65899cd5d769cef628c15e35835bcd7a93bde60 | 19,562 |
def frequency(string, word):
""" Find the frequency of occurrences of word in string
as percentage """
word_l = word.lower()
string_l = string.lower()
# Words in string
count = string_l.count(word_l)
# Return frequency as percentage
return 100.0*count/len(string_l) | dd2183dcec04bdf835ab22a8a351d53571f6e5e9 | 19,566 |
def get_func_names(job_content):
"""
Get function names from job content json
:param job_content: job content info
:return: function names
"""
func_names = []
for op in job_content["op_list"]:
if "func_name" in op:
func_names.append(op["func_name"])
return func_names | 58d32e48f308758a2d6028f3312c2b376e04c9f5 | 19,568 |
def filter_out_dict_keys(adict, deny):
"""Return a similar dict, but not containing the explicitly denied keys
Arguments:
adict (dict): Simple python dict data struct
deny (list): Explicits denied keys
"""
return {k: v for k, v in adict.items() if k not in deny} | a377c35f4eaedf0ed3b85eeaedbd45f7af0e8ec7 | 19,580 |
def loadraw(path, static=False):
"""Loads raw file data from given path with unescaped HTML.
Arguments:
path (str): Path to the file to read.
static (bool):
If True, all the `{` and `}` will be replaced
with `{{` and `}}` respectively.
Example:
>>> # $ cat p... | 438d4128bd72a81f46e581984d1cf53b3d11254a | 19,581 |
def get(obj, path):
"""
Looks up and returns a path in the object. Returns None if the path isn't there.
"""
for part in path:
try:
obj = obj[part]
except(KeyError, IndexError):
return None
return obj | f7d936174f1171c42cd7ec2fa4237a887e78bb0e | 19,584 |
import pickle
def load_pickle_object(filename: str):
"""Load/Unpickle a python object binary file into a python object.
Args:
filename (string): pickle filename to be loaded. (<filename>.pkl)
Returns:
python object: returns the loaded file as python object of any type
"""
obj = N... | d079728fce59420cba6d17da8743d6dba8d4d37d | 19,592 |
def nonzero_reference_product_exchanges(dataset):
"""Return generator of all nonzero reference product exchanges"""
return (exc for exc in dataset['exchanges']
if exc['type'] == 'reference product'
and exc['amount']) | 77796243c4f07b0877c997a9103a4d14ab48f2c7 | 19,596 |
def __update_agent_state(current_agent_state, transition_probability, rng):
"""
Get agent state for next time step
Parameters
----------
current_agent_state : int
Current agent state.
transition_probability : ndarray
Transition probability vector corresponding to current state.
... | 4d447f196ac6a326720cdf69c67286fe5053e5fc | 19,597 |
def is_leap_year(year):
"""
Indicates whether the specified year is a leap year.
Every year divisible by 4 is a leap year -- 1912, 1996, 2016, 2032, etc.,
are leap years -- UNLESS the year is divisible by 100 AND NOT by 400. Thus,
1200, 1600, 2000, 2400, etc., are leap years, while 1800, 1900, 2100... | 7e56255a4d3d969f56bb27b9b4474b56b047b022 | 19,601 |
def hotel_name(hotel):
"""Returns a human-readable name for a hotel."""
if hotel == "sheraton_fisherman_s_wharf_hotel":
return "Sheraton Fisherman's Wharf Hotel"
if hotel == "the_westin_st_francis":
return "The Westin St. Francis San Francisco on Union Square"
if hotel == "best_western_t... | d7e6118f25caa59174480c44fc4be63198d0c2c0 | 19,615 |
def always_true(*args, **kwargs): # pylint: disable=unused-argument
"""
Returns ``True`` whatever the arguments are.
"""
return True | 6f755e48a482dba4a3cccc8dad92cb6fbb610a1b | 19,616 |
def undocumented(func):
"""Prevents an API function from being documented"""
func._undocumented_ = True
return func | 135de1a166927dda811c6a9f7b6d5f826a13e42d | 19,621 |
def get_mask_bool(mask, threshold=1e-3):
"""
Return a boolean version of the input mask.
Parameters
----------
mask : enmap
Input sky mask.
threshold : float, optional
Consider values below this number as unobserved (False).
Returns
-------
mask_bool : bool enmap
... | f7950e1b332c5b6de6b963578e510a3e4fe65799 | 19,622 |
import torch
def activate_gpu(gpu='GPU'):
"""Use GPU if available and requested by user. Defaults to use GPU if available."""
if torch.cuda.is_available() and gpu.lower() == 'gpu':
print('Running on GPU')
device = torch.device('cuda:0')
else:
print('Running on CPU')
device ... | 3d5fbda4709a1307373156d8fab269445d24aeda | 19,623 |
def round_if_near(value: float, target: float) -> float:
"""If value is very close to target, round to target."""
return value if abs(value - target) > 2.0e-6 else target | 005a7d7110265bbb1abd5f5aef6092fb67186a62 | 19,626 |
def get_authors() -> str:
"""Ask for an author until nothing is entered."""
authors = []
while True:
author = input("Author: ")
if not author:
break
authors.append(author.title())
return ' and '.join(authors) | 2332f9ff2680d2d5612fc2f0a32e1020f0c674a0 | 19,628 |
import re
def tokenize_per_cluster_args(args, nclusters):
"""
Seperate per cluster arguments so that parsing becomes easy
Params:
args: Combined arguments
nclusters(int): total number of clusters
Returns:
list of lists: Each cluster conf per list
ex: [[cluster1_co... | be4c8d0ef01a2d2431f46434bd1ca88127b75cb6 | 19,640 |
def _from_quoted_string(quoted):
"""Strip quotes"""
return quoted.strip('"').replace('""', '"') | febde29bb30d54675b1ff5eebf5276d0ef9efdc2 | 19,642 |
def get_parent_build(build):
"""Returns the parent build for a triggered build."""
parent_buildername = build.properties_as_dict['parent_buildername']
parent_builder = build.builders[parent_buildername]
return parent_builder.builds[build.properties_as_dict['parent_buildnumber']] | ef4b1041bfd54b7aa2ac1469e6b58bfcf6acd724 | 19,643 |
def format_app_name(appname):
"""
Convert long reverse DNS name to short name.
:param appname: Application name (ex. sys.pim.calendar -> "calendar")
:type appname: str
"""
final = appname.split(".")[-1]
return final | aceb4f58506fa7fae0358f9fcf3dd0ea6fbab352 | 19,645 |
import re
def parse_show_vlan_internal(raw_result):
"""
Parse the 'show vlan internal' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show vlan internal command in a \
dictionary of the form. Returns None if no internal v... | f3f7bec8d4afc8d1d65e5eef0f60f772128e8530 | 19,649 |
def sqrt(number):
"""
Calculate the floored square root of a number
Args:
number(int): Number to find the floored squared root
Returns:
int: Floored Square Root
"""
high = number
low = 0
while low <= high:
mid = (low + high) // 2
midsquare = mid * mid
... | 1dca451d1b96ec88a36753d9d07edd9ba2f34de8 | 19,652 |
def do_work(func, args, kwargs=None):
"""
Wrap a function with arguments and return the result for
multiprocessing routines.
Parameters
----------
func
Function to be called in multiprocessing
args : tuple
Positional arguments to 'func'
kwargs : dict
Keyword argu... | 0f14dddccc40afdeeb18c3cd16322f85a2008112 | 19,653 |
import itertools
def make_call_summary_report(calls_list, users, for_graphviz=False):
"""
Makes a graphical or textual report of who has been on a call with who.
Only considers calls initiated by one of the tracked users.
Parameters
----------
calls_list: list
Calls to look through (... | 607c590e51194100e3fbc0f1f5aa09c4fe94a4ca | 19,656 |
def get_dataset(dataloaders: dict) -> dict:
"""
From dictionary of dataloaders to dictionary of datasets
"""
datasets = {split: dataloader.dataset for split, dataloader in dataloaders}
return datasets | b21b266f377a2edb910bde163ff656988512f964 | 19,664 |
import cmath
def twiddle_factor(turns):
""" Calculates the FFT twiddle factor of an angle measured in turns (not radian).
"""
return cmath.exp(-2.0j*cmath.pi*turns) | 4521143dc42d2e70c2215a36977d69e7cc519418 | 19,670 |
def wrap_deprecated(func, name):
"""Return a check function for a deprecated assert method call.
If the `assertive-deprecated` option has been enabled and the wrapped
check function doesn't yield any errors of its own, this function will
yield an A503 error that includes the new name of the deprecated ... | a94e0308ad4271ec669f4c5392a54193754c6b3f | 19,672 |
def _get_error_message(check, threshold, importance, series_name, value):
"""
Construct a check's error message, which will differ based on the number of
consecutive failed points.
For a single failed point:
Format: <importance> <series_name>: <value> not <comparator> <threshold>
Exa... | a91a761fc5bfb59c8ac8bdc3ea71b0e457d40bc1 | 19,674 |
def make_subj(common_name, encrypted=False):
"""
Make a subject string
:param common_name: Common name used in certificate
:param encrypted: Add the encrypted flag to the organisation
:return: A subject string
"""
return "/C=FR/ST=Auvergne-Rhone-Alpes/L=Grenoble/O=iPOPO Tests ({0})" \
... | def68ad50d44003c27b2ac0dfa4f67faa8bf9ed9 | 19,676 |
def string_contains_surrogates(ustring):
"""
Check if the unicode string contains surrogate code points
on a CPython platform with wide (UCS-4) or narrow (UTF-16)
Unicode, i.e. characters that would be spelled as two
separate code units on a narrow platform.
"""
for c in map(ord, ustring):
... | f459cfd562cf40e8e5705fa58009fcde6c9b1a0c | 19,678 |
def finalize(cur_aggregate):
"""Retrieve the mean and variance from an aggregate."""
(count, mean, m_2) = cur_aggregate
mean, variance = mean, m_2 / (count - 1)
if count < 2:
return float('nan')
else:
return mean, variance | 50190036de4eee6b3a5fac3ee0488fc9f21fb734 | 19,680 |
def can_be_index(obj):
"""Determine if an object can be used as the index of a sequence.
:param any obj: The object to test
:returns bool: Whether it can be an index or not
"""
try:
[][obj]
except TypeError:
return False
except IndexError:
return True | 899b36096a1aaf3fc559f3f0e6eb08251c36277c | 19,681 |
def scale(coord_paths, scale_factor):
"""
Take an array of paths, and scale them all away from (0,0) cartesian using a
scalar factor, return the resultinv paths.
"""
new_paths = []
for path in coord_paths:
new_path = []
for point in path:
new_path.append( (point[0]*sc... | e38dc71c0e2361628e428804e41b5314907641d5 | 19,692 |
def get_documentation_str(node):
"""
Retrieve the documentation information from a cwl formatted dictionary.
If there is no doc tag return the id value.
:param node: dict: cwl dictionary
:return: str: documentation description or id
"""
documentation = node.get("doc")
if not documentatio... | 6fce12b94d6000aee862c7dc8f105f4420357370 | 19,695 |
import json
def generateKoldieQueryCampaignIDJSONpayload(koldie_query_campaign_id):
"""
Input: Takes in Kolide query campaign ID
Output: Returns JSON payload for querying result(s) of query
"""
koldie_query_campaign_id_payload = {
"type":"select_campaign",
"data":{
"campaign_id": koldie_query_... | bd71b1d1f0d6eb57169e5fe93e6a8184b3149bb7 | 19,698 |
def get_shape_xyzct(shape_wh, n_channels):
"""Get image shape in XYZCT format
Parameters
----------
shape_wh : tuple of int
Width and heigth of image
n_channels : int
Number of channels in the image
Returns
-------
xyzct : tuple of int
XYZCT shape of the image
... | 7b8ec67ccbfd33811904393dfe0905a169900513 | 19,699 |
def rescale(num, old_min, old_max, new_min, new_max):
"""
Rescale num from range [old_min, old_max] to range [new_min, new_max]
"""
old_range = old_max - old_min
new_range = new_max - new_min
new_val = new_min + (((num - old_min) * new_range)/old_range)
return new_val | f823f46267d3b666ae0921957c2c3a3ca8c0a393 | 19,701 |
def find_fired_conditions(conditions, guard=None, *args, **kwargs):
"""
For an iterable (e.g. list) of boolean functions, find a list of
functions returning ``True``.
If ``guard`` is given, it is applied to a function to get the
predicate - a function ``() -> bool``. If this predicate is
not ``... | 0ae88df1df36667c7d771380c12d413437ebed11 | 19,702 |
def get_month(date):
"""
Extract month from date
"""
return int(date.split('-')[1]) | eabf8f51554f537bbf12148eb9a9151fabe1cfad | 19,704 |
def lollipop_compare(old_epoch: int, new_epoch: int) -> int:
"""
Compares two 8-bit lollipop sequences
:returns: a value indicating if the given new_epoch is in fact newer than old_epoch
1 if the new_epoch is newer than old_epoch
0 if the new_epoch is newer and the sequence has been reset
... | b925a333324c905ee89f368b218ffe584501fc9b | 19,705 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.