content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import List
def prime_factorization(N: int) -> List[int]:
"""Get list of prime factors of `N` in ascending order"""
factors = []
p = 2
while p * p <= N:
while N % p == 0:
factors.append(p)
N //= p
p += 1
if N > 1: # any left-over factor must be ... | c7a91ff819f5bb3d33058d5da2af9734abebba47 | 145,329 |
def unique_path(path):
"""Generate an unused filename that looks like `path`"""
# this adds ".1", ".2" etc. before the extension
orig_suffix = path.suffix
orig_name = path
number = 1
while path.exists():
path = orig_name.with_suffix(f'.{number}{orig_suffix}')
number += 1
retu... | 4034815c2203321ed5e875f0ee93d280e7bc4ef3 | 189,329 |
def get_property(config_values, path):
"""
Safely retrieve a config value by a list-defined config key path.
:param config_values: Dictionary of config values.
:param path: List of strings representing nested keys into the dictionary.
:return: The value of the requested path, or None if it does not... | bd370845833e2b582077123bf1aee72ddd69bb26 | 206,055 |
def of_type(*classinfo, **kwargs):
"""Returns a validator for a JSON property that requires it to have a value of
the specified type. If optional=True, () is also allowed.
The meaning of classinfo is the same as for isinstance().
"""
assert len(classinfo)
optional = kwargs.pop("optional", Fals... | ca5a202ef3ae61f8aa366494607abc2f12a44b35 | 557,341 |
import torch
def clsmap2scoremap(cls_maps, use_softmax=False, Cat=80, Anchor=9, score_shel=0):
"""
:param cls_maps: Cat * Anchor x H x W
:param use_softmax: score如果使用了sigmoid,就可以不进行softmax操作, use_softmax可以设置为False
:param Cat: 类别
:param Anchor: Anchor个数
:param score_shel: score threshold
... | d0f6527a2c1ef0c1296d408d5cc05ca1b25580e1 | 377,013 |
def simulate_multiline(string):
"""Return simulated multiline input for given string."""
counter = 0
strings = string.split("\n")
def simulated_input(*args):
nonlocal counter
if counter == len(strings):
return ""
value = strings[counter]
counter += 1
... | 06e9f2b73e736809ad2569bf44c8b36fa2c6bfc7 | 614,039 |
def checkEmblFile(filin):
"""Check EMBL annotation file given by user"""
line = filin.readline()
# TEST 'ID'
if line[0:2] != 'ID':
return 1
else:
return 0 | 8087a78a35193545070f76dbd969b617c7c92b0c | 22,717 |
from typing import Optional
def extract_lineage_from_line(line: str, exclude_withdrawn=True) -> Optional[str]:
"""
Extracts the lineage name from one of the lineage_notes.txt lines.
Most lines look like this
Q.3 Alias of B.1.1.7.3, USA lineage, from pango-designation issue #92
(note, that... | 2fb87ed19ad22f24c8a5066f60a9d19bb9621617 | 525,106 |
def get_user_input(username, session_id):
""" Prompt and get a command from the user.
Arguments:
:username: The username of the user.
:session_id: The session number incremented each time asking for inputing a command.
Returns:
The string command the user entered.
"""
print(... | 53be7f822de04ccaf66a2481f3cdb808a44c2ef2 | 451,455 |
def space_tokenizer(sequence):
""" Splits sequence based on spaces. """
if sequence:
return sequence.split(' ') | 539809996bfe16faebad8abd29bcec46e88a8283 | 81,562 |
def skip_n_lines_in_file(file_path, num_lines):
"""
Remove the initial num_lines of text from a file.
:param file_path: The path to the file that needs initial lines removed.
:param num_lines: The number of initial text lines to remove from the file
at file_path.
:return: The ... | 42a51d264085edeade267163254e8bf49777d98e | 241,902 |
from typing import Any
def fixture_labels_file_sync(tmpdir: Any) -> str:
"""Return a filepath to an existing labels file for the sync test."""
return "tests/sync.toml" | 3d4624bf7cd555a4bbf2acdf4e477adec7cdd10c | 495,105 |
import time
def get_timestamp(with_milliseconds=True):
"""Get current timestamp.
Returns:
Str of current time in seconds since the Epoch.
Examples:
>>> get_timestamp()
'1639108065.941239'
>>> get_timestamp(with_milliseconds=False)
'1639108065'
"""
t = str... | 1e9fbba08244cd8f9df00b94cd69ba10bf7e5e8b | 59,410 |
def CodepointsToUTF16CodeUnits( line_value, codepoint_offset ):
"""Return the 1-based UTF-16 code unit offset equivalent to the 1-based
unicode codepoint offset |codepoint_offset| in the Unicode string
|line_value|"""
# Language server protocol requires offsets to be in utf16 code _units_.
# Each code unit is... | 976daeb55916dbfeeff7f92e5352ee3ab135a608 | 679,794 |
from typing import List
def bubble_sort(arr: List[int]) -> List[int]:
"""Sort a list of integers in ascending order.
Args:
arr (List[int]): List of integers to be sorted.
Returns:
List[int]: Ordered list of integers.
"""
s = n = len(arr) - 1
for i in range(n):
a, b = ... | e85f32c6e134a808b7f68391dfd3cc1231a73a44 | 220,943 |
def passport_valid(
passport: str,
required_fields: tuple[str, str, str, str, str, str, str] = (
"byr",
"iyr",
"eyr",
"hgt",
"hcl",
"ecl",
"pid",
),
) -> bool:
"""Check is a passport is valid, by having all required fields in it."""
fields_in_... | 338eaeff7c88f47fa295404de8adc25c84aa5429 | 95,382 |
def get_like_status(like_status, arg_1, arg_2):
"""
Fetches a string for a particluar like_status
args:
like_status(boolean): It's either a True for a like
or False for a dislike
arg_1(str)
arg_2(str)
Returns:
arg_1(str): Incase the like_st... | b8d975bf90386bf0f2fa3a3b96d3d3a83862f36b | 594,737 |
def url_parse_server_protocol(settings_dict):
"""Return the public HTTP protocol, given the public base URL
>>> url_parse_server_protocol({'USE_SSL': True})
'https'
>>> url_parse_server_protocol({'USE_SSL': False})
'http'
"""
return "https" if settings_dict["USE_SSL"] else "http" | 705e458e78258cd6825c57f33fc2edcc3ac1f60b | 270,465 |
import inspect
def get_linenumbers(functions, module, searchstr='def {}(image):\n'):
"""Returns a dictionary which maps function names to line numbers.
Args:
functions: a list of function names
module: the module to look the functions up
searchstr: the string to search for
Retu... | b2cc1bc104cdae6bbbfb3680ac940540396db08a | 695,893 |
def encode_matrix_parameters(parameters):
"""
Performs encoding of url matrix parameters from dictionary to
a string.
See http://www.w3.org/DesignIssues/MatrixURIs.html for specs.
"""
result = []
for param in iter(sorted(parameters)):
if isinstance(parameters[param], (list, tuple)):... | d54643e25f37106d6fabc820f6e091693bf29bdd | 412,890 |
import torch
def space_motor_to_img(pt):
"""
Translate all control points from spline space to image space.
Changes all points (x, -y) -> (y, x)
Parameters
----------
pt : torch.Tensor
(..., 2) spline point sequence for each sub-stroke
Returns
-------
new_pt : torch.Tenso... | 6c1510b3b58d2864db90c739d4afb202314e0a33 | 350,827 |
def extract_guest_restraints(
structure, restraints, guest_resname, dummy_prefix="DM", return_type="dict"
):
"""
Utility function to extract the guest restraints from a list of restraints
and return individual restraints in the form ``[r, theta, phi, alpha, beta, gamma]``.
If there is no restraint ... | 339e6c24a03edfa8dffa314bd00560ce87546bf8 | 375,582 |
def collect_all_links(soup):
"""Finds all links on the page and returns them as a list
:param soup: The BeautifulSoup object
:type soup: BeautifulSoup object
:returns: List with URLs
"""
links = []
for link in soup.find_all('a'):
links.append(link.get('href'))
return links | b78f8146db1f352c1c85117d336dac7612f0cb62 | 236,884 |
def _page_to_text(page):
"""Extract the text from a page.
Args:
page: a unicode string
Returns:
a unicode string
"""
# text start tag looks like "<text ..otherstuff>"
start_pos = page.find(u"<text")
assert start_pos != -1
end_tag_pos = page.find(u">", start_pos)
assert end_tag_pos != -1
end... | d4ef3ea9365260972605ce1b35dbc457e7080e8a | 390,763 |
def stack_is_failing(events):
"""iterate stack events, determine if resource creation failed"""
failed = False
failure_modes = ('CREATE_FAILED', 'UPDATE_ROLLBACK_IN_PROGRESS')
for event in events['StackEvents']:
if event['ResourceStatus'] in failure_modes:
failed = True
if ev... | 95be398f3f6df51b58738e4d4a30224a3bc9af40 | 171,298 |
import socket
def GetHostName(useFqdn=False):
"""Returns the host name, and with FQDN if specified."""
thisHost = "localhost"
if useFqdn:
thisHost = socket.getfqdn()
# If the server is configured correctly getfqdn() works fine, but it might
# take what's in /etc/hosts first, so double check to se... | 6610f0b12c625b57e6b1b7964e60c42d915bdcc3 | 448,648 |
def escapeName(name):
"""Escape a name such that it is safe to use for files and anchors."""
escape = '_'
xs = []
for c in name:
if c.isalpha() or c in ['-']:
xs.append(c)
else:
xs += [escape, str(ord(c))]
return ''.join(xs) | 7b0dd8273dbbeacee754a1fdc36a2b20e6620380 | 545,342 |
def get_path_indices(not_dones):
"""
Returns list of tuples of the form:
(agent index, time index start, time index end + 1)
For each path seen in the not_dones array of shape (# agents, # time steps)
E.g. if we have an not_dones of composition:
tensor([[1, 1, 0, 1, 1, 1, 1, 1, 1, 1],
... | 39733f53c594389e83eb1609ab121ac3acbcb536 | 455,786 |
def query_newer_than(timestamp):
"""
Return a query string for later than "timestamp"
:param timestamp: CloudGenix timestamp
:return: Dictionary of the query
"""
return {
"query_params": {
"_updated_on_utc": {
"gt": timestamp
}
},
"... | 84d089ffca7f405714f3020f81500ee739d75cc9 | 404,627 |
def get_spin_link_dict(peaklist):
"""
Map each unique spin link to all of its corresponding peaks.
NOESY peak lists represent spin links between Hydrogen atoms. Whether
2D, 3D or 4D, each peak in a NOESY peak list has exactly two Hydrogen
spins. Here, a spin link is represented by a frozenset conta... | c9ce2d919c57f86467ef33a558c37dd539e3a7ef | 259,461 |
import hashlib
def double_sha256(string, as_hex=False):
"""
Get double SHA256 hash of string
:param string: String to be hashed
:type string: bytes
:param as_hex: Return value as hexadecimal string. Default is False
:type as_hex
:return bytes, str:
"""
if not as_hex:
retu... | bce1607fbbab0c3c9a3b3dd2dcd2e74b6cb84f87 | 690,194 |
def has_tag(ds, tag):
"""
Returns whether or not the specified tag is present in the specified
dataset.
:param ds: The dataset to search.
:param tag: The tag to search for.
:return: Whether or not a DICOM tag is present.
"""
return tag.value in ds | 04747d1d4263dd46a54a8443908fb231e90046e7 | 397,421 |
def linearsearch(A, elem):
"""
Linear Search Algorithm that searches for an element in an array with O(n) time complexity.
inputs: Array A and element e, that has to be searched
output: True/False
"""
for a in A:
if a==elem:
return True
return False | 5372e23eba64cacb59532a126b5aac6fdc9efe8f | 650,745 |
def count_lines(in_path):
"""Counts the number of lines of a file"""
with open(in_path, 'r', encoding='utf-8') as in_file:
i = 0
for line in in_file:
i += 1
return i | 848d6cf870f449a7ba9b9c249461f0438c62a7b0 | 654,239 |
def getIndentation(text):
"""Get the leading whitespace of a string."""
for i in range(len(text)):
if not text[i].isspace():
return text[:i] | c0565a4ab257dbdaadd7f8271173e52168afdbb6 | 469,225 |
def label_scoped_path(ctx, path):
"""Return the path scoped to target's label."""
return ctx.label.name + "/" + path.lstrip("/") | 6b61bec030ce77dfb559ada1c694510a93cb2b21 | 532,849 |
def search(x, thing):
"""Search for x in thing. True iff found. Utility used only
for tests in this file."""
if isinstance(thing, dict):
for y in thing.values():
if search(x, y):
return True
elif isinstance(thing, list):
for y in thing:
if searc... | bb58a69f43ea41e35414f98925945fe9fc4d872f | 562,486 |
def xfail(reason, strict=False):
"""
Mark a testcase/testsuit as XFail(known to fail) when not possible to fix
immediately. This decorator mandates a reason that explains why the test is
marked as passed. XFail testcases will be highlighted as amber on testplan
report.
By default, should the tes... | b5d511236980d17f999f343bcdeaaf6eff1b5c9d | 404,572 |
from datetime import datetime
from pathlib import Path
def create_datetime_subdir(dir_path):
"""
Create subdirectory named after the current date and time.
Args:
dir_path (Path): Path to directory.
Raises:
ValueError: If `dir_path` exists, but is not a directory.
Returns:
... | 74df542e541faf7b93276f6d84806e3766df9c40 | 437,434 |
def asst70_variation_descriptors(moa_vid70):
"""Create assertion70 variation_descriptors test fixture."""
return [moa_vid70] | 1e8d1fc13a55b173674c60c339f6d6a13945ca6f | 69,673 |
def is_pulsemap_check(table_name: str) -> bool:
"""Check whether `table_name` corresponds to a pulsemap, and not a truth or RETRO table."""
if "retro" in table_name.lower() or "truth" in table_name.lower():
return False
else: # Could have to include the lower case word 'pulse'?
return True | 8a467580c0ad50c357ff50d17a4ebf7e34633c09 | 613,366 |
import re
def parse_show_lacp_interface(raw_result):
"""
Parse the 'show lacp interface' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show lacp interface command in a \
dictionary of the form:
::
{
... | a093c0912742c0bc7e538c8ec59757b370cb24de | 88,662 |
def bonferroni_correction(pvals):
"""
Bonferroni correction.
Reference: http://en.wikipedia.org/wiki/Bonferroni_correction
"""
n = len(pvals)
return [min(x * n , 1.0) for x in pvals] | f57ffd6b77a0a74a61904334604d1cb0eb08f8ff | 706,275 |
def _chao1_var_uncorrected(singles, doubles):
"""Calculates chao1, uncorrected.
From EstimateS manual, equation 5.
"""
r = singles / doubles
return doubles * (.5 * r ** 2 + r ** 3 + .24 * r ** 4) | 96c5017fb3bef7dfca3f541dce087fe6a6cabfa2 | 207,846 |
def get_week_day(integer):
"""
Getting weekday given an integer
"""
if integer == 0:
return "Monday"
if integer == 1:
return "Tuesday"
if integer == 2:
return "Wednesday"
if integer == 3:
return "Thursday"
if integer == 4:
return "Friday"
if in... | 5bd0431e8598d56e99f970da738e532630665163 | 15,180 |
def attack(p, m1, c1, d1, c2, d2):
"""
Recovers a secret plaintext encrypted using the same nonce as a previous, known plaintext.
:param p: the prime used in the ElGamal scheme
:param m1: the known plaintext
:param c1: the ciphertext of the known plaintext
:param d1: the ciphertext of the known ... | a538f9ec358dde85267db2900aeef21b5e91dc1b | 541,465 |
def find_closest(numb, list_of_values, periodic=False):
"""For a given number, return the closest value(s) from a given list"""
all_dist = []
for value in list_of_values:
if periodic:
all_dist.append(min(abs(numb-value), (360-abs(numb-value))))
else:
all_dist.append(a... | c9150d33b497a4967c343c224875f7fa7a7d26b1 | 135,868 |
def check_not_present(context, raw_data, raw_field):
"""
Verifies that a specified field is not present in a raw data structure.
Args:
context (str): The context of the comparison, used for printing error messages.
raw_data (dict): Raw data structure we're checking a field from.
raw... | a8a1d505689c14a55ad26c5d59e146568c62d361 | 375,399 |
def parse_line(line):
"""Parse instruction and return it as tuple of operator and value"""
op, val = line.split()
val = int(val)
return op, val | e4963becf24beb7b998e969f7301d06744dd107e | 595,036 |
def get_union(*args):
"""Return unioin of multiple input lists.
"""
return list(set().union(*args)) | 18025cfd37d64f15daf92aa2ae3e81176cae6e39 | 5,786 |
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 by_locale(value_for_us, value_for_international):
""" Return a dictionary mapping "us" and "international" to the two values.
This is used to create locale-specific values within our UNITS.
"""
return {"us" : value_for_us,
"international" : value_for_international} | 94477ffaa40b0ed8d433d2c7a4cc94e0fb3b4f7f | 383,109 |
import keyword
def attr_str(attr_name):
# type: (str) -> str
"""Gets the string to use when accessing an attribute on an object.
Handles case where the attribute name collides with a keyword and would
therefore be illegal to access with dot notation.
"""
if keyword.iskeyword(attr_name):
... | fdf6319e022c0db28d000a0c8545df8ada9b80fd | 185,693 |
def numpy_ndarray(pd_ser, nan_to_null=False):
"""Return numpy.ndarray view of a pandas.Series
"""
return pd_ser.to_numpy() | 4f1e073fc8f92f51da5390fcf0de6d9f2c559e51 | 174,578 |
import pathlib
from typing import List
def _get_all_directories(root: pathlib.Path) -> List[pathlib.Path]:
"""Walk the directory tree and return all the folders."""
all_files_and_folders = root.glob("**/*")
return [path for path in all_files_and_folders if path.is_dir()] | 911dc7b14629e6b929f8aa9b96b9ba72406f36ee | 591,377 |
def last_replace(s, old, new, number_of_occurrences):
"""
Replaces last n occurrences of the old string with the new one within the string provided
:param s: string to replace occurrences with
:param old: old string
:param new: new string
:param number_of_occurrences: how many occurrences shoul... | 0cfa60e46694cb28f731c4adb0d912af3bf6bd06 | 632,609 |
def remove_padding(im, pad):
"""
Function for removing padding from an image.
:param im: image to remove padding from
:param pad: number of pixels of padding to remove
:return:
"""
return im[pad:-pad, pad:-pad] | 58d822dc9ab587f63d1a98eb19e17268d75b2ab4 | 686,436 |
def print_pauli_list_grouped(pauli_list_grouped):
"""Print a list of Pauli operators which has been grouped into tensor
product basis (tpb) sets.
Args:
pauli_list_grouped (list of lists of (coeff, pauli) tuples): the
list of Pauli operators grouped into tpb sets
Returns:
None
... | cc58f5a9dce2ee77fdf46d9801f617ca85cf6306 | 605,617 |
def _intersects_bounds(a, b):
"""
Return true if two bounding boxes intersect.
"""
aminx, aminy, amaxx, amaxy = a
bminx, bminy, bmaxx, bmaxy = b
if aminx > bmaxx or amaxx < bminx:
return False
elif aminy > bmaxy or amaxy < bminy:
return False
return True | e6016e6e90e6df95b9c826928dc58913dbfc9faf | 162,924 |
from datetime import datetime
import pytz
def localized_date_to_utc(date):
"""
Return a timezone-unaware UTC time from a timezone-aware localized datetime object.
"""
if not isinstance(date, datetime):
return date
return date.astimezone(pytz.utc).replace(tzinfo=None) | 63ccd11c27645d56b479b01245703038d58d215e | 58,662 |
def norm_isbn_str(s):
"""
Given an ISBN string, normalize the string so that it only contains
the relevant digits.
This function drops all ASCII whitespace characters (tab, space,
carriage return, line feed) and all ASCII characters that are not
alphanumeric.
It also converts all ASCII letters to... | 890d010f8361524be44ebaf783d8b6c7d0541b2b | 223,269 |
def simtelTelescopeConfigFileName(
site, telescopeModelName, modelVersion, label, extraLabel
):
"""
sim_telarray config file name for a telescope.
Parameters
----------
site: str
South or North.
telescopeModelName: str
LST-1, MST-FlashCam, ...
modelVersion: str
V... | e5ae27857c5615bedeb11ca9698355ba8f03ce70 | 97,649 |
import functools
import tempfile
import pathlib
import shutil
def with_tempdir(wrapped):
"""Creates a temporary directory for the function, cleaning up after it returns normally.
When the wrapped function raises an exception, the contents of the temporary directory
remain available for manual inspection.... | 9a8f7e745aae4ceb78793b8e14f8a0386bafad3a | 436,772 |
def how_many_bytes(bits: int) -> int:
"""
how_many_bytes calculates how many bytes are needed to to hold the given number of bits
E.g.
=> how_many_bytes(bits=0) == 0
=> how_many_bytes(bits=8) == 1
=> how_many_bytes(bits=9) == 2
Args:
bits (int): The number of bits
Returns:
... | 9308b429659c0f17e8f7d1325109d851eee1f1ed | 273,958 |
import torch
def apply_weight_norm(w, input_dims=(1, 2, 3), eps=1e-8):
"""
Applies the "demodulation" operation from StyleGAN2 as a form of normalization.
:param w: Weights
:return: Normed weights
"""
divisor = torch.sqrt((w ** 2).sum(dim=input_dims, keepdim=True) + eps)
return w / divisor | 5b9bdca5af181b309a37d2f873bb401741fc98d8 | 182,907 |
import random
import string
def gen_dummy_object(class_, doc):
"""Create a dummy object based on the definitions in the API Doc."""
object_ = {
"@type": class_
}
if class_ in doc.parsed_classes:
for prop in doc.parsed_classes[class_]["class"].supportedProperty:
if "vocab:" ... | 86e981c7f62ccddda0463145c825d43dc1c3c476 | 693,072 |
def vec_leq(vec1, vec2):
""" Check that vec1 is less than vec2 elemtwise """
assert isinstance(vec1, list), "Only work with lists"
assert isinstance(vec2, list), "Only work with lists"
assert len(vec1) == len(vec2), "Vector lengths should be the same"
for x, y in zip(vec1, vec2):
# if a coor... | 59803934ee083243b20f6c30478a5108e7072f91 | 560,644 |
from typing import Counter
import math
def unigram_task_score(X):
"""
Given a list of strings, X, calculate the maximum log-likelihood per character for a unigram model over characters (including STOP symbol)
"""
c = Counter(x for s in X for x in s)
c.update("end" for s in X)
n = sum(c.values(... | 694396779d73415971e3062afbaa6bb65d1d0cf1 | 478,862 |
import time
def encode_date (date):
"""Encodes a datetime in TiddlyWiki format."""
return time.strftime('%Y%m%d%H%M', date) | 3e9b0315476e740d2f902666e91d94f8eeeb2ef0 | 371,535 |
def confirm(message: str) -> bool:
"""
Confirms action by requesting right input from user
:param message:
:return:
"""
return input(message) == 'Y' | 1556e8fc8734442e82751e0578ab7712442f04e3 | 261,859 |
def nonlocals(dynamicscope):
"""Access the nonlocals of a dynamic scope.
"""
return dynamicscope[0]['nonlocals'] | 99647f0e23e2fdb8435f54c737c02259c1688b73 | 549,442 |
def get_ds_capacity(datastore):
"""
Get vsphere datastore capacity size
:param datastore: vsphere datastore object
:return: datastore capacity size
"""
capacity_size = datastore.summary.capacity
return capacity_size | 38cbae4aec571449e448002a8dd5b57af8ad71a6 | 434,984 |
from typing import Union
from typing import Any
def type_to_str(type_annotation: Union[type, Any]) -> str:
"""Gets a string representation of the provided type.
:param type_annotation: A type annotation, which is either a built-in type or a typing type.
:return: A string representation of the type annota... | ce2adebf95503aed61a0e7c8877a0cdb9b8d104e | 426,567 |
import re
def get_postcode(address_string):
"""
Takes an address and returns the postcode, or None if no postcode is found.
"""
address_string = address_string.upper()
pc_regex = "([A-PR-UWYZ]([1-9]([0-9]|[A-HJKSTUW])?|[A-HK-Y][1-9]([0-9]|[ABEHMNPRVWXY])?) *[0-9][ABD-HJLNP-UW-Z]{2}|GIR *0AA)"
... | bad2bf8a03eebea3c034a402c665a7b9cae9df26 | 218,453 |
def count_parameters(net):
"""Counts the parameters of a given PyTorch model."""
return sum([p.numel() for p in list(net.parameters())]) | 1d1dc1b36d573ae2427cc2ab4f70e4bc7a7b8f00 | 522,468 |
def clean_dict(d):
""" clean dictionary object to str
:param dict: dictionary
"""
new = {}
for k, v in d.items():
if isinstance(v, dict):
v = clean_dict(v)
new[k] = v
else:
new[k] = str(v)
return new | e9a61a83b5367fc86badcacf58a63e672c0fb941 | 134,818 |
def baseline_grid_consistent_with_prevents(baseline_grid, element, at_root=False):
""" Checks whether the baseline grid is not prevented by the locks an on element """
if "prevents" in element and "baseline_grid" in element["prevents"]:
bg_value = element["prevented_values"]["baseline_grid"]
if baseline_grid in ... | dce2e991d838b94ea58891a87b966e6773b0f81b | 166,399 |
def image_filter(input_stream, image_stream_index, x, y, t_start, t_end,
output_stream):
"""Generate a ffmeg filter specification for an image input.
Arguments:
input_stream -- name of the input stream
image_stream_index -- index of the input image among the -i arguments
x, y -- po... | 20ddd75b1ab97f43eeb59deb3ec058b844c82e35 | 266,100 |
import re
def stringify_arg(value):
"""
Gets rid of the CDATA xml part of the string.
:param value: a possibly unicode element
:return: unicode value without the CDATA information
"""
patt = re.compile(r"<!\[CDATA\[(.+)\]\]")
if value is None:
value = "null"
m = patt.search(va... | bf8ff8b3e0b0b24b8fabcbac1fb51d74ceffcfed | 425,258 |
def identity(x):
"""Identity activation Layer
A placeholder identity operator that is argument-insensitive.
Args:
x (np.ndarray): input tensor.
Returns:
(np.ndarray): output tensor and have same shape with x.
Examples:
>>> identity(np.array([-3.0, -1.0, 0.0, 2.0]))
... | e3486b83b083348f2d252fee49fef7cace0a54dc | 217,712 |
def sign(x):
"""Returns sign of x"""
if x==0:
return 0
return x/abs(x) | 677dfd796b0ee354fbcaf78b58cf7a5a660446b5 | 705,300 |
from typing import Any
def verify_assign_and_read(obj: Any, attr: str, value: Any) -> Any:
"""
Assign value to attribute, read and return result.
Assert that values can be mutated and read before and after mutation.
"""
try:
setattr(obj, attr, value)
except AttributeError:
rai... | b7ae561c3cee9d9f379a6c0883a6f3bdb5861768 | 669,900 |
def indent(value, n=2, character=' '):
"""
Indent a value by `n` `character`s
:param value: string to indent
:param n: number of characters to indent by
:param character: character to indent with
"""
prefix = n * character
return '\n'.join(prefix + line for line in value.splitlines()) | 895559983bf02c90c030d33d1f95ba4ac3814394 | 223,923 |
def convertToCamelCase(input, firstIsLowercase=False):
"""Given an input string of words (separated by space), converts
it back to camel case.
'Foo Bar' (firstIsLowercase=False) --> 'FooBar'
'Foo Bar' (firstIsLowercase=True) --> 'fooBar'
'foo bar' (firstIsLowercase=False) --> 'FooBar'
Args:
input (str)... | a27a0ff9163917973e3ad21e4c892080fcccac14 | 212,273 |
def dashcount(entry):
"""
Counts the number of dashes at the beginning of a string. This
is needed to determine the depth of options in categories.
Args:
entry (str): String to count the dashes at the start of
Returns:
dashes (int): Number of dashes at the start
"""
dashes ... | 9a096f6da8e44cb8f8daf310f454543b322df654 | 475,789 |
def user_dir_path(instance, filename):
""" files will be uploaded to MEDIA_ROOT/user_<id>/filename """
return 'user_{0}/reports/{1}'.format(instance.visit_id.user_id, filename) | c286dada6d995ed4d38b49a3e46890e7d08898be | 168,614 |
def round_exp(x,n):
"""Round floating point number to *n* decimal digits in the mantissa"""
return float(("%."+str(n)+"g") % x) | d101d0839f4e12e511d222a3758adfadb7165184 | 146,819 |
def premium(q,par):
""" Returns the (minimum) premium that an insurance company would take
Args:
q (float): coverage
par (namespace): parameter values
Returns:
(float): premium
"""
return par.p*q | 2166bc6e16577a26d3adc17afe5929bf8fca073b | 33,739 |
def get_user_groups(db, user_id=None):
"""Retrieves the existing user groups,
if member_is is provided returns
only the groups associated to the user_id
Args:
db (object): The db object
user_id (int): User ID
Returns:
The user groups
"""
sql = '''SELECT id, na... | 469f3793efdfebc88f989a2ed5961eb2ed4398d6 | 496,111 |
import re
def trim_ansi_tags(data_str):
"""
Trim all ANSI tags
:param data_str: input data string to trim
:return: Trimmed string
>>> trim_ansi_tags('')
''
>>> trim_ansi_tags(u'')
''
>>> trim_ansi_tags(u'hello world')
'hello world'
>>> trim_ansi_tags('hello world')
'he... | a78493aba53230494b24a9b27afc76dcc8616639 | 340,059 |
def ispalindrome(n):
"""
checks whether the integer n is a palindrome
"""
s = str(n)
return s == s[::-1] | 47b1cadb203fddd0509357135c71b94b989b982c | 117,562 |
def hex_to_long(hex_string: str):
"""Convert hex to long."""
return int(hex_string, 16) | c9a88a1c6d30afe8b8aab6c0c303e8e467fe6b26 | 431,518 |
def notas(* n, sit=False):
"""
-> Função para analisar notas e situação de vários alunos
:param n: um ou mais notas dos alunos (aceita várias)
:param sit: (opcional) indica se deve ou não adicionar a situação
:return: dicionário com várias informações sobre o desempenho da turma
"""
desempen... | 56d43d412417964dce9f7eb59a6f00a9ec0b267c | 506,707 |
import math
def electrode_distance(latlong_a, latlong_b, radius=100.0):
"""
geodesic (great-circle) distance between two electrodes, A and B
:param latlong_a: spherical coordinates of electrode A
:param latlong_b: spherical coordinates of electrode B
:return: distance
"""
lat1, lon1 = lat... | 99ae372ff17678c545ce48dac085b865f8fe3b88 | 172,443 |
import json
def write_json(file_path, json_obj):
"""Write JSON string.
# Arguments
file_path: `str`<br/>
the absolute path to the JSON string.
json_obj: `dict`<br/>
a dictionary
# Returns
flag : bool
True if saved successfully
False... | 3f212d2271e3b29e68d64510974b4ad1c50f7a99 | 663,456 |
def cat_lists(*list_args):
"""
Given any number of lists, concatinate onto a new list
"""
result = []
for List in list_args:
result.extend(List)
return result | 3dd43be591e8112dbe3906d89b065e7a177208c8 | 301,298 |
import time
def ms_time_to_srt_time_format(d: int) -> str:
"""Convert decimal durations into proper srt format.
ms_time_to_srt_time_format(3890) -> '00:00:03,890'
"""
sec, ms = d // 1000, d % 1000
time_fmt = time.strftime("%H:%M:%S", time.gmtime(sec))
# if ms < 100 we get ...,00 or ...,0 whe... | 3ca2713615b7fb8ef1ea9e9712e0b26b23c5f7e1 | 35,616 |
def min_max_norm(x):
""" Performs min-max normalization --> scales values in range between 1 and 0
:param x (1-D array like)
:return: (1-D np.array) min-max normalized input
"""
mini = min(x)
maxi = max(x)
return (x - mini) / (maxi - mini) | 72b19fb7e5bf47fcf78d51676a9b89c3694bee44 | 623,166 |
def _reformat_spectrometer_df(spectrometer_df_with_clean_header):
""" Reformats a df of spectrometer data with many wavelength columns to a more useful format with 2 columns
Args:
spectrometer_df_with_clean_header: a pandas df of spectrometer data,
cleaned up with _clean_up_spectrometer_df_... | f926ee35bcbaa282bf1d116e9b3282d491d0de52 | 251,405 |
def decimal(anon, obj, field, val):
"""
Returns a random decimal
"""
return anon.faker.decimal(field=field) | 9ca0d3fab6c5f1862ce01bb3008ab82eccdfd865 | 458,727 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.