content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
import torch
def zeros(shape):
"""Create zeros like shape."""
return torch.zeros(shape) | a71105b8a009ee297105770670a9f363fe0e2019 | 460,523 |
def oriented(square, desired):
""" Return True if the given square is oriented as desired.
"""
success = True
neighbors = square.neighbors
for side,id_ in desired.items():
if id_ is None:
success &= (side not in neighbors)
else:
success &= (side in neighbors a... | 0734c5feed757b238ca748a88965e013b0d390aa | 454,405 |
def _normalize_percent_rgb(value):
"""
Normalize ``value`` for use in a percentage ``rgb()`` triplet, as
follows:
* If ``value`` is less than 0%, convert to 0%.
* If ``value`` is greater than 100%, convert to 100%.
Examples:
>>> _normalize_percent_rgb('0%')
'0%'
>>> _normalize_pe... | 910da5cf9d270ef46e4ace3e53fd082763743191 | 282,124 |
def calculate_occlusion(ray, obj, light, objects):
"""
Calculate if there is an object between the light and object
Args:
ray: A ray starting in the hit point with direction to the light
obj: The object where the hit point is
light: A source of light to calculate if it's occluded
... | c15acf785f8baf72da64307380cd36d7de6b6ef8 | 694,713 |
import tempfile
import zipfile
def decompress(zip_file, dir=None):
"""Decompress Zip file
Decompress any zip file. For example, TOSCA CSAR
inputs:
zip_file: file in zip format
dir: directory to decompress zip. If not provided an unique temporary
directory will be generated and ... | 4a860d6b8a104d8325bd4fa83db6aa9b05a49f76 | 382,180 |
def build_index(interactors):
""" Build the index (P x D) -> N for all interactors of the current protein.
"""
index = dict() # P x D -> N
sorted_interactors = sorted(list(interactors))
for p, d in sorted_interactors:
index[(p, d)] = sorted_interactors.index((p, d))
return index | 44856b3dd98cb751d7da43f0952fe6a15e530886 | 375,006 |
import urllib3
import certifi
def post_json(ctx, path, json):
"""
Make a POST request with a JSON payload to be sent to a NuvIoT endpoint.
Parameters
----------
ctx:
Context Object that defines how this method should call the server to include authentication.
path:
Path u... | a6c1f49ce04d4f129d5fc8d180c2e460bbc825ac | 585,558 |
import re
def extract_energies(pdb_file):
""" Extract energies from the header of the PDB file, according to HADDOCK formatting """
vdw = .0
elec = .0
desolv = .0
air = .0
bsa = .0
vdw_elec_air_regex = r"\s(\-?\d*\.?\d{1,}|0\b)" # Known error: 8.754077E-02 is matched as 8.754077 which is
# not relevant for ... | 326aa323de92ef834365eb8b61eef3dc7b8fa97d | 344,606 |
def camelify(s):
"""Helper function to convert a snake_case name to camelCase."""
start_index = len(s) - len(s.lstrip("_"))
end_index = len(s.rstrip("_"))
sub_strings = s[start_index:end_index].split("_")
return (s[:start_index]
+ sub_strings[0]
+ "".join([w[0].upper() + w[1:... | 84bed77f217b8af55b0bd2cca0d354f372ba9e3d | 552,514 |
import cProfile
def profiler_setup(config):
"""
Set up profiler based on config
"""
if not config["profile"]:
return
profiler = cProfile.Profile()
profiler.enable()
return profiler | bc67268533a87482a2735dbc57cfc7af64655605 | 387,040 |
def normalize(lst, maxval=1.):
"""
Normalizes a list of values with a specified value.
**Parameters**
lst: *list*
List of values to be normalized
maxval: *float*, optional
The maximum value that the list will have after normalization.
**Returns**
normalized list: *list*... | 9ae34b5b7a81d55de88c942806f0440040873165 | 27,682 |
from typing import Any
def get_cls_name(obj: Any, package_name: bool = True) -> str:
"""
Get name of class from object
Args:
obj (Any): any object
package_name (bool): append package origin at the beginning
Returns:
str: name of class
"""
cls_name = str(obj.__class__)... | 6eb9a5b8b2ac4b33b988a90ba5f1988633179295 | 44,624 |
def id_number_checksum(gd):
"""
Calculates a Swedish ID number checksum, using the Luhn algorithm
"""
n = s = 0
for c in (gd['year'] + gd['month'] + gd['day'] + gd['serial']):
# Letter? It's an interimspersonnummer and we substitute the letter
# with 1.
if c.isalpha():
... | bbf0a9fa7f6ed2c2bfc414173fd2ac9e9c1d8835 | 706,841 |
def case_sorting_key(e):
"""Sorting key for test case identifier."""
return tuple(map(lambda n: int(n), e[0].split('.'))) | c6bb059b516b2fd2118caf117277d05fa1d44dfa | 267,573 |
def get_active_intfs(host_ans):
"""
@Summary: Get the active interfaces of a DUT
@param host_ans: Ansible host instance of this DUT
@return: Return the list of active interfaces
"""
int_status = host_ans.show_interface(command="status")['ansible_facts']['int_status']
active_intfs = []
... | b5131862f6f8944dc908b1c1e245efaccce37bb1 | 220,292 |
def count_matches(a: str, b: str) -> int:
"""Returns the number of locations where the two strings are equal."""
assert len(a) == len(b)
return sum(int(i == j) for i, j in zip(a, b)) | 9c901f8c8303f58989db466f0a728bac3f93eb67 | 610,859 |
def is_integer(s):
"""True if s in an integer."""
try:
c = float(s)
return int(c) == c
except (ValueError, TypeError):
return False | d24cc5f51fc44dd7fb19b9f1fdc430760ba66181 | 299,550 |
def binary_search(val, array):
"""
>>> binary_search(1, [1, 2, 3])
(0, 1)
>>> binary_search(1.5, [1, 2, 3])
(1, 2)
>>> binary_search(8, [1, 2, 3])
(None, None)
>>> binary_search(3, [1, 2, 4])
(2, 4)
"""
# Trivial cases - out of array range.
if len(array) == 0:
re... | 7e77f29945b3f4f579461d11acd334f288daa601 | 132,115 |
def report_writer(md):
"""
Reads meta data into function and makes txt message report.
----------
md : dict
Contains meta data from experiment file
Returns
-------
message : string
The text output for the report
"""
s_name = md["sample_meta_data"]["sample_name"]
s... | 16d67de3ca6f858aeea1f1a652ab4946a6c60cc0 | 61,436 |
def list_contains_only_integers(lst):
"""Returns True if the input list contains only str representations of digits.
Args:
lst: A list.
Elements must be strings, and if any element is not a string representation of
a digit, the function returns False.
"""
if not isinstance(lst, list):
raise TypeEr... | 06ac2b8b9867c651d501b5e3fee4e6452b77f5a0 | 219,237 |
def select_categorical_gmeta_fields(metabase_cur, column_id):
"""
Select Gmeta fields related to categorical columns.
Note that the return value is different from other column types.
Args:
metabase_cur
column_id
Return:
(Query result object fetched from psycopg2's DictCurs... | 30fb4247bdbbdcd50e56065efec429a7a4a3a37e | 407,928 |
import torch
def kl_prox_softmin(ecost, a, b, eps, rho, rho2):
"""Prepares functions which perform updates of the Sikhorn algorithm
in exponential scale.
Parameters
----------
ecost: torch.Tensor of size [Batch, size_X, size_Y]
Exponential of the cost. Kernel of Sinkhorn operator.
a: tor... | 3572de47292e22cb64654d84c4845590a1000eab | 474,497 |
def median_imputation(df):
"""Impute the missing numeric values with the median of that column after grouping by label"""
imputed_df = df.copy()
# get the numeric columns in the input df ("Label" and "struct_ordered" are excluded)
numeric_cols = imputed_df.drop(columns=["Label", "struct_ordered"]).selec... | 1870b3e2b2204626983ac9ca2f0766d66251f9fb | 491,975 |
def copy_or_set_(dest, source):
"""
A workaround to respect strides of :code:`dest` when copying :code:`source`
(https://github.com/geoopt/geoopt/issues/70)
Parameters
----------
dest : torch.Tensor
Destination tensor where to store new data
source : torch.Tensor
Source data... | d30b1e98da0ab2ef134173ad39a3e6e66e08c903 | 524,799 |
def get_shape(x, unknown_dim_size=1):
"""
Extract shape from onnxruntime input.
Replace unknown dimension by default with 1.
Parameters
----------
x: onnxruntime.capi.onnxruntime_pybind11_state.NodeArg
unknown_dim_size: int
Default: 1
"""
shape = x.shape
# replace unknow... | 1c719191922a46b948fb567273e3a5152769e190 | 8,539 |
import hashlib
def sha256_hash(b: bytes) -> bytes:
"""
sha256_hash hashes the given bytes with SHA256
Args:
b (bytes): bytes to hash
Returns:
bytes: The hash result
"""
return hashlib.sha256(b).digest() | 110367c664552fc068f1a1e0839fed0ae061d22f | 256,139 |
def transform_dict(img):
"""
Take a raster data source and return a dictionary with geotranform values
and keys that make sense.
Parameters
----------
img : gdal.datasource
The image datasource from which the GeoTransform will be retrieved.
Returns
-------
dict
A di... | 8817028adfce28ae7f7ae787d4256d52fee095bc | 15,933 |
def query_registry(model, registry):
"""Performs a lookup on a content type registry.
Args:
model: a Django model class
registry: a python dictionary like
```
{
"my_app_label": True,
"my_other_model": {
"my_model": True,... | 7c410c5baa8d20792ee7f49423da000fee34d001 | 669,370 |
def binary_search_recursive(lst, key, start=0, end=None):
"""
Performs binary search with recursion for the given key in iterable.
Parameters
----------
lst : python iterable in which you want to search key
key : value you want to search
start : starting index
end : ending index
Re... | 70f464151c3357786308f2a0ea16e77c25382700 | 284,998 |
from typing import Any
from pathlib import Path
from typing import Tuple
def lookup_path(context: Any, sub_paths: Path) -> Tuple[bool, Any]:
"""Lookup attributs in a context like dictionary.
Arguments:
context (Any): a dictionnary like structure with in and [] methods
(support __contains_... | fd21a1f993d9596ff15420a6faa022b832b25b66 | 433,999 |
def indexPosition2D(i, j, N, M):
"""This function is a generic function which determines if for a grid
of data NxM with index i going 0->N-1 and j going 0->M-1, it
determines if i,j is on the interior, on an edge or on a corner
The funtion return four values:
type: this is 0 for interior, 1 for on ... | 3197313b6211e40e8b3bbde6e7eb18bdf15ee814 | 461,579 |
def GetErrorOutput(error, new_error=False):
"""Get a output line for an error in regular format."""
line = ''
if error.token:
line = 'Line %d, ' % error.token.line_number
code = 'E:%04d' % error.code
error_message = error.message
if new_error:
error_message = 'New Error ' + error_message
retur... | 4661c74fcef9f13c0aad3d74e827d9eea20f86ef | 12,861 |
def rev_comp(seq: str) -> str:
"""
Generates the reverse complement of a sequence.
"""
comp = {
"A": "T",
"C": "G",
"G": "C",
"T": "A",
"B": "N",
"N": "N",
"R": "N",
"M": "N",
"Y": "N",
"S": "N",
"W": "N",
"K... | cb6b95d2d3f15910ff3ad793d99bb56de898026e | 11,619 |
from typing import Optional
def get_shelf_audience_code(location_code: str) -> Optional[str]:
"""
Parses audience code from given normalized location_code
"""
try:
audn = location_code[2].strip()
if audn:
return audn
else:
return None
except IndexEr... | 5aa9c32a186f1f8a111f8a50fbf2c05ea0fd6705 | 344,232 |
def are_relatively_prime(a, b):
"""Return ``True`` if ``a`` and ``b`` are two relatively prime numbers.
Two numbers are relatively prime if they share no common factors,
i.e. there is no integer (except 1) that divides both.
"""
for n in range(2, min(a, b) + 1):
if a % n == b % n == 0:
... | f3f98b43a27f6da219e0c68f9da55df0a2774bde | 616,781 |
def boolean(entry, option_key="True/False", **kwargs):
"""
Simplest check in computer logic, right? This will take user input to flick the switch on or off
Args:
entry (str): A value such as True, On, Enabled, Disabled, False, 0, or 1.
option_key (str): What kind of Boolean we are setting. W... | d62b36d08651d02719b5866b7798c36efd2a018f | 3,297 |
def primary_private_ip(ip_configs):
""" This function extracts primary, private ipaddress """
return [ip['properties']['privateIPAddress']
for ip in ip_configs if ip['properties']['primary']][0] | 281f25eecda0c477308d93376587875942b19993 | 516,169 |
def isInteger(n, epsilon=1e-6):
"""
Returns True if n is integer within error epsilon
"""
return (n - int(n)) < epsilon | 8ef0960cffadc063317830dca77d1177569ad178 | 34,840 |
import pickle
def save_pickle(value, filename):
"""
Save value to pickle file
:param value: Value to save
:param filename: Filename to save value as
"""
with open(filename, 'wb') as f:
return pickle.dump(value, f) | 70e8fbbf2420586127c2d0704243a227fe2c5d58 | 536,373 |
from typing import List
from typing import Any
def flatten(x: List[Any]) -> List[Any]:
"""Returns flattened list.
Args:
x (list): Nested Python list.
Returns:
list: Flattened Python list.
"""
return [i for sl in x for i in sl] | d9b24e63d75849bcf5f1538bbb3dcb44c4a64a5c | 177,843 |
def uri_leaf(uri):
"""
Get the "leaf" - fragment id or last segment - of a URI. Useful e.g. for
getting a term from a "namespace like" URI. Examples:
>>> uri_leaf('http://example.org/ns/things#item')
'item'
>>> uri_leaf('http://example.org/ns/stuff/item')
'item'
>>> ... | abbcc83543c5f20a93a59a94cc6c7e164ed70deb | 169,223 |
def get_file_date_part(now, hour) -> str:
""" Construct the part of the filename that contains the model run date
"""
if now.hour < hour:
# if now (e.g. 10h00) is less than model run (e.g. 12), it means we have to look for yesterdays
# model run.
day = now.day - 1
else:
d... | 42c2beddccba755f66061364463f8ad759d3c020 | 12,851 |
import zlib
def inflate(data):
"""Returns uncompressed data."""
return zlib.decompress(data, -zlib.MAX_WBITS) | 144ba727f93a79abec7880a2781ea9971a69d825 | 374,636 |
def merge_dict_of_lists(d1: dict, d2: dict) -> dict:
"""Merge two dicts of lists.
Parameters
----------
d1 : dict
The first dict to merge.
d2 : dict
The second dict to merge.
Returns
-------
dict
The merged dict.
"""
ret = {k: list(v) for k, v in d1.item... | 51c9c495c087c2d7fa1676800ab8223d1881308f | 407,665 |
def calulate_loss_of_life(List_V, t):
""" For list of V values, calculate loss of life in hours
t = Time Interval (min)
"""
L = 0
for V in List_V:
L += (V * t) # Sum loss of life in minutes for each interval
LoL = L / 60 # Calculate loss of life in hours
return LoL | ee2499af737cca764aad0a2f13794a925a172b9e | 10,849 |
import random
def encode_string(value):
"""
Encode a string into it's equivalent html entity.
The tag will randomly choose to represent the character as a hex digit or
decimal digit.
"""
e_string = ""
for a in value:
e_type = random.randint(0, 1)
if e_type:
en... | 76af82e3495c605a5ddaf3df9bdd352749856c07 | 641,657 |
def mouse_within_existing_lines(self, mouse_y):
"""
Returns True if the given Y-coordinate is within the height of the text-editor's existing lines.
Returns False if the coordinate is below existing lines or outside of the editor.
"""
return self.editor_offset_Y < mouse_y < self.editor_offset_Y + (s... | f0446b9607119d2ad439cc1933ab1723a0381ec0 | 477,852 |
import math
def euclidian(p1, p2):
"""Return euclidian distance between 2 points."""
return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2) | 82c326077e8a90ed067e7d6cd2d5aabfd9745499 | 50,546 |
def curvature_from_fit(fit, y):
"""Compute curvature radius
Args:
fit (numpy.ndarray[3]<float>): polynomial regression fit coefficients
y (float): point where curvature will be evaluated
Returns:
float: curvature radius
"""
if len(fit) != 3:
raise AssertionError(f"... | e4122c06e7e91da03aef0cafd21399a049004e1d | 496,389 |
def _rect(x: float,
y: float,
boxwidth: float,
boxheight: float,
fill: str = 'white',
strokewidth: float = 1):
"""Draw an SVG <rect> rectangle."""
return f'<rect x="{x}" y="{y}" width="{boxwidth}" height="{boxheight}" ' \
f'stroke="black" fill="{fill}... | ce0b88a946dc1f1d65a3ffe5fa81920be06a294b | 607,055 |
def is_within_region(readpos, contiglength, readlength, regionlength):
"""Checks if a read is within the given region."""
return readpos - readlength <= regionlength \
or readpos >= contiglength - regionlength | 934ce7f066de80beb5d0f65bbe6eb6707fdfb39c | 117,361 |
def load_stop_words(filename):
"""Load a set of stop words from a file.
One word each line."""
# you are using CPython, don't you?
# http://stackoverflow.com/a/11027437/1240620
stopwords = {w.strip() for w in open(filename)}
return stopwords | e23ec9a1d20396a0694bdd366a283bfbafb66f2b | 646,221 |
def to_unicode(obj):
"""Convert object to unicode"""
if isinstance(obj, bytes):
return obj.decode('utf-8', 'ignore')
return str(obj) | e54c02e04109b8a99a7eb4e357e95ead89166137 | 8,536 |
def onlyunix(f):
"""
Decorator that indicates that the command cannot be run on windows
"""
f._onlyunix = True
return f | 935bfe9f5fbb4b2341f79b3d7a7736e8664549cc | 408,338 |
def after_space(s):
"""
Returns a copy of s after the first space
Parameter s: the string to slice
Precondition: s is a string with at least one space
"""
return s[s.find(' ') + 1:] | d16fe547b562a7089a0babf9578e7a06f7a1f69e | 671,077 |
def get_bytes(encoded: bytearray, idx: int, length: int) -> tuple:
"""
Returns the bytes with given length, and next to be read index
:param encoded: bytearray
:param idx: index to start read from
:param length: length to be read
:return: tuple of bytes read and next index
"""
return enc... | 08fc9023b93680306e9d1703790fb86b092060be | 532,893 |
def strip_suffix(text, suffix):
"""
Cut a set of the last characters from a provided string
:param text: Base string to cut
:param suffix: String to remove if found at the end of text
:return: text without the provided suffix
"""
if text is not None and text.endswith(suffix):
return ... | 883ccee3bd3c48b80839d8ad4838a77720c28faf | 88,568 |
def format_human_readable_time(seconds):
""" format the number of seconds given as a human readable value """
if seconds < 60:
return "%.0f seconds" % seconds
if seconds < 60 * 60:
minutes = seconds / 60
return "%.0f minutes" % minutes
hour = seconds / 60 / 60
return "%.0f ho... | fefde7d1b3e7bb8ba0c3db5a949a0d728d6790a1 | 415,297 |
def compute_node_degrees(ugraph):
"""
Returns a dictionary of degree number for
all nodes in the undirected graph
"""
node_deg = {}
# iterate over all dictionary keys to find size of
# adjacency list for each node
for node in ugraph:
node_deg[node] = len(ugraph[node])... | a6d2f2df91b8536eca7814d54376f8b7855c2e7b | 44,379 |
import yaml
def parse_config_file(config_file) -> dict:
"""Read config.yaml file with params.
Returns
-------
dict
Dict of config
"""
with open(config_file, 'r') as stream:
try:
CONFIG = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(... | 8f1fb9bcda94ef5c21edbf5e5bf95b327efd8c96 | 8,673 |
def listify(argument) -> list:
"""
Turn `argument` into a list, if it is not already one.
"""
if argument is None:
return []
if type(argument) is tuple:
argument = list(argument)
elif not type(argument) is list:
argument = [argument]
return argument | c0ec40c9b487028fa38d3023752107a12b7f18d0 | 456,467 |
def bytesToStr(s):
"""Force to unicode if bytes"""
if type(s) == bytes:
return s.decode('utf-8')
else:
return s | 876e72d3b82c988edc92dce26969230cb04f17a8 | 207,022 |
def roots_linear(f):
"""Returns a list of roots of a linear polynomial."""
return [-f.coeff(0)/f.coeff(1)] | 6fbd70139c0c90d8c9e4dc5f42cce64908716f4d | 373,716 |
def _join_memory_tool_options(options):
"""Joins a dict holding memory tool options into a string that can be set in
the environment."""
return ':'.join(
'%s=%s' % (key, str(value)) for key, value in sorted(options.items())) | 20f61a8ed622de2bbe12d14936669196c8a6be26 | 340,893 |
import re
def strip_hive_comments(hive_query):
"""Strip the comments in a Hive query."""
regex = r'--.*'
flags = re.MULTILINE | re.IGNORECASE
return re.sub(regex, '', hive_query, flags) | 09bb1172d3753f2fdc5d0100120b77f09ea3066f | 365,188 |
import torch
def reference_loss_func(loss_sum_or_avg: torch.Tensor, num_measurements: torch.Tensor, take_avg_loss: bool):
"""
Returns average loss for data from``loss_sum_or_avg``. This function sums all losses from ``loss_sum_or_avg`` and
divides the sum by the sum of ``num_measurements`` elements.
... | 11771a75f53d03ff767591a8a4884a3f61f4406a | 437,967 |
def compute_number_of_clusters(
eigenvalues, max_clusters=None, stop_eigenvalue=1e-2):
"""Compute number of clusters using EigenGap principle.
Args:
eigenvalues: sorted eigenvalues of the affinity matrix
max_clusters: max number of clusters allowed
stop_eigenvalue: we do not loo... | 2d58a05c54ad0f178bba33ddfbc0c82cdb4fcfc3 | 454,822 |
def calculateSphereInertia(mass, r):
"""Returns upper diagonal of inertia tensor of a sphere as tuple.
Args:
mass(float): The spheres mass.
r(float): The spheres radius.
Returns:
: tuple(6)
"""
i = 0.4 * mass * r ** 2
ixx = i
ixy = 0
ixz = 0
iyy = i
iyz = 0
... | 324ddd5e9175971fbc45bf269118ce1a673718f6 | 410,115 |
def consolidate_grades(grade_decimals, n_expect=None):
"""
Consolidate several grade_decimals into one.
Arguments:
grade_decimals (list): A list of floats between 0 and 1
n_expect (int): expected number of answers, defaults to length of grade_decimals
Returns:
float, either:
... | 2125a562d90dad50d56b077f7c4573870b77437c | 266,677 |
import yaml
def load_vasp_summary( filename ):
"""
Reads a `vasp_summary.yaml` format YAML file and returns
a dictionary of dictionaries. Each YAML document in the file
corresponds to one sub-dictionary, with the corresponding
top-level key given by the `title` value.
Example:
The fil... | 236396afb16af6d30c5c39033e7efb122f25607b | 536,956 |
def function_maker(func):
"""Wraps a function to return [params, f(params)]"""
def f(params):
try:
r = func(**params)
except Exception as e:
r = e
return [params, r]
return f | ba1add09c09b924db27500f04c0c3938e3940e93 | 623,489 |
import re
def _make_regex(pem_type):
"""
Dynamically generate a regex to match pem_type
"""
return re.compile(
r"\s*(?P<pem_header>-----BEGIN {0}-----)\s+"
r"(?:(?P<proc_type>Proc-Type: 4,ENCRYPTED)\s*)?"
r"(?:(?P<dek_info>DEK-Info: (?:DES-[3A-Z\-]+,[0-9A-F]{{16}}|[0-9A-Z\-]+,[... | 1c1345520e37bb6c7ab75ae5856177c745f9f0fd | 177,306 |
def program(msg):
"""Returns the program value of a program change message."""
return msg[1] | 24cc307630dfe783a9b9157623d636b873c944bc | 463,037 |
def to_payload(aliases):
"""
Boxes a list of aliases into a JSON payload object expected
by the server.
"""
return {"aliases": [{"value": alias} for alias in aliases]} | 1950d4eac9fb6c9e211a7faafdea615a01179223 | 360,156 |
def compose(outer_function, inner_function):
"""
Utility function that returns the composition of two functions.
Args:
outer_function (function): A function that can take as input the output of
`inner_function`.
inner_function (function): Any function.
Returns:
func... | 75243aed676f106c7dba575f9cedf2c72c8059d3 | 199,691 |
from typing import Any
def flag(argument: Any) -> bool:
"""
Check for a valid flag option (no argument) and return :py:obj:`True`.
Used in the ``option_spec`` of directives.
.. seealso::
:class:`docutils.parsers.rst.directives.flag`, which returns :py:obj:`None` instead of :py:obj:`True`.
:raises: :exc:`Va... | 7aeb0b0ddf5b98cafebf868adbc95204518513db | 665,503 |
def escape_path(path):
"""
Adds " if the path contains whitespaces
Parameters
----------
path: str
A path to a file.
Returns
-------
an escaped path
"""
if ' ' in path and not (path.startswith('"') and path.endswith('"')):
return '"' + path + '"'
... | 6f3122532fa2590d43e9ad537d07f005d05c54fa | 646,486 |
import random
def make_n_length_integer(n1, n2, allow_negative=False):
"""Function that generates an integer with specified number of digits.
Parameters
----------
n1 : int
Lower boundary for the number of digits
n2 : int
Upper boundary for the number of digits
allow_negative ... | b277900036f30cefd5b2b5251320daa2fb4be139 | 504,328 |
def _ofc(id):
"""OFC ID converter."""
return "ofc-%s" % id | c31e2fb102c0238c943629de98cffeeac127cf29 | 628,111 |
def sieve_eratosthenes(range_to):
"""
A Very efficient way to generate all prime numbers upto a number.
Space complexity: O(n)
Time complexity: O(n * log(logn))
n = the number upto which prime numbers are to be generated.
"""
range_to=int(range_to)
# creating a boolean list first
pri... | b3f127295f988de6e0021d4137fc4e36290a5717 | 401,181 |
def _filter_features(
example,
feature_whitelist):
"""Remove features that are not whitelisted.
Args:
example: Input example.
feature_whitelist: A list of feature names to whitelist.
Returns:
An example containing only the whitelisted features of the input example.
"""
return {
fea... | 26f4afd9297f1b678761646494ebb83d4724ca01 | 70,379 |
def make_urls_list(ids_list):
"""
Appends each video id to the base url and insert them into a list
:param list ids_list: youtube video id list
:return list: list of urls
"""
base_url = 'https://www.youtube.com/watch?v='
urls_list = [base_url + _id
for _id in ids_list
... | 8e682a2f8e5c2b815f112435b50b4925f2ed146b | 203,879 |
def biggest_indices(items, n):
"""Return list of indices of n biggest elements in items"""
with_indices = [(x, i) for i, x in enumerate(items)]
ordered = sorted(with_indices)
return [i for x, i in ordered[-n:]] | fc1faf2720f605cceb007925aa1d54dca2f793de | 435,682 |
import re
def format_author_name(author_name):
"""Format the author name (string) as N Benabderrazik. If there are
multiple first names it would be: A B FamilyName where A and B are
the first letters of the respective first names.
"""
# Keep only strings before an opening parenthesis (e.g. disca... | 040128f4249f261a73bcbb59c8c34bd6dff201db | 302,893 |
def get_weights(model):
"""
Return weights of Keras model as a list of tuples (w, b), where w is a numpy array of weights and b is a numpy array
of biases for a layer. The order of the list is the same as the layers in the model.
:param model: Keras model
:return: List of layer weights (w, b)
""... | dcd18a9ffaa9afbb40b0df96cc98d1f9795d2431 | 224,385 |
def monthly_soil_heat_flux(t_month_prev, t_month_next):
"""
Estimates the monthly soil heat flux (Gmonth) [MJ m-2 day-1]
assuming a grass crop from the mean
air temperature of the previous month and the next month based on FAO
equation (43). If the air temperature of the next month is not known use
... | fa2e19f5f9839f4c75fcfee15c10b5227e2e1d6b | 238,263 |
def get_number_base(bitstring, base):
"""Transfer bitstring to a number in base `base`."""
nr = 0
for place, bit in enumerate(bitstring[::-1]):
nr += base**place * int(bit)
return nr | 1a54f84dd67b245009831258b7e50a28924e7f5b | 637,916 |
import re
def install_package_family(pkg):
"""
:param: pkg ie asr900rsp2-universal.03.13.03.S.154-3.S3-ext.bin
:return: device_type of the installed image ie asr900
"""
img_dev = None
m = re.search(r'(asr\d+)\w*', pkg)
if m:
img_dev = m.group(1)
return img_dev | b344d51ae426e167dbd2397ab93cbf8707b01496 | 708,790 |
def expectationFromObservationDF1(observation):
"""Returns the expectation values for observation values, assuming a table
of two columns and two rows represented in a value list observations.
That is, the first two values are assumed to be row 1, the second two
values are assumed to be row 2.
... | c8f62376eb70762f5e2def6b26a56e3677cedca8 | 137,690 |
import torch
def h_inverse(x, epsilon=1.0):
"""Inverse if the above h-function, described in the paper [1].
If x > 0.0:
h-1(x) = [2eps * x + (2eps + 1) - sqrt(4eps x + (2eps + 1)^2)] /
(2 * eps^2)
If x < 0.0:
h-1(x) = [2eps * x + (2eps + 1) + sqrt(-4eps x + (2eps + 1)^2)] /
(2 * ... | 3fdf30e5b02550eadefd63e60d72794424a29202 | 270,061 |
def parse_header(line):
"""Parse output of tcpdump of pcap file, extract:
time
date
ethernet_type
protocol
source ip
source port (if it exists)
destination ip
destination port (if it exists)
length of the data
resolved addresses (if the... | 3f2e84048f0e150e780752bec2bdb8897241275a | 565,473 |
def calculate_IoU(geom, match):
"""Calculate intersection-over-union scores for a pair of boxes"""
intersection = geom.intersection(match).area
union = geom.union(match).area
iou = intersection/float(union)
return iou | 92480c5cc7c1e3e99b6339a950256524a017ba3a | 664,252 |
def number_of_lines(filename=""):
"""Returns the number of lines of a text file.
Keyword Arguments:
filename {str} -- file name (default: {""})
Returns:
Int -- number of lines of a text file.
"""
with open(filename, mode="r", encoding="utf-8") as file:
return len(file.readl... | 63ffab8fa133356354052591e8b29101ad267ad9 | 684,676 |
def parse_data_url(data_url):
"""
Parses a data URL and returns its components.
Data URLs are defined as follows::
dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
mediatype := [ type "/" subtype ] *( ";" parameter )
data := *urlchar
parameter := attribute "=" v... | ebffe86b339ee7e00717842fea16ae33922becb1 | 216,918 |
def _wildcards(word, symbol="_"):
"""Return list of wildcards associated with word."""
res = []
for i in range(len(word)):
res.append(word[:i] + symbol + word[i + 1 :]) # O(L) space
return res | b12a7c530f7e937c1358bd2809e064419118f928 | 547,455 |
def getBuildStepVersion(step):
"""Return the unpickled builder's persistenceVersion.
The version reported in buildstep.persistenceVersion is what the currently
loaded version of buildbot expects a step to be (instead of what is pickled).
This returns what has been pickled.
"""
return getattr(step,
... | b2f9920a22108cc8c83fd657f81ed58779320f9f | 510,801 |
import re
def is_doi(doi: str) -> bool:
"""
check whether a string is a valid DOI
:param doi: the string to be checked
:return: True if a valid DOI, False otherwise
"""
if type(doi) is not str:
raise TypeError("The method only takes str as its input")
# prefix suffix separated by /... | 70962bc4df333cb8c861eb37b58b049086a2d57d | 387,349 |
def bounding_box_to_annotations(bbx):
"""Converts :any:`bob.ip.facedetect.BoundingBox` to dictionary annotations.
Parameters
----------
bbx : :any:`bob.ip.facedetect.BoundingBox`
The given bounding box.
Returns
-------
dict
A dictionary with topleft and bottomright keys.
... | 41b984e7824035ebda551712b5777c2aa4269de6 | 123,298 |
def mean(data):
"""
Get mean value of all list elements.
"""
return sum(data)/len(data) | 32884e9f1a29b2a37422ec1da04d0c59b6b67d3c | 38,651 |
from pathlib import Path
import shutil
def pwhich(command: str) -> Path:
"""Path to given command.
shutil.which only returns a string.
:returns: Path to command
:rtype: pathlib.Path
"""
path_str = shutil.which(command)
assert path_str, f"{command} not found"
return Path(path_str) | a926850cab35bace6c2187933438c44001d01eeb | 643,347 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.