content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def datachild_yaml_map() -> dict:
""" """
return {
"data": {
"list": [0, 1.0, 2e2, 1, b"a", "f"],
"set": {None, True},
},
"level": 1,
} | 4f0a8a6e7553a5067aeb2211c4f46584dad6ca79 | 670,478 |
import os
def is_image_file(filename):
"""Does `filename` appear to be an image file?"""
img_types = [".jpg", ".jpeg", ".png", ".gif"]
ext = os.path.splitext(filename)[1]
return ext in img_types | b2f1c1f3ba11de53ba2f735362e990e8c69b3dc4 | 670,479 |
import glob
import os
def get_boards():
"""Returns a list of all available boards."""
all_socs = glob.glob("meta/boards/*yaml")
return list(map(lambda x: os.path.splitext(os.path.basename(x))[0], all_socs)) | 492df9a6a71f1e6309c4e6d049513fc397d0823d | 670,480 |
def calc_V_drop_lamb_dielectric(zeta, q_debye, C_dl, phi_channel):
"""
THIS IS WRONG - THIS IS WRONG - THIS IS WRONG
Calculate the voltage drop across the Stern/dielectric and Debye layers throughout the channel
units: V
"""
V_drop_lamb_dielectric = zeta - q_debye/C_dl + phi_channel
return V... | 2732db5fe8acdb6b5c317657452bcb9add22534f | 670,481 |
def I2I0_pow(n0, theta0, r, I=1):
""" Convert Intensity I(r) at r to I at theta_0 with power law.
theata_s and r in pixel """
I0 = I * (r/theta0)**n0
return I0 | 14f03eae1abd53de0d2f31d7feceb7891b447f0f | 670,482 |
def normalize_wiki_text(text):
"""
Normalizes a text such as a wikipedia title.
@param text text to normalize
@return normalized text
"""
return text.replace("_", " ").replace("''", '"') | ec3855b8661ae67abc6ca84d03634ff48437ad58 | 670,483 |
from typing import Any
from typing import Union
def try_parse_int_float_str(candidate: Any) -> Union[float, int, str]:
"""
Tries to parse the given value as an int or float. If this does not work simply the
string-representation of the candidate will be returned.
Examples:
>>> res = try_parse... | 2a356253cf55c429e1ac9cfdfd31eaaef54037e9 | 670,484 |
def find_edf_events(raw):
"""Get original EDF events as read from the header.
For GDF, the values are returned in form
[n_events, pos, typ, chn, dur]
where:
======== =================================== =======
name description type
======== ================... | 6015da7468ae92b4a12a13122682a3d47db3d831 | 670,485 |
def buildup_function(p, E_max, p_half):
"""Calculate asymptotic buildup curve
Args:
p (array): power series
E_max (float): maximum enhancement
p_half (float): power at half saturation
Returns:
ndarray: buildup curve
.. math::
f(p) = 1 + E_{max} * p / (p_{1/2} +... | bdc43e2fd12336ee0b415c4d574f2a62a5555217 | 670,486 |
def plot_hsu(hst, models, max_speed, pressure_charge, max_pressure):
"""
For the given HST computes the sizes, efficiencies and plots the efficiency map.
Returns:
---
fig: plotly figure object
"""
hst.compute_sizes()
hst.compute_speed_limit(models['pump_speed'])
hst.add_no_load((180... | 0e2b5db439ce4c102d06a58f02c2483e00d3263d | 670,487 |
def multiplica(x, y, z=None):
"""Multiplica x, y, z
Multiplica x, y e z = o programador pde omitir a variavel z
caso nao tenha necessidade de usa-la
"""
if z:
return x * y
else:
return x * y * z | 265e33da34c43d2926cc6ef308946f00d4ba34e7 | 670,488 |
def format(dt, fmt = "dt", simplified = True):
"""Format a datetime object.
Use a python :py:class:`datetime.datetime` object and convert it to a string,
wrapping the :py:meth:`datetime.datetime.strftime` method.
For convenience, enable the interpretation of a simpler syntax for common and
default ... | 8b5f86b91f9d617bcc931c2f6e43aee9f3921915 | 670,489 |
import mpmath
def _fmod(x, y):
"""
returns x - n * y, where n is the quotient of x / y, rounded
towards zero to an integer.
"""
fquot = mpmath.mpf(x) / y
if fquot < 0:
n = -mpmath.floor(-fquot)
else:
n = mpmath.floor(fquot)
return x - n * y | 51ba5b89ba0f0409ae70c39e31e7cbacdbfcd3c2 | 670,490 |
def dest_file(file_name):
"""
"Add.asm" -> "Add.hack"
"""
naked = file_name.rsplit('.', 1)[0]
return naked + '.hack' | 26def31853ef3eecac584c45a05ec9aa3365d7f5 | 670,491 |
def THETA_0():
"""
The `THETA_0` function returns the value for the Earth's Rotation Angle
(ERA) at J2000.0 according to the IERS numerical standards (2010).
"""
return 0.7790572732640 | b4c58a9a836359e21052ee8e012f84f32503e98f | 670,493 |
def get_id(x):
"""Pro zadany znak v rozsahu 'a' - 'z' vrati hodnotu 0 - 25."""
return ord(x) - ord('a') | 30d4cc52d2ae3cd403ecc4fc555c35e030bf5078 | 670,495 |
def _factors_sum(idadf, columnlist, valuelist):
"""
Compute the arithmetic sum over for all columns in a list (valuelist)
over the IdaDataFrame grouped by a list of columns (columnlist).
Parameters
----------
columnlist : list
List of column names that exist in self.
valuelist : lis... | 57b29dea6310b98b05c90c5ace163dfa9f47215a | 670,496 |
def count_in_list(my_list, count_for=1):
""" Gets the count of a certain value in a list.
Args:
my_list (list of obj): The list to search through.
count_for (obj): The object to count.
Returns:
int: The number of that object
"""
count = 0
for item in my_list... | 6cd59227fc7f6a08f254970a5495bd705d464597 | 670,497 |
def depth_first_search(graph, start, end):
"""
Determines path from start to end using
'depth first search' with backtracking.
:param graph: class Graph
:param start: start node
:param end: end node
:return: path as list of nodes.
"""
if start not in graph:
raise ValueError(... | 98a15ae24c2a081e2655c925daa4c278e1e12a0a | 670,498 |
import os
def is_path_exists(path):
"""check path
check path existence
Args:
path (str): analyze control queue file path
Returns:
True/False (boolean): exist:True not found:False
"""
try:
directory = os.path.dirname(path)
fl = os.listdir(directory + "/")
... | e90ff86bc900a0f7c8dfcc79fc6bce01ef3055c0 | 670,501 |
from typing import List
from typing import Tuple
def triplets(n : int) -> List[Tuple[int, int, int]]:
"""Précondition : n >= 0
Retourne la liste des triplets (i,j,k) sur l'intervalle [1;n]."""
i : bool
return [(i, j, k) for i in range(1, n+1)
for j in range(1, n+1)
... | dc14db376bf8ea00f37c2981b2e632d4b604dd31 | 670,502 |
def get_terciary_topic(lda_model, corpus):
"""
Extract dominant topic for each document and its percentage contribution.
"""
doc_topics = []
doc_topics_percent = []
for document in corpus:
topics_dist = lda_model.get_document_topics(document)
if len(topics_dist) > 1:
... | 7a90fbfac1a3ee33a880cd9f42db318ca7d0ef22 | 670,503 |
def pool_sku(config, lower=False):
# type: (dict, bool) -> str
"""Get Pool sku
:param dict config: configuration object
:param bool lower: lowercase return
:rtype: str
:return: pool sku
"""
sku = config['pool_specification']['sku']
return sku.lower() if lower else sku | 6049ac4ec80e452bf2f6c8405e1d0085e230c668 | 670,504 |
import time
def time_now():
"""returns current unix time as an integer"""
return int(time.time()) | 6296d37b49fe5784f5a0a83fd1c26e660b345f25 | 670,505 |
def filter_latest_builds(builds):
"""Filters Build objects to include only the latest for each builder.
Args:
builds: A collection of Build objects.
Returns:
A list of Build objects; only one Build object per builder name. If
there are only Builds with no build number, then one is ... | e1ecc4a5bb8ced67a6913c1a7662d52ad03fc84e | 670,506 |
def checksum(number, alphabet='0123456789'):
"""Calculate the Luhn checksum over the provided number. The checksum
is returned as an int. Valid numbers should have a checksum of 0."""
n = len(alphabet)
number = tuple(alphabet.index(i)
for i in reversed(str(number)))
return (sum(nu... | a40fb8175bbd8aa4d1185e3ad3765f62db89df95 | 670,508 |
def racks_for_replica_list(replicas, pos=None):
"""
Returns a set of racks for each of the given replicas in the list
Skip the replica at position pos, if specified
:params replicas: a list of Broker objects
:params pos: a replica position to skip, or None to not skip a replica
:returns: a list... | 830d3e9ba1072d6e54bed5c1328f6d20a5346d0b | 670,510 |
def is_text(bytesio):
"""Return whether the first KB of contents seems to be binary.
This is roughly based on libmagic's binary/text detection:
https://github.com/file/file/blob/df74b09b9027676088c797528edcaae5a9ce9ad0/src/encoding.c#L203-L228
"""
text_chars = (
bytearray([7, 8, 9, 10, 11, ... | 548b89e3c3c685b7225fce24bff43aca62918272 | 670,511 |
def create_getter(key):
"""Create getter method."""
def f(self):
return self._values[key]
return f | 837f3a8424e6c2f90d40dd8afd678b2933e6b608 | 670,512 |
def session_device(request, var, Session="auth_device"):
"""
Set a Session variable if logging in via a subacc
This will be linked to a decorator to control access to
sections of the site that will require the master account to be used
:param request:
:param session: default is auth_device
:... | c216eecbe521c35b63ce7efd9dd8faccb438ae4c | 670,513 |
def insertion_sort(arr):
"""Sorts the given array using insertion sort.
Average/worst case is O(n^2).
Best case is O(n).
Arguments:
arr: The array to sort.
Returns:
The array arr, but sorted.
"""
# i keeps track of the end of the sorted
# section. The element immediate... | deacf9459d28c32953687d3fe20948f243a0a227 | 670,514 |
def tbody(
trContent=""):
"""
*Generate a table body - TBS style*
**Key Arguments:**
- ``trContent`` -- the table row content
**Return:**
- ``tbody`` -- the table body
"""
tbody = """<tbody class="">%(trContent)s</tbody>""" % locals()
return tbody | c4fd63b07aba144205a39e7fd841459bbdbba39f | 670,515 |
def sample_width_to_string(sample_width):
"""Convert sample width (bytes) to ALSA format string."""
return {1: 's8', 2: 's16', 4: 's32'}[sample_width] | 5a08a08d845a1727f206e822045a5619db33347a | 670,516 |
import hashlib
def sha256(payload):
"""This function returns the sha256 of the provided payload"""
return hashlib.sha256(payload).digest() | 05e5fef168521265c0fdfa0b82ca18930baadef6 | 670,517 |
import os
def create_md_path(label):
"""
create MD simulation path based on its label (int),
and automatically update label if path exists.
"""
md_path = f'omm_runs_{label}'
try:
os.mkdir(md_path)
return md_path
except:
return create_md_path(label + 1) | 3e9b3d771f1a05a0fce199ebb52a7d70ac4c2479 | 670,518 |
def _generate_snitch_text(cluster):
"""Generate the text for the PropertyFileSnitch file"""
i=1
contents = [
"# Auto-generated topology snitch during cluster turn-up", "#",
"# Cassandra node private IP=Datacenter:Rack", "#", ""
]
for z in cluster.keys():
contents.append("# Zo... | a37d30101f8588ebc4b32c665834504455b5b93c | 670,519 |
from collections import OrderedDict
def readResult(fname):
"""
Open results file, extract and return minimum point as OrderedDict
and return raw list of all other lines for further processing.
"""
RES=[]
OTH=[]
with open(fname) as f:
for line in f:
l=line.strip()
... | 81fb8aa081a42a10691e0fedfcb4b727dce407db | 670,520 |
import re
def _identifier_for_name(name, *reserveds):
"""Makes an identifier from a given name and disambiguates if it is reserved.
1. replace invalid identifier characters with '_'
2. prepend with '_' if first character is a digit
3. append a disambiguating positive integer if it is reserved
:p... | e75089624367e2f6bde9a6e7ac1f8657222efc2d | 670,521 |
import subprocess
def runcmd(cmd, shell=False, check=False):
"""
Run command.
Args:
cmd: Command to run. Array with value for each arg, unless shell is True or there's only 1 arg (binary to run).
shell (opt, False): Whether to run command in a shell.
check (opt, False): Whether to throw except... | 258fac7f6c41ff6a9a143dc57b4796a31996e868 | 670,523 |
import mpmath
def var(lam):
"""
Variance of the Poisson distribution.
"""
return mpmath.mpf(lam) | 601c5e800bdb94e2c30c51eab84e8569b378b000 | 670,524 |
import traceback
def isTestMode():
"""
Returns true if we detect the TestCase class in stack
"""
for line in traceback.extract_stack(None):
if 'unittest' in line.filename:
return True
return False | a043cfd0ac89c191fe0fe3c9867d761d00803d8f | 670,525 |
def scale_to_range(min_max_old, element, min_max_new=[0, 10]):
"""Scale element from min_max_new to the new range, min_max_old.
Args:
min_max_old: Original range of the data, [min, max].
element: Integer that will be scaled to the new range, must be
within the old_range.
min... | 263f08a7247af4feea9f498bd2ac2a129f949556 | 670,526 |
import os
def do_compile(infile, outfile, extras):
"""Create the command-line for a C compiler invocation."""
if os.path.splitext(infile)[1] == '.C' or 'g++.dg' in infile: # lol windows
return [extras['cxx'], infile, '-o', outfile] + extras['cxxflags']
else:
return [extras['cc'], infile, '-o', outfile]... | efd2208d6bbc60a5b1f57854e1fe7b549a42e42c | 670,527 |
def output_file_version() -> str:
"""A suffix that is added to output files, denoting a version of the data format"""
return 'v5' | 713162ae39175fd8cd57ea8cb176c5970cf758b9 | 670,528 |
import os
def getTestSuiteName(testDir):
"""
Extracts test suite name from the given directory structure.
Example:
testDir = "/home/user/zserio/tests/language/enumeration_types/python
testSuiteName = getTestSuiteName(testDir)
print(testSuiteName) # prints "language/enumeration_types"
:pa... | ef74db78ff544457413a19b13983003059090292 | 670,529 |
def collate_sampling_metrics(ld_metrics):
"""Converts Langevin metrics into TensorBoard-readable format.
Args:
ld_metrics: A tensor with metrics returned by annealed_langevin_dynamics
sampling procedure.
"""
num_metrics, num_sigmas, num_steps = ld_metrics.shape
del num_metrics # unused
sampl... | e9f462f1a8dd4636f76c11c907a342d9c35bcd91 | 670,530 |
def _GetBrowserPID(track):
"""Get the browser PID from a trace.
Args:
track: The tracing_track.TracingTrack.
Returns:
The browser's PID as an integer.
"""
for event in track.GetEvents():
if event.category != '__metadata' or event.name != 'process_name':
continue
if event.args['name'] =... | 1e9a5900a4cd9930f8c634c8f0a932eae4873764 | 670,531 |
def mean(x1, x2):
"""Integer average."""
return (x1 + x2)/2 | a4f8a0df5d90bd8cde5b37682c7ca2a2e7e8a602 | 670,532 |
def get_time(seconds):
"""Returns human readable time format for stats."""
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
return "%dd:%dh:%02dm:%02ds" % (d, h, m, s) | 1a1c5439dabcfbde4d78c6aeccff4472a9b45f0a | 670,533 |
def manhattan_distance(x: int, y: int) -> int:
"""compute the manhattan distance"""
return abs(x) + abs(y) | 19c0db41c6cb332cd6da63e9d37f6a1a44ce63b7 | 670,534 |
import selectors
def is_readable(fileobj, *, timeout=None):
"""Check that the file-like resource is readable within the given timeout via polling.
:param Union[int, SupportsFileNo] fileobj:
:param Optional[int] timeout: (in seconds)
:return bool
"""
with selectors.DefaultSelector() as selecto... | 7ddff8c6e782973c26b15347c8c1aebea9552caa | 670,535 |
def manage_time(timestamp):
"""
Given the string representation of a the time using the
"minutes:seconds[:miliseconds]" representation, returns the number
of seconds using double precision
"""
time_strip = timestamp.split(":")
seconds = int(time_strip[0]) * 60 + int(time_strip[1])
# Ad... | 8782a2c49c70cfd6a3c4f2869c71f86a3576c2ec | 670,536 |
def check_syntax(code):
"""Return True if syntax is okay."""
try:
return compile(code, '<string>', 'exec')
except (SyntaxError, TypeError, UnicodeDecodeError):
return False | 77a27c4baceb814159e5530cc44888572943933b | 670,537 |
import json
def parse_genres(movie):
"""
Convert genres to a dictionnary for dataframe.
:param movie: movie dictionnary
:return: well-formated dictionnary with genres
"""
parse_genres = {}
g = movie['genres']
with open('genre.json', 'r') as f:
genres = json.load(f)
for k... | 079221e858868fdc4db250bb8b2fc7046efb213d | 670,538 |
import torch
def filter_maxima(image, min_distance=2, threshold_abs=0.05, threshold_rel=0.5, pad=True):
""" Similar to skimage.feature.peak.peak_local_max(image, min_distance=10, threshold_abs=0, threshold_rel=0.1, num_peaks=inf)
Args:
image: tensor (B,C,H,W), density map
min_distance: int
... | 8b963abcab389e4825dbf607ca87f628b64a847c | 670,540 |
from typing import List
def primes_sieve(limit: int) -> List[int]:
"""Returns all primes under ``limit`` in increasing order."""
a = [True] * limit
a[0] = False
for i, isprime in enumerate(a[1:], start=2):
if isprime:
for n in range(i * i, limit + 1, i):
a[n - 1] =... | aafc0f6598003e80503ec656dee3b6e3af92d06b | 670,542 |
def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float:
"""
Convert a given value from Rankine to Celsius and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
>>> rankine_to_celsius(2... | d77bbd977777960650b06ee804dd30891cb665b9 | 670,543 |
import math
def distance(point_a, point_b):
"""
Returns the distance between two points given as tuples
"""
x0, y0 = point_a
x1, y1 = point_b
return math.hypot(x0 - x1, y0 - y1) | d41cec3978ea62b3b93e1e64b1f1103bce88d231 | 670,544 |
def estimate_clipping_rect(projector, size):
"""
Return:
rect -- NSRect style 2d-tuple.
flipped (bool) -- Whether y-axis is flipped.
"""
# lt -> rt -> lb -> rb
image_corners = [(0, 0), (size[0], 0), (0, size[1]), size]
x_points = []
y_points = []
for corner in image_corners:
... | 10ba33b415913b72dd46a9a367ebe0fcf377789a | 670,545 |
def getTau(z,density,xH,TS= 1):
"""
Given NumPy arrays for density, xH and TS calculate the corresponding
21cm optical depth in each cell
should extend later to allow for velocity field
"""
norm=0.009*pow(1+z,1.5)
tau=norm*(1+density)*xH/TS
return tau | 90ddc0b5357004d8072dc13e1a84fdb32c528d00 | 670,546 |
import os
def read(path):
"""read(path) -> str
Open file, return content.
Examples:
>>> read('pwnlib/util/misc.py').split('\\n')[0]
'import socket, re, os, stat, errno, string, base64'
"""
path = os.path.expanduser(os.path.expandvars(path))
with open(path) as fd:
retu... | cf0ae583a83ff8d267e5cc062e5ab08ee91df03e | 670,547 |
import numpy
def error(ilo, ihix, ihiy, dx, r):
""" calculates the L2 norm of elements in the residual """
e = numpy.sqrt(dx*dx*numpy.sum((r[ilo:ihix+1,ilo:ihiy+1]**2)))
return e | 3685abb0984109e930909e5935e9140351798e05 | 670,548 |
def set_of_words_2_vector(vocabulary_list, input_set):
"""
:param vocabulary_list: 词汇的列表
:param input_set: 某个文档
:return: 文档向量,向量的每一个元素为1或0,分别表示词汇表中的单词在输入文档中是否出现
"""
# 创建一个其中所含元素都为0的向量
return_vector = [0] * len(vocabulary_list)
for word in input_set:
... | 718eee002ecb1d21227bfa983a985a44252be8e4 | 670,549 |
import json
import sys
def format(content: bytes) -> str:
"""
传入的数据为utf-8格式的Json数据,将Json数据格式化为Html
:param content:
:return: 格式化后的Html
"""
jsonData = json.loads(str(content, 'utf-8'))
# 格式化被查询的单词
word = '''<p style="color: red; font-weight: bold">%s</p>'''%(sys.argv[1])
# 格式化音标 当翻译句... | 99f65bf3714beb969f0be6e1e00d31f7f29bc604 | 670,550 |
import re
def mask_as_regex(mask):
"""Return a regex object corresponding to the IRC hostmask pattern
string *mask*."""
pattern = ''
backslash = False # was the last character a backslash?
for char in mask:
if backslash:
# The RFC doesn't state this explicitly, but the provide... | 29165d3b41691353abf73779c3b745d0233be285 | 670,551 |
def flatten(nested):
"""
flattens a nested list
>>> flatten([['wer', 234, 'brdt5'], ['dfg'], [[21, 34,5], ['fhg', 4]]])
['wer', 234, 'brdt5', 'dfg', 21, 34, 5, 'fhg', 4]
"""
result = []
try:
# dont iterate over string-like objects:
try:
nested + ''
except(TypeError):
pass
else:... | 3634057e2dbae0ef98fd215cd810ff314667dc80 | 670,552 |
from typing import Tuple
from typing import Callable
import hashlib
from typing import Union
def _hash(
tpl: Tuple, hash_function: Callable = hashlib.sha1, as_int: bool = True
) -> Union[str, int]:
"""Deterministic hash function. The main use here is
providing a `commit_hash` for a Dataset to compare acro... | 35d52babd68f6b79b929fac2d9b113c599fc2ba7 | 670,553 |
def collect_src_frechet_files(py, search_directoy, output_directory):
"""
collect src_frechet files
"""
script = f"ibrun -n 1 {py} -m seisflow.scripts.source_inversion.collect_src_frechet --search_directoy {search_directoy} --output_directory {output_directory}; \n"
return script | 5c2dadcd6aa5291cc1888c8e3738eee0e0c59eb1 | 670,554 |
def fill_gaps(indicies, elementss, size, gap):
"""Fill gaps of arrays with size with indicies and elems."""
full = [None] * size
for ind, elem in zip(indicies, elementss):
full[ind] = elem
for ind in range(size):
if full[ind] is None:
full[ind] = gap()
return full | 366caaddc83cf76e8faa7e984b12464ec3e619bb | 670,555 |
def get_language(abrev):
"""
returns: the list of languages of a canton. The list is sorted by main language
"""
lang = {
'AG': ['D'],
'AR': ['D'],
'AI': ['D'],
'BL': ['D'],
'BS': ['D'],
'BE': ['D', 'FR'],
'FR': ['FR', 'D'] ,
'GE'... | b1e963198ac0a6ea6e9350cf54a34bfeb25e90b8 | 670,556 |
def BOSZ_filename(Teff, metallicity, log_g, res, carbon=0, alpha=0):
""" Generate filename for BOSZ spectrum. """
teff_str = f't{Teff:04.0f}'
logg_str = 'g{:02.0f}'.format(int(log_g*10))
metal_str = 'mp{:02.0f}'.format(int(abs(metallicity*10)+0.5))
# Metallicity [M/H]
if metallicity<0:
... | fdb6e4b649b4284639822ff905d95da77ad0007a | 670,557 |
def generate_sequence(lst: list[int]) -> list[int]:
"""Return a new list that contains the sequence of integers between the minimum and maximum of
lst, inclusive.
When the minimum and maximum of lst are the same, the list should only contain one element.
Assume that len(lst) >= 1.
>>> generate_se... | 86a84dfe0825550d2b227e29e9906cd361c592a4 | 670,558 |
def checkR(board, intX, intY, newX, newY):
"""Check if the rook move is legal, returns true if legal"""
tmp=False
count=1
if intX==newX:#Checks E and W
tmp=True
while count<9:
if intY<count<newY or newY<count<intY:
if board[count-1][intX-1]!='OO':
... | a7245021da22c24c5098437de553f4976bfd91f3 | 670,559 |
def equilibrium_check(accumulate, average, calls):
"""
Define stop conditions
"""
if average != 0:
vpA = abs(accumulate[0] - average) / average # Calculate A-Phase imbalance
vpB = abs(accumulate[1] - average) / average # Calculate B-Phase imbalance
vpC = abs(accumulate[2] -... | ef53bb6622065ebf754fe7ffef30de835dfb0fcc | 670,560 |
import math
def euclidean_distance(p, q):
""" Computes the distance between two points p and q.
"""
return math.sqrt((p[0] - q[0])**2 + (p[1] - q[1])**2) | 6e460743b8171e1ca8ca780e26c3b5e440dd4b79 | 670,561 |
def get_ranks_info():
"""
Return current MPI rank and number of ranks
None, None - if MPI environment is not available
:return: rank, max_rank
"""
rank = None
max_rank = None
try:
pass # removed in April 2020 since it was only used on Titan and is causing import errors
... | 5b3fe927f9c18201b860efd25d94b103c6853e57 | 670,562 |
import os
def path(*paths):
"""
计算目录及文件的绝对路径
"""
dir_name=os.path.dirname(os.path.realpath(__file__))
return os.path.abspath(os.path.join(dir_name,*paths)) | 5c85187d2f782c126a191a3b5e2c28f059e83f04 | 670,563 |
def get_func_name(func):
"""Get name of a function.
Parameters
----------
func: Function
The input function.
Returns
-------
name: str
The function name.
"""
return func.func_name if hasattr(func, "func_name") else func.__qualname__ | 8fc00a61378c21f469fc4f1c3d6b39251e87be8d | 670,564 |
import json
def format_json(data):
"""
格式化json
:param data:
:return:
"""
if isinstance(data, str):
data = json.loads(data)
return json.dumps(data, indent=4, ensure_ascii=False) | f34c26b4f259a732cf6bf735c1c02312800e7d1a | 670,565 |
def _normalize_image_id(image_id):
"""
The image IDs we get back from parsing "docker build" output are abbreviated to 12 hex digits.
In order to compare them to the ids we get from "docker.Client.images()" calls, we need to
normalize them
"""
if image_id is None:
return None
if ima... | 5f64666ab15273e3853f8978918effeab12c9c89 | 670,566 |
import torch
def mask_fill(
fill_value: float,
tokens: torch.Tensor,
embeddings: torch.Tensor,
padding_index: int,
) -> torch.Tensor:
"""
Function that masks embeddings representing padded elements.
:param fill_value: the value to fill the embeddings belonging to padded tokens.
:param... | e89e2a0f807765694ff68109b7d1a5adfec0297b | 670,567 |
def pbin(num):
"""
convert int to 8 characters binary string
which not contain '0b' in begin
"""
return bin(int(num))[2:].zfill(8) | 2ecfeab38509b3b971ab256f4cb30593147e6e26 | 670,568 |
import os
def GetPathToAsset(asset, search_paths):
"""Builds a list of (filename, asset) pairs from an asset file.
Args:
asset: string - a file to search for.
search_paths: list of strings - paths to search for asset files
Returns:
The full path to the found file, or None if it does not exist.
"... | 1992ba1ff15dffb78dfd8bd2ea5b3f41bcb1241f | 670,569 |
import math
def stats_collect(Mt_real, Mt_est, server, client, user_def):
"""The stats_collect function is responsible for collecting the data
on every migration that occurs. This data will be usefull determine the
effectiveness of the migration mechanisms used
:param Mt_real: Total time of migrati... | 9c0a79f3d3fb4d46203283c1929a6dab63b787db | 670,570 |
def _average(value_a: float, num_a: int, value_b: float, num_b: int) -> float:
"""Compute a weighted average of 2 values with associated numbers."""
divisor = num_a + num_b
if divisor == 0:
return 0
else:
return float(value_a * num_a + value_b * num_b) / divisor | c2326ae7e17c556abfd2de493707b88e528effbf | 670,571 |
def _bind_context(function):
"""
Lifts function from ``RequiresContext`` for better composition.
In other words, it modifies the function's
signature from: ``a -> RequiresContext[env, b]`` to:
``Container[env, a, c]`` -> ``Container[env, b, c]``
.. code:: python
>>> from returns.conte... | cb996756bb736937f0088834d826638474b56f1d | 670,572 |
import math
import numpy
def l2Norm_local(x):
"""
Compute the l_2 norm for just local (processor) system (not parallel)
"""
return math.sqrt(numpy.dot(x,x)) | 15e0ecc96c058ab72b2dc342d07a4dc7443b27d0 | 670,573 |
def average(lst):
"""
Calculates the average of a given list
:param lst: list of numbers
:return: average value
"""
return sum(lst) / len(lst) | aa84f1de98cca31d84ab0e3e2a77a22d46ad622f | 670,574 |
def _bti(bs):
"""Convert multibyte character literals in C enum to int value.
See 6.4.4.4 in C99 (TC3).
http://stackoverflow.com/a/548312/1376863
"""
rbs = reversed(bytearray(bs))
return sum(b * (2 ** (i * 8)) for b, i in zip(rbs, range(len(bs)))) | 4b7bbf782e11a23846e4277c356e64117fc97652 | 670,575 |
def _multihead_attention_output_shape( # pylint: disable=invalid-name
input_shapes, **unused_kwargs):
"""Helper: calculate multihead attention output shape."""
q_shape = input_shapes[0][0] # Inputs are ((q, k, v), mask).
mask_shape = input_shapes[1]
return q_shape, mask_shape | bcf5494a547dc3c0e5c8273187f27fb5c98eb1ca | 670,576 |
import os
def mtime(path):
"""shorthand for mtime"""
return os.stat(path).st_mtime | 1afa61aafb75d3c1c36a111530672ea48699ef07 | 670,577 |
import os
import subprocess
def _install_exe(src, dest):
"""Run the MSI installer to silently install the application into the
destination folder. Return the folder path.
Arguments:
src -- MSI installer to be executed
dest -- the path to install to
"""
# The installer doesn't automatical... | 9b75285fec8cc6d840583af3a72fd8f987ad12b2 | 670,578 |
def getChunks(dsets,nbchunks):
""" Splits dataset object into smaller chunks
Parameters:
* dsets (dict): dataset
* nbchunks (int): number of data chunks to be created
Returns:
* dict: chunks from dataset stored as dictionaries
"""
ret = []
for ichunk in range(nbchunks):
datagrp = {}
f... | d693ad68b142816b5d43bde37f01d757ced60298 | 670,579 |
def from_rgb(rgb):
"""translates an rgb tuple of int to a tkinter friendly color code
"""
r, g, b = rgb
return f'#{r:02x}{g:02x}{b:02x}' | 7bf6494dfc98b43912c2f44cf97801da86b21b1d | 670,580 |
def desvioPoisson(l, t):
"""
Cálcula o desvio padrão de uma distribuição
poisson
"""
return t*l | 2994c1e657df3c923f05907de7762df8c2b3597f | 670,581 |
def value_to_intervals(value, dict_valstoinv):
"""
根据字典对值返回对应的区间
e.g.
dict_valstoinv:{(-1, 100]: 0, (100, +Inf): 1}
value: 50
返回值(-1, 100]
PS:如果存在有重复匹配的区间, 则取第一个匹配上的
Parameters:
----------
value: number, 数值
dict_valstoinv: dict, 区间字典
Returns:
-------
数值对应的区间
... | 74983d068c363861b7ed75cef43811cf5f84b719 | 670,582 |
import struct
def parse_user(user_id):
"""
Repack user id into XX:XX:XX:XX formatted string
"""
user_bytes = [hex(x) for x in struct.unpack("4B", struct.pack("<I", user_id))]
return ':'.join(user_bytes).replace('0x', '') | f3c5bcc03c630a22e536622a5f9f73227048a59b | 670,583 |
from typing import Union
def make_string(seq: Union[bytes, list]) -> str:
"""
Don't throw an exception when given an out of range character.
"""
string = ''
for char in seq:
# Screen out non-printing characters
try:
if 32 <= char < 256:
string += chr(cha... | b860d96e513172b87327d3b2a01c6b0dbba2c6f3 | 670,584 |
import math
def printAngle(angle):
"""Generate angle line
Parameters
----------
angle : Angle Object
Angle Object
Returns
-------
angleLine : str
Angle line data
"""
k0 = angle.K0*8.3680
angle0 = math.radians(angle.angle0)
return '<Angle class1=\"%s\... | ce6f32021fb99faeb8a344e4da00cfab938658ce | 670,585 |
import torch
def validation(model, loader, criterion, device):
"""
model inference during training
Parameters:
model - model architecture, support : 'vgg16, 'resnet152', 'densenet161'
loader - dataloaders for e.g validloaders
criterion - deep learning criterion
... | f828ad85ce3b7f059b3cd50349b3b32fa39107ef | 670,586 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.