content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def parse_labels(label_file_path: str) -> dict:
"""
Function to parse labels
Input:
label_file_path - path to audacity-style label file
Ouput:
dict in style of label_dict["class_name"]=(onset, offset, low_freq, high_freq)
"""
assert os.path.exists(label_file_path), f"Could no... | 6b13749fbe637482183a159bcdda37d7ffeae2d3 | 51,289 |
def list_widgfield(widgfield, widgfield_dict):
"""Converts a widgfield (with no i value), and a dictionary to a list of
of widgfield,value tuples, with each widgfield in the tuple having i set to the key
and the list is sorted by key"""
if widgfield.i:
return [(widgfield, widgfield_dict)]
... | 7e7a735cb17638e969c2c0211407d24f2de33084 | 51,290 |
def batch_to_numpy_images_and_labels(data):
"""Returns a list of images and labels from a data batch
Args:
data (batch): A data batch with labels and images
Returns:
tuple: A tuple of lists of labels and images
"""
images, labels = data
numpy_images = images.numpy()
numpy_l... | fe58dd02dfc7128928042ec7e2be65db6c18ce85 | 51,291 |
import os
import logging
def convert_spectpath_to_audiofpath(audiofolder: str, specpath: str) -> str:
"""
Finds the path of the audio file that corresponds to the spectrogram
found at `specpath`.
"""
specfname = os.path.basename(specpath)
wavfname = os.path.splitext(specfname)[0] + ".wav"
... | 7553e813b6d378fd9ee64efa3c3e50b8e0933276 | 51,292 |
def get_byte_array(integer):
"""Return the variable length bytes corresponding to the given int"""
# Operate in big endian (unlike most of Telegram API) since:
# > "...pq is a representation of a natural number
# (in binary *big endian* format)..."
# > "...current value of dh_prime equals
# ... | 09f432308ca62ee05273dc278178fde27bc18c40 | 51,293 |
def neutronify(name):
"""Adjust the resource name for use with Neutron's API"""
return name.replace('_', '-') | 660b403cbdcf3dea4c16439668a24d04a22acbf5 | 51,294 |
def calc_current_density(Nt: float, height: float, thickness: float, i_ph: float):
"""
Calculates the average current density of a superconducting winding, if the filling factor considered constant.
:param Nt: number of active turns in the winding [#]
:param height: height of the winding [mm]
:para... | 7ffc63c894686cc2d59e8636da0bf7ccdecc4464 | 51,295 |
def pluralize(num, singular):
"""Return the proper plural version.
Examples:
>>> pluralize(2, "meme")
'2 memes'
>>> pluralize(1, "thing")
'1 thing'
>>> pluralize(1, "class")
'1 class'
>>> pluralize(0, "class")
'0 classes'
"""
if num == 1:
return f"{num} {sing... | 458f09e95a9dbb329e719c50fc5c72c27e952057 | 51,298 |
def rangeSplit(rangeStr):
"""Return an array of numbers from a specified set of ranges.
Given a string such as "1 2 4-6 8" will return [1,2,4,5,6,8]. The numbers
and ranges can either be space separated or comma separated (but not both).
Keyword arguments:
rangeStr -- a string containing ranges s... | 60f8d2d7a051e6f7a1819b6de3da8f42a20179dc | 51,299 |
import torch
def compute_accuracy(y_pred, y_true):
"""
Computes the average accuracy given predictions and true labels
Parameters
----------
y_true : torch.Tensor
The list of true labels
y_pred : torch.Tensor
The list of predicted labels
"""
con... | 161952e666175ab6a8d8d2f9a262dc3e122ad5f4 | 51,300 |
def funnels_as_ini_section(funnels):
"""from a list of funnels, gives back a dict that can be exported to a
file that RTW can understand
"""
section_content = {}
for name, funnel in funnels.items():
section_content[name+ "Pos"] = round(funnel.position)
for name, funnel in funnels.items()... | cd9477ea6e8885c6b00e052932440deef6795b3c | 51,301 |
import os
def abspath(path: str) -> str:
"""Return os.path.abspath(path) if the path is on a local file system. If the
path is of form s3:..., return the path as is.
"""
if path.startswith('s3:'):
return path
return os.path.abspath(path) | 7458c48f69bc8c8f955c153ec2e624fd25261382 | 51,302 |
import pickle
def load_sample_illuminations():
"""Loads example illuminations sampled from the test set.
Returns:
Numpy arrays of azimuth_npy and lc_npy from the data directory.
"""
azimuth_npy = pickle.load(open("factorize_a_city/data/azimuth.npy", "rb"),
encoding="bytes")
... | 4fad1bd29e53e6246cd607486d9db48d834d8da2 | 51,303 |
def _filter_folders(folder_list, from_date_obj=None, to_date_obj=None,
min_price=0.0, max_price=None, transportation_mean=None,
min_segment_nb=1, max_segment_nb=None,
bicycle_without_reservation_only=None,
bicycle_with_reservation_only=None... | 698be54fae0cc1cc783ca6acc2662e25eb0dd22d | 51,305 |
def overlap(v1, v2):
"""Determine whether affected positions of two variants overlap."""
v1_b = v1.pos + max(len(v1.ref), len(v1.alt))
v2_b = v2.pos + max(len(v2.ref), len(v2.alt))
return min(v1_b, v2_b) - max(v1.pos, v2.pos) > 0 | 79c4e4958d0293896cb00937a8119d2c2bb7e696 | 51,306 |
import ast
import os
import imp
def load_rules(rules, root='./'):
"""
Load custom post-processing rules.
Rules should be added to the configuration file under a property called
"rules", which has key-value pairs mapping a unique rule name to a Python
file. Each Python file intended to be used as ... | 9fabc1ff2199bfa36464d44ddfcbccbfe37e28f3 | 51,307 |
def _get_plot_title(target_name: str, last_observation_date: str,
eval_dataset_creation_date: str,
forecast_horizon: int) -> str:
"""Gets the title of the plot."""
return (
f"Comparison of metrics for predicting {target_name}. Forecast date: "
f"{last_observation_... | bdd8a9a0d648342192200d7583cb4ed452ab989c | 51,310 |
from time import sleep
def fatorial(n, show=True):
"""
=> calcula o Fatorial de um número.
:param n: O número a ser calculado.
:param show: (opcional) mostra ou não a conta.
:return: O valor do fatorial de um número n.
"""
f = 1
print(f'\nO fatorial de {n} é: ')
sleep(0.5)
for ... | 1e364b70c0c0ebf03012635c22ff1839beac137a | 51,311 |
def list_chunk(target, n):
"""
리스트를 n개로 분할해줍니다.
**Example**
simple_utils.array.list_chunk(your_list, 5)
**Parameters**
* **target** (list) --
분할할 타겟입니다.
* **n** (int) --
몇 개씩 분할할지 정합니다.
"""
return [target[i:i+n] for i in range(0, len(target), n)] | 77d9ec17cacb339a7899c05156670ad5164aa9f5 | 51,312 |
def box_kernel_config(im_shape, block=(2, 4, 32)):
"""
block = (z=2,y=4,x=32) was hand tested to be very fast
on the Quadro P2000, might not be the fastest config for other
cards
"""
grid = (
(im_shape[0] + block[0] - 1) // block[0],
(im_shape[1] + block[1] - 1) // block[1],
... | e857371336e503d4a0f418075b81e21a07710a78 | 51,313 |
import os
import sys
def on_slurm_cluster():
""" On the cluster? """
return 'HPCCLUSTER_INSTITUTE' in os.environ and sys.platform.find('linux') != -1 | 3d2422db90e6c7cd0323c278cc6780139a56a589 | 51,314 |
import csv
def split_categories(cat, csv_path):
"""
access the sub-class of a categories and re-number the class ID.
:param cat:
:return:
"""
with open(csv_path, 'r') as file:
reader = csv.reader(file)
lines = [row for row in reader][1:]
isCat = []
for line in l... | 9db8d47f5c876156d13ec285c7c11542841b6b6c | 51,315 |
def _quote_if_str(val):
"""
Helper to quote a string.
"""
if isinstance(val, str):
return f"'{val}'"
return val | 5b216d94c1039c6a95947220badf414e2b6b3a93 | 51,316 |
def count_labels_distribution(data_loader):
""" Count dataset statistics """
bg_pix_count = 0
fg_pix_count = 0
for i, sample_batch in enumerate(data_loader):
labels = sample_batch['label'][:, :, :, :].numpy()
bg_pix_count += (labels == 0).sum()
fg_pix_count += (labels == 1).sum()... | daa65a759dca1c88b91bb58ff46b438bd6027142 | 51,317 |
import re
def extract_cast(soup):
"""
extracts the cast from the given page
:param soup: BeautifulSoup object of the page
:return: list of the cast
"""
info_row = soup.find(class_="cast_list").find("tr").find_next_sibling("tr")
cast = []
while info_row is not None:
actor = {}... | fdbde1167938dfe2f1fb61220dd1d70f4e869d54 | 51,318 |
from typing import List
def find_max_cross_subarray(sequence: List[int], low: int, mid: int, high: int):
"""Find max with a crossover point at mid"""
# NOTE: Observe the end points of the for loop, there is a chance to easily
# make off by one errors
# calculate the left sum
left_sum = float("-i... | 5c37d441f2ef7ff3f5b814532e1a58985884b096 | 51,320 |
from typing import Counter
def count_entities(entities):
"""
Return entity cound
:param entities:
:return:
"""
return Counter(entities).most_common() | 3a5e520489c54fc216f7367157f6622eedeea803 | 51,321 |
from typing import TextIO
from typing import List
from typing import Any
def count_birds(observations_file: TextIO) -> List[List[Any]]:
"""Return a set of the bird species listed in observations_file,
which has one bird species per line.
>>> infile = StringIO('bird 1\\nbird 2\\nbird 1\\n')
>>> count_... | 95fd1047d01a6cdc878de25b2a267745449b51a6 | 51,322 |
import os
def _sort_file_by_oldest(d):
"""
Get files and directories in specified path sorted by last modified time
:param d: directory path, ```str```
:return: a list of files and directories sorted by last modified time (old first), ```list```
"""
files = os.listdir(d)
files.sort(key=la... | 487e84cb49d5ea6ad039cc047ff0e5b93b9a47c5 | 51,323 |
def simpleInterest(p, r, t):
"""Simple interest
Returns: interest value
Input values:
See 'Simple interest future value' below
"""
i = p * r * t
return i | bda3e6fe4e922c531454843c6afbf177bfd788d6 | 51,324 |
import os
import re
def find_files(folder, regex, remove_empty = False):
"""
Find all files matching the [regex] pattern in [folder]
folder : string
folder to search (not recursive)
regex : string (NOT regex object)
pattern to match
"""
files = o... | 896e72a64b484d8e2b454bdb758ca90d6902a72a | 51,325 |
from typing import Union
import os
def result_file(file_path: str) -> Union[str, None]:
"""
Return a file path if it and the file_path directory exist
:param file_path: (str) where should be the file (e.g. ./tmp/file_id)
:return: (str) the file path in the directory if it exists,
None otherwise
... | 393e60ac595cdd74a488ae927eef0918f7a0f817 | 51,326 |
def take_out_npools_from_cmdline(cmdline):
"""
Wipe out any indication about npools from the cmdline settings
:param cmdline: list of strings with the cmdline options (as specified in
pw input settings)
:return : the new cmdline with the options about npools
"""
return [e for i,e in enu... | 6ae18ffb8092cfc9aca8d1016b28faa3c579769d | 51,327 |
def actors(hg):
""""Returns an iterator over all actors."""
return [edge[1] for edge in hg.search('(actor/P/. *)')] | 78e66fb98613e35a9892957951819d6759a61236 | 51,328 |
import json
def get_message_content_sents(parsedData):
"""
:param parsedData: data after being parsed by the en parser
:return: sentence recognition
"""
sents = {}
# the "sents" property returns spans
# spans have indices into the original string
# where each index value represents a ... | 35c8e0c68f30f25883f77076b91f80a578c75e7e | 51,329 |
import torch
def spknn(x, y, k):
""" knn serach
Arguments:
pos_support - [B,N,3] support points
pos - [B,M,3] centre of queries
k - number of neighboors, needs to be > N
Returns:
idx - [B,M,k]
dist2 - [B,M,k] squared distances
"""
B = x.size(0)
m, n = x.... | a334bb30e91139d57301be650fb6924bb435b7b8 | 51,330 |
def cvsecs(*args):
""" converts a time to second. Either cvsecs(min, secs) or
cvsecs(hours, mins, secs).
"""
if len(args) == 1:
return float(args[0])
elif len(args) == 2:
return 60 * float(args[0]) + float(args[1])
elif len(args) == 3:
return 3600 * float(args[0]) + 60 * ... | a4f39701a1b486e5df39555cf174d268f40be4a0 | 51,331 |
def is_small_calcification(bb_width, bb_height, min_diam):
""" remove blobs with greatest dimension smaller than `min_diam`
"""
if max(bb_width, bb_height) < min_diam:
return True
return False | 823af619ce76b08e0b4c36f2a2244dea3db813a0 | 51,333 |
def strings_to_services(strings, string_to_service):
"""Convert service strings to SUPPORT_* service bitmask."""
services = 0
for string in strings:
services |= string_to_service[string]
return services | e863ed240980dd5ed60e665c73a0d999681d0bde | 51,335 |
def _pkcs1_padding(m, size):
"""Add PKCS padding to the message 'm', so that it's appropriate for
use with a public key of 'size' bytes."""
# I'd rather use OAEP+, but apparently PyCrypto barely supports
# signature verification, and doesn't seem to support signature
# verification with nondeterm... | 430a5220b046034ac4caa79de7508c7613028d0b | 51,336 |
def build_interval_data(chanjo_db, sample_id, group_id, interval_data):
"""
.. versionchanged:: 2.1.2
Create model without adding it to the session.
"""
# create a new intervals data entry
return chanjo_db.create(
'interval_data',
parent_id=interval_data[3],
sample_id=sample_id,
group_id=g... | 844a1220258431573858d764a2a817d8dd0dfdf3 | 51,337 |
from typing import List
def process_covid_csv_data(covid_csv_data: List[str]):
"""Function that returns 3 variables from the csv file
variables returned:
- last7days_cases - cumulative number of cases from the last 7 days
- current_hospital_cases - number of current hospital covid-19 cases
... | ef50908b60e73d8f26ce605f5ea7da5389c883fc | 51,339 |
import re
def _verify_format(s, format):
"""
Make sure the input is in the right format
"""
r = re.compile(format)
if r.match(s) is not None:
return True
return False | 0078a16e053d68afb5d170bbe808763361bcaeab | 51,340 |
def hasSheBang(fname):
"""Checks fname is a #! script."""
with open(fname) as f:
return f.read(2).startswith('#!') | b5d04b3a28fd09b42e59b862a51afdbbe2e35ae9 | 51,343 |
def quote_escape(value, lf='&mjf-lf;', quot='&mjf-quot;'):
"""
Escape a string so that it can safely be quoted. You should use this if the
value to be quoted *may* contain line-feeds or both single quotes and double
quotes.
If the value contains ``\n`` then it will be escaped using ``lf``. By
d... | b9ad94a91e9fbecb9cef7c2f7fba362f09be25a7 | 51,345 |
def load_noise(front_path, end_path):
"""
Load the front and end noise
:param front_path:
:param end_path:
:return: List: front_list, end_list
"""
front_list = []
end_list = []
with open(front_path, 'r', encoding='utf-8') as front_f:
while True:
line = front_f.rea... | e1388935afc8437c0e773591d57a01fc79a1560f | 51,346 |
def str_to_array_of_int(value):
""" Convert a string representing an array of int into a real array of int """
return [int(v) for v in value.split(",")] | 244d8250e42665fd782b7dfbc52d1f5938d1d3d8 | 51,347 |
def is_json_response(req):
"""Returns True when the request wants a JSON response, False otherwise"""
return "Accept" in req.headers and "application/json" in req.accept | d566e03c84ebb6a26254fa14dbd794539caf5728 | 51,348 |
def convert_pt_to_in(pts: int) -> float:
"""Converts a length in pts to a length in inches.
Parameters
----------
pts : int
A length in pts.
Returns
-------
float
A length in inches.
References
----------
- https://www.overleaf.com/learn/latex/Lengths_in_LaTeX
... | 396438bd677cf267c3b9a83fab1198f3ab0808a5 | 51,349 |
def run(x_train, y_train, x_test, y_test, clf, epochs):
"""Train and test"""
test_err = []
clf.max_iter = 1
for i in range(epochs):
clf.fit(x_train, y_train)
terr = 1.0 - clf.score(x_test, y_test)
clf.warm_start = True
test_err.append(terr)
return test_err | 5b3616a4de8678464cb520688279f2184af32515 | 51,351 |
def mean(r):
"""Return the mean (i.e., average) of a sequence of numbers.
>>> mean([5, 10])
7.5
"""
try:
return float(sum(r)) / len(r)
except ZeroDivisionError:
raise ValueError("can't calculate mean of empty collection") | 08e6cf79231444735e5ba9d56765b96d6a3cfce0 | 51,352 |
def calc_log_probs(exp, result, batch):
"""
Calculates log_probs of batch
"""
mods = exp.modalities
log_probs = {}
weighted_log_prob = 0.0
for m_key in mods:
mod = mods[m_key]
ba = batch[0][mod.name]
log_probs[mod.name] = -mod.calc_log_prob(out_dist=result['rec'][mod... | 510e9c0210efde5507453e436dab72795feae36a | 51,353 |
def split_list(input_list):
"""Split input_list into three sub-lists.
This function splits the input_list into three, one list containing the
inital non-empty items, one list containing items appearing after the
string 'Success' in input_list; and the other list containing items
appearing after the... | 3c4d73b824b56e1f74cf1f5eeea7a86d829f2aed | 51,355 |
def add42(self, a_val):
""" Add a class constant to a variable. """
return a_val + self.A42 | 47f6ddd9b3e6c19a45787e7ec311e3fc2004c662 | 51,356 |
def synchronize_iterables(iterables):
"""Synchronize the given iterables in item-wise order.
Return: the {field: value} dictionary list
Examples
--------
>>> from nipype.pipeline.engine.utils import synchronize_iterables
>>> iterables = dict(a=lambda: [1, 2], b=lambda: [3, 4])
>>> synced =... | 4573e9c6a5a2bc04447b54e088ae68650b5f832e | 51,357 |
def clean_iso_timestamps(tl: dict) -> dict:
"""
Timestamps can be in any format, and our processing handles it okay
However, for testing purposes, we want the output format to line up,
and unfortunately there is some ambiguity in ISO timestamp formats.
"""
tl["timestamp"] = tl["timestamp"].repla... | e5747e28176cfe69e0d370a2c189fa89ca57125a | 51,358 |
def get_config(configs, requisition):
"""Get the associated config."""
for config in configs:
ref = "{}-{}".format(config["enduser_id"], config["aspsp_id"])
if requisition["reference"] == ref:
return config | 7f1a3ceaa845954984ef9f3c17c843097f82ad06 | 51,359 |
def zipstar(L, lazy=False):
"""
A much faster A, B, C = zip(*[(a, b, c), (a, b, c), ...])
May return lists or tuples.
"""
if len(L) == 0:
return L
width = len(L[0])
if width < 100:
return [[elem[idx] for elem in L] for idx in range(width)]
L = zip(*L)
return L if... | dc458ca547b5bdf7fccf9137f158f3eb67474ff7 | 51,360 |
import os
import re
def guess_source(filename_or_string):
"""Returns whether the source type of the content of the file or string is
xml, ttk or text. This is a guess because the heuristics used are simple and
are just searching the first 1000 characters of the input."""
# this needs to be large enoug... | b7ec72822c5fab002e18d3ead04051bcdde155c3 | 51,361 |
import zlib
def decompress_and_truncate(zipped, truncate=True, max_length=1000):
"""
Decompress a string zipped by zlib and truncate it
:param zipped: Zipped string
:param truncate: If it result be truncated
:param max_length: Specified length
:return:
"""
res = zlib.decompress(zipped)... | 63eaa83381e851721dde8a4726b93b59ce4a4317 | 51,362 |
def BuildAdGroupAdOperations(adgroup_operations):
"""Builds the operations adding a TextAd to each AdGroup.
Args:
adgroup_operations: a list containing the operations that will add AdGroups.
Returns:
a list containing the operations that will create a new TextAd for each of
the provided AdGroups.
... | 5786705380d9bd870c6ff9f391b0152de0241f75 | 51,363 |
def remove_values(the_list, val):
"""
Remove all items with value `val` from `the_list`
"""
return [value for value in the_list if value != val] | 071f7a2adf88540187b1eea6f1465ea6025bc2d7 | 51,364 |
def is_valid(x, size):
""" 実行可能解であることを確認する """
return all(-1 < i < size for i in list(x)) | 1deda8370707eb586053e6e897f5fbdcfc0976ee | 51,365 |
def flatten(list_of_lists):
"""Return a list-of-lists into a single list with only items in it."""
return [item for inner_list in list_of_lists for item in inner_list] | 2ec2ccca79377b9f99417e630a9b7f0ab513c3d4 | 51,366 |
def get_state_dict(model):
"""Return model state dictionary whether or not distributed training was used"""
if hasattr(model, "module"):
return model.module.state_dict()
return model.state_dict() | fe1f22c63dac3b7d96b0f0485c9a010e98bae2f5 | 51,367 |
import os
def IsWindows():
"""Checks whether or not the script is running on Windows.
Returns:
True if running on Windows.
"""
return os.name == 'nt' | 65b76b5bb5b94c7a6294a5099a3be5f77bb4961b | 51,370 |
def permutation(l):
"""
Code plagiarized from StackOverflow. With a given list of values,
this function changes the list in situ to the next permutation.
This function differs from itertools.permutations in that it takes
into account repeated values in the list and avoids returning duplicates.
... | bc8f987696021fd31eb6232b602e6932f28425e7 | 51,371 |
def get_total_expenses(context):
"""
Gets the total of all expenses
returns an integer
"""
return sum(map(lambda x: x.amount, context['Expenses'])) | 59b91c4b2ad8abfe4719e55b31aeab71d5b18db9 | 51,372 |
import sys
def builtins_module():
"""
Python3 renames the __builtin__ module to builtins.
This function returns whichever is correct for the python version.
"""
if sys.version_info >= (3, 0):
return "builtins.open"
else:
return "__builtin__.open" | 5256f599feb815e209c49244709e14c61c1c446c | 51,374 |
def printed(o, **kwargs):
"""Print an object and return it"""
return print(o, **kwargs) or o | a40f40541999ebb8bd9b9e61b6d2dbd7b77a6722 | 51,376 |
def ele_C(w, C):
"""
:param
w: Angular frequency [1/s], (s:second)
C: F
:return:
"""
return 1 / (1j * w * C) | 5c2c8126ff54a2ab359d80b1a92315d69f7acf1b | 51,378 |
def onCircle_elements(nelx,nely):
"""
return a list of the element centroid located on the border
of a circle of radius nelx
"""
list = []
for x in range(nelx):
for y in range(nely):
if abs(((x-(nelx-1)/2.0)**2+(y-(nely-1)/2.0)**2)**.5 - (nelx-1)/2.0) < .5 :
l... | bdaf5a5420a8811d00b73099c15f9719f9795a60 | 51,379 |
from pathlib import Path
def museum_packages_dir(tmpdir, monkeypatch):
"""
Fixture pointing to a directory containing museum packages
"""
path = Path(tmpdir) / "MuseumPackages"
path.mkdir(exist_ok=True)
return path | 0625b8dbb41ec320772d359d47d3b572ad2d7c36 | 51,381 |
import psycopg2
from psycopg2 import sql
import os
def test_data_db(image_name, structure, database_name):
"""Inputs: string describing the name of an image and a string describing a subcellular structure in that image
and a connection object
Tests if any object data for a given structure and image has b... | 09539121b7b9077480ff40917e1b197443f17246 | 51,382 |
def is_bool(value):
""" Checks if the value is a bool """
return value.lower() in ['true', 'false', 'yes', 'no', 'on', 'off'] | c71cac1dbf2ffacc2da420906bc7588bd4f416ec | 51,384 |
import click
def modify_pileups(ctx, normalize, startpos, endpos, no_coverage, pileups):
"""
modify_pileups - Performs normalization, truncation and/or selecting the
range of the pileup, if these options are enabled.
INPUT:
[CONTEXT] [ctx]
[BOOL] [normalize/dont_norm... | e6e7674e9d59d080de60a6a808416cb7b6828c19 | 51,385 |
def get_slope(x,t):
"""This function calculates the slope of a peak from exceeding the threshold to the maximum.
Args:
x (list): x Values from which the slope is to be determined
t (list): time section from which the slope is to be determined
Returns:
slope (flo... | 5c8b7347d5b3abeb633fd6990afc68a288c0f733 | 51,386 |
import os
import time
def get_file_age(filename):
"""
Returns age of file in seconds
:param str filename: file to inspect
.. versionadded:: 1.0.0
"""
mtime = os.path.getmtime(filename)
now = time.time()
return int(now - mtime) | e8ab862ebe28c00f24801fe17ae3fc30be0af479 | 51,387 |
def _unmangle_name(mangled_name, class_name):
"""Transform *mangled_name* (which is assumed to be a
"_ClassName__internal" name) into an "__internal" name.
:arg str mangled_name:
a mangled "_ClassName__internal" member name
:arg str class_name:
name of the class where the (unmangled) name... | 681e7b0e05b2feda22764149feafd8da89609ebc | 51,388 |
import math
def get_page_numbers(resources, page):
"""
Get the pagination information for the request.
Parameters
----------
resources: array
List of top level resources
page: int
Page number passed through the query parameters
Returns
-------
A dictionary of page... | 4880d846374af9b915bb3cff69adaa4fafde18ce | 51,389 |
def name(name):
"""Args, positional, are parsed in the order they're added in"""
return name | 442feb1ecfd083dc6880855e05eaec2f4e460722 | 51,391 |
import sys
def _GetCommandStdout(proc):
"""Extract the stored standard error, print it and return it.
"""
out = proc.stdout.read()
sys.stdout.write(out)
return out | 2dc136ede014276ace2128b757b4ae0b6911c05d | 51,392 |
def find_largest_digit(n):
"""
:param n: int, a number that we want to get the largest digit of.
:return: int, the largest digit in n.
"""
# convert negative integer to positive.
if n < 0:
n = n*-1
# base case
# return will n is a single digit number.
if n < 10:
return n
# recursive case
else:
k = n ... | 1e14a231a60b87d03eb6b7e38f8b65c6c9442b6b | 51,394 |
def storage_management_feature(cpc_or_partition):
"""
Return a boolean indicating whether the specified CPC, or the CPC of the
specified partition has the DPM storage management feature enabled.
On z13 and earlier, the storage managemt feature is always disabled.
On z14 and later, the storage manag... | 559a7646d2304ff915366751c52ba9c8b636b012 | 51,395 |
import json
def to_json(data):
"""Converts Python data to JSON.
"""
return json.dumps(data).encode('utf8') | 512ba5c2df08029a735b6046ebc977210117dbdc | 51,396 |
def state_derivatives(states):
"""Returns functions of time which represent the time derivatives of the
states."""
return [state.diff() for state in states] | c8daf98027e9949be2a12db7acb799ed6c9845c0 | 51,397 |
from typing import Callable
from typing import Iterable
def sort_by(key: Callable):
"""Return a new list containing all items from the iterable in ascending order, sorted by a key.
>>> sort_by(len)(["hi!", "my", "name", "is"])
['my', 'is', 'hi!', 'name']
"""
def sort_by(seq: Iterable):
re... | 9e37364aa604c170c599286829c60b2f8a7f2ae4 | 51,398 |
def IntValidate(text):
"""
vérifie si l'entrée est une string convertible en integer ou vide
"""
if text == "":
return True
try:
int(text)+1
except Exception as e:
# print(e)
return False
return True | a40dff48f2e2b4110a27e8ef3ad32b791e1bbe69 | 51,399 |
def obj_ratio(dets):
"""Calculate the ratio of one ojbect detected versus anything not one.
Parameters
----------
dets : list of lists
The list of how many ojbects were detected.
Returns
-------
ratio : float
The ratio of when one object was detected versus some... | f872c6265a0bf7f43007b1cc687fa2c32eaf64b6 | 51,401 |
def timeformatter(x, pos):
"""The two args are the value and tick position"""
return '{}:{}:{:02d}'.format(int(x/3600), int(x/24/60), int(x%60)) | 281edb1ff155597925d6742d06d42d579a6059e2 | 51,402 |
def human_bytes(num, suffix='B', use_binary_prefix=True):
"""Provide a human readable representation of a specified number of bytes.
Convert a number of bytes into a higher order representation such as megabytes
or gigabytes to make more human readable. Similar to specifying `-h` in many command
line t... | 4bb21c33fb8cadfde03e0d084b3ed61ea6414970 | 51,403 |
def read_binary_metadata(metadata_file):
""" Read the metadata of a binary file.
Arguments:
metadata_file: str
Metadata filename.
Returns:
metadata: dict
Metadata.
"""
fid = open(metadata_file, 'r')
trans_tab = str.maketrans(dict.fromkeys('\n{}'))
met... | 074ce259221efb906a305119a8a1eeef744c2031 | 51,404 |
def color_tuple_to_hsl(three_tuple):
"""
Converts a (h, s, l) to a valid CSS value.
h: hue
s: saturation (in %)
l: lightness (in %)
"""
return 'hsl({}, {}%, {}%)'.format(*three_tuple) | 5ea546bef92fe2dfa40b5440e8d0004330ee5299 | 51,405 |
def process_group(grp):
"""
Given a list of list of ints,
where two ints share a directed edge
u-v with v > u if v = u + i for some
i in (1, 2, 3), compute the total number
of branches (or equivalently leaves) in
this directed tree.
:param grp: The list of list of ints.
:return: The... | 30192a6773a6d008e3c6b7f47b136ce80680df24 | 51,406 |
def fmt_filename(text):
"""File name formatter.
Remove all file system forbidden char from text.
**中文文档**
移除文件系统中不允许的字符。
"""
forbidden_char = ["\\", "/", ":", "*", "?", "|", "<", ">", '"']
for char in forbidden_char:
text = text.replace(char, "")
return text | 5326a74dfd1887f3d17141824b96e5b2459eea53 | 51,407 |
import requests
def lint_file(file):
"""Lints GitLab CI file. Returns True on success"""
with open(file) as f:
r = requests.post(
"https://gitlab.com/api/v4/ci/lint",
json={"content": f.read()},
verify=False,
)
if r.status_code != requests.codes["OK"]:
... | 08c5fb309d2ac4608da388d85392efd5bcd96a60 | 51,409 |
import os
import json
def load_recipes_from_dir(directory):
"""Loads all recipe JSON files from a given directory."""
recipes = []
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(".json"):
with open(os.path.join(root, file)) as jsonf:
recipe_json = json.... | 3b8c9044aeb145a6528957eedf3d05544be0bb27 | 51,410 |
def escape(x):
"""
Shell escape the given string
Implementation borrowed from now-deprecated commands.mkarg() in the stdlib
"""
if '\'' not in x:
return '\'' + x + '\''
s = '"'
for c in x:
if c in '\\$"`':
s = s + '\\'
s = s + c
s = s + '"'
return... | f4943943be451fd71189f457d2ab06e4ae7918e1 | 51,411 |
from typing import Dict
from typing import Optional
from typing import Any
def nested_get(dictionary: Dict, *keys: str) -> Optional[Any]:
"""Get nested object from dict."""
if len(keys) > 1:
return nested_get(dictionary.get(keys[0], {}), *keys[1:])
elif len(keys) == 1:
return dictionary.ge... | 2a4f441a27ae24cf1fddb304144d2bb0ed433cc5 | 51,413 |
def div(num1, num2):
"""
Divides two numbers
>>> div(4,2)
2.0
Raises zero division error
>>> div(4,0)
Traceback (most recent call last):
...
ZeroDivisionError: division by zero
"""
return num1 / num2 | b575f4addbbc5319a56b9aa5c5e555a40eab9930 | 51,415 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.