content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import jinja2
def render(path, variables={}):
"""Render the given template using the given variables."""
env = jinja2.Environment(
loader=jinja2.PackageLoader('gutenberg'),
trim_blocks=True,
lstrip_blocks=True)
template = env.get_template(path)
return template.render(variables... | a0f7fbe1a8165c99264ba93834df40077b6ba8b6 | 59,803 |
def list_sets_for_entry(nsets):
"""
Parameters
----------
nsets: List of integers, sets to select from
Returns
-------
str1: sring variable, the list of sets (for a simple dialog)
"""
str1 = '%d' % nsets[0]
if len(nsets) > 1:
for loop in range(1, len(nsets)):
... | 3cbc52dc13c7747d0641f60d34e97548141cea75 | 59,805 |
def Fname_data(Fpath):
""" takes both pulse data file names and h5 file names and returns UTC_time, station_name, Fpath"""
Fname = Fpath.split('/')[-1]
data = Fname.split('_')
timeID = data[1]
station_name = data[2]
if len(data[3][1:])==0:
file_number = 0
else:
file_numb... | 90940234e97a97a41b20f83de1f6160776a7f708 | 59,810 |
def __add_abcd_counts(x, y):
"""
Adds two tuples. For example.
:math:`x + y = (x_a + y_a, x_b + y_b, x_c + y_c, x_d + y_d)`
:param x: Tuple (a, b, c, d).
:param y: Tuple (a, b, c, d).
:return: Tuple (a, b, c, d).
"""
return x[0] + y[0], x[1] + y[1], x[2] + y[2], x[3] + y[3] | 9453058aae1e72c297ce6343ec80fcecaed76f74 | 59,814 |
def get_set_time(deadline: int):
"""Return time-step set:
T = {1,2...tau}, tau = deadline"""
T = list(range(1, deadline + 1))
return T | cb54ca541ebe65e7693794cbfc4190a217b951f9 | 59,816 |
def A_cells_um(nc, rho, A_c_rho1=800):
"""
Returns the area of `nc` cells at density `rho` in
micrometers^2.
`A_c_rho1` is the area of each cell at `rho=1` in
micrometers^2.
"""
return nc * A_c_rho1 / rho | db667cf9a72cf05a70d271c502b8d604feeef7d5 | 59,819 |
def GetZipPath(file, dir, dirname):
"""Given an absolute file path, an absolute directory path, and the dirname
of the directory, return a relative path to the file from the parent
directory of the given directory, with unix-style path separators.
"""
file = dirname + file[len(dir):]
return file... | 8fa0d97ae5668588329e84c0f9695b57567aa459 | 59,821 |
def word_count(phrase):
"""
given a phrase, count the occurrences of each word in that phrase
words comprise alphanumeric characters and are separated by anything else
"""
counts = {}
for word in ''.join(
map(lambda c: c.lower() if c.isalnum() else ' ', phrase)).split():
tr... | 94bc88eb158699391f85484ef2c40368ce929858 | 59,822 |
def n(T: float) -> float:
"""
T = 360° / T
:param T: translation period
:type T: float
:return: mean motion in degrees
:rtype: float
"""
return 360 / T | 0c52f9b82c8054dd4282ddb9cdc23f4fd53c636f | 59,823 |
def word_splitter(df):
"""returns pandas DataFrame with a new column 'Split Tweets' that contains
tweets as list of seperate words.
Args:
df (pandas(pd) DataFrame): pd.DataFrame object with atleast one column:
'Tweets': Contains strings (pd.Series objects) of individual tweets (one ... | c75939719d136b8a267d2e7039cfe5426e601022 | 59,824 |
def remove_suffix(s: str, suffix: str) -> str:
"""Remove `suffix` from the end of `s` if it exists."""
if suffix and s.endswith(suffix):
return s[:-len(suffix)]
return s[:] | b47d5e193ebb3b522dfc546ed264bb65b117a1b0 | 59,826 |
def remove_unnecessary(string):
"""Removes unnecessary symbols from a string and returns the string."""
string = string.replace('@?', '')
string = string.replace('?@', '')
return string | 56965ef4b60d302e659bafd4874b8c72790c5ec3 | 59,827 |
import sympy
def solve(eq, target, **kwargs):
"""
solve(expr, target, **kwargs)
Algebraically rearrange an equation w.r.t. a given symbol.
This is a wrapper around ``sympy.solve``.
:param eq: The :class:`sympy.Eq` to be rearranged.
:param target: The symbol w.r.t. which the equation is rear... | 9972338f0e967b343cc6ce2b8919e297ac7542d9 | 59,829 |
def downright(i,j,table):
"""Return the product to down-right-diagonal"""
product = 1
for num in range(4):
if i+num>19 or j+num>9: product*=1
else: product *= int(table[i+num][j+num])
return product | efa618d32892b3fb68217fd41907f5d874172ecf | 59,833 |
def affiche_etat(etat):
"""Retourne _etat_ avec des espaces entre chaque lettre
e.g.: "E_AN" => "E _ A N"
"""
return " ".join(etat) | da8ea70fcd9ac03fa5f6ee493fc934b81382f6a4 | 59,834 |
def get_movies_by_year(hs_movie, year):
"""
Showing the movies that released that year
Parameters:
hs_movie (dic): information about movies
year (int): The year that movie released
returns:
list: return
"""
if year in hs_movie:
return hs_movie[year]
else:
re... | c9ed75908105f061ad6a81f4e1c363ac7d39383f | 59,838 |
def crowded_comparison_operator(self, other, pareto):
"""
The crowded-comparison operator guides the selection process at the various
stages of the algorithm toward a uniformly spread-out Pareto-optimal front.
The operator returns True if *self* is better than *other* and
False otherwise.
:para... | 4e8667c1b2409a43f84b2a59cb0ea4acbebfeae3 | 59,841 |
from typing import Dict
from typing import Any
def _get_batchmm_opts(a_shape, a_strides, b_shape, b_strides, c_shape,
c_strides) -> Dict[str, Any]:
"""
Detects whether a matrix multiplication is a batched matrix multiplication
and returns its parameters (strides, batch size), or an e... | 29f50020b7b27a0e17984fdc127d55361dfaf28a | 59,844 |
def intervalOverlapCheck(
interval, cmprInterval, percentThreshold=0, timeThreshold=0, boundaryInclusive=False
):
"""
Checks whether two intervals overlap
Args:
interval (Interval):
cmprInterval (Interval):
percentThreshold (float): if percentThreshold is greater than 0, then
... | c129487dae826909d55ba7bdee4c8fc5a0edff69 | 59,845 |
def get_graph_names(accessor):
"""
given an instance of an accessor, get the configured graph names
"""
graph_documents = accessor.get_all_documents_from_collection("graph")
graph_names = [graph["title"] for graph in graph_documents]
return graph_names | 3f2555d49c30f7adae1ad9720572e2cf6b3943c4 | 59,852 |
def _seconds_to_time(seconds):
"""
Convert seconds into a time-string with the format HH:MM:SS. Seconds should
be an integer or float (rounded to nearest second and then cast to int).
"""
# Represent as integer
try:
if not type(seconds) is int:
seconds = int(round(seconds,0... | 275bdd2c11d7c4b92b880bbfc4ab6cd3916b67b0 | 59,853 |
def href_finder(soup_ele):
"""
Finds all a["href"] in beautifulSoup object
"""
return [a["href"] for a in soup_ele.findAll("a", href=True)] | 25de3093f07e58ba38037b213a0710eee062c9a2 | 59,854 |
import re
def remove_special(s):
"""Remove all special characters from the given string"""
return re.sub(r"[?|:*/\\<>\"]+", '', s) | 5db21e06ea74927120be73b87ef20868d561f413 | 59,857 |
def _detect(fun, seq):
"""Return the first element that satisfies the predicate fun."""
for item in seq:
if fun(item):
return item
return None | e6d6a4e87cbd696dbe3390ca31cbb267d716b9c5 | 59,859 |
from typing import Any
import importlib
def import_python_object_from_string(function_string: str) -> Any:
"""
Based on https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string
""" # pylint: disable=line-too-long
mod_name, func_name = function_string.rsplit("... | 924f4ce0dfcf5cf902f351b3a04545efbc535407 | 59,860 |
import math
def newmark_overpressure(energy_mttnt, radius_m):
"""
Newmark-Hansen Overpressure formula. Intended for surface blasts, but adapted to air-bursts.
:param energy_mttnt: Energy in Megatons TNT
:param radius_m: Actual distance from blast in m (hypotenuse distance for airburst events).
:r... | dff7fb6eb807772f035d40410088f715662eb65b | 59,864 |
def remove_prefix(text, prefix):
"""
Removes the prefix string from the text
Args:
text (str): The base string containing the prefixed string
prefix (str): Prefix to remove
Returns:
str: the base string with the prefix removed
"""
if text.startswith(prefix):
ret... | d29435dba6872c162dfbd0d9634ae65ef2d43619 | 59,870 |
def check_value(arr, shape, name=None):
"""
Check that the given argument has the expected shape. Shape dimensions can
be ints or -1 for a wildcard. The wildcard dimensions are returned, which
allows them to be used for subsequent validation or elsewhere in the
function.
Args:
arr (np.a... | 1adea9e8cb6d0db4976dd31335f6abaf53599efd | 59,874 |
def classify_attachments(files):
""" Return an (audio_files, related_docs) tuple. """
audio = []
related = []
for f in files:
if 'audio' in f['file_mime']:
audio.append(f)
else:
related.append(f)
return audio, related | 28f78c420cc2ac54823f69f6eb0e2f6f810c5f5c | 59,876 |
def _dohome_percent(value: int) -> float:
"""Convert dohome value (0-5000) to percent (0-1)."""
return value / 5000 | 8889c8af7240a919eed1f45143d2302e206ec9b7 | 59,877 |
def _iou(p1, p2):
"""Computes intersection over union of two intervals.
Args:
p1 ((int,int)): First interval as (first ts, last ts)
p2 ((int,int)): Second interval as (first ts, last ts)
Returns:
float: intersection over union of the two intervals.
"""
i_start = max(... | 2fbe75748a131ce2cfbfe7cee5a9fff300e617e1 | 59,882 |
import socket
def getfqdn4(name=None):
"""return (a) IPv4 FQDN (Fully Qualified Domain Name)
if name is not given, returns local hostname"""
if name is None:
return socket.getfqdn()
return socket.getfqdn(name) | e13a098bfaa9e1ca442adb8200c82dc558030f02 | 59,883 |
def two_gaussian_potential_bc(vnew, f2, coords):
"""
Apply Boundary Condition to the potential, force, and coordinates.
Parameters:
-----------
vnew : float (or array of floats)
Potential Energy
f2 : float (or array of floats)
Force
coords ... | 2d9eda2eb4db4a800f72f7b7eaf61c8508c5f848 | 59,885 |
def is_int_list(value):
"""Checks if a value's type is a list of integers."""
return value and isinstance(value, list) and isinstance(value[0], int) | 752ab515da58bccfb06d8f72cf0da43a909ce6db | 59,889 |
def get_sp_benchmarks(fmtstr):
"""
Return the list of input SinglePrefix benchmark files with their destinations.
Applies to SinglePrefix fatXPol, fatXMaintenance and spX benchmarks.
"""
common = [(4, 10), (8, 12), (10, 13), (12, 64), (16, 0), (20, 0)]
benches = [(fmtstr.format(sz), d) for (sz, ... | f2ce47b852f3abaa0099ce64ec68ca264eb73c75 | 59,890 |
def regex_result_escape_duplicate_quotes(result):
"""
Regex search handler: Escape sections where we find duplicate empty
quotes surrounding objects.
Args:
result (MatchObject): Match result from a previous regex match.
"""
return "{}\"{}\"".format(result.group(1), resul... | 3464559e514358e151a14dfa8d1a77109233ccfc | 59,895 |
def get_status_code(code):
"""
Table B-1.1 CIP General Status Codes
:param code: Code to get the Status from
:return: Status Message
"""
if code == 0x00: return 'Success'
elif code == 0x01: return 'Connection failure'
elif code == 0x02: return 'Resource unavailable'
elif code == 0x03... | 3622da583ae55785322828a6cd1ba7601d125ac9 | 59,897 |
def get_counts(df, field, save_path=None):
"""Get the topic counts by a particular field"""
counts_df = df[['#topic', field, 'doc']].copy()
counts = counts_df.groupby(['#topic', field]).count()
counts.rename(columns={'doc': 'Number of Docs'}, inplace=True)
counts = counts.unstack(fill_value=0)
... | fa988ad73b0014837c81f3e7dcf7443341e47697 | 59,898 |
def unique(sequence):
"""Return unique items in sequence, preserving order."""
# https://www.peterbe.com/plog/fastest-way-to-uniquify-a-list-in-python-3.6
return list(dict.fromkeys(sequence)) | 880cbcdadfb2c0214674c86afb357096abf5be47 | 59,899 |
def quotewrap(item):
"""wrap item in double quotes and return it.
item is a stringlike object"""
return '"' + item + '"' | 91acd54664b9408832b105a01b47165b53fdf4f5 | 59,900 |
import re
def MakeAlphaNum( str ):
"""Return a version of the argument string, in which all non-alphanumeric chars have been replaced
by underscores.
"""
return re.sub( '\W+', '_', str ) | d0eb0b4e4d7be0e592fa5517fa088dc10c1d455e | 59,902 |
def line() -> str:
"""
Add line md style.
:return: Formatted line in md style.
:rtype: str
"""
return f"---" | c406a2fa5ea8452b10c3826bc7ac24674ca2cdf5 | 59,916 |
def transform_subject_number(subject_number, loop_size):
"""
Args:
subject_number (int)
loop_size (int)
Returns:
int:
The resulting subject number.
"""
return pow(subject_number, loop_size, 20201227) | 13cb3bc0a5ef094e6578bf6f54b9e8a0854416d2 | 59,920 |
def is_action_execution_under_action_chain_context(liveaction):
"""
The action execution is executed under action-chain context
if it contains the chain key in its context dictionary.
"""
return liveaction.context and "chain" in liveaction.context | eca64bd25ecf8cfd6e1232e36084262f674e1dbd | 59,927 |
def make_kernel_names(kern_list):
"""
Take a list of kernels and return a list of strings, giving each kernel a
unique name.
Each name is made from the lower-case version of the kernel's class name.
Duplicate kernels are given training numbers.
"""
names = []
counting_dict = {}
for... | 97c589ea271d110e2578d82182d198a52773bc6e | 59,930 |
def sign(n):
""" Returns -1 if n is negative, 1 if n is positive, and 0 otherwise. """
if n > 0:
return 1
elif n < 0:
return -1
else:
return 0 | de619f0ac36ffb963b37fb46b4da262b3f8a535c | 59,938 |
import re
def extract_title(textbody):
"""
Returns the title of the .tex file, assuming that the
title is set in \title{TITLE}. Otherwise, returns "TITLE"
"""
title_re = re.compile(r"^\s*\\title{([^}]*)}", re.MULTILINE)
title = title_re.findall(textbody)
if title:
return title[0]
... | 0e1055c8644823e0edfd4bfb22a1d3dcc2428570 | 59,940 |
def linear_variability(csr, var_frac):
"""Return an array with a linear relation between clearsky ratio and
maximum variability fraction. Each value in the array is the maximum
variability fraction for the corresponding clearsky ratio.
Parameters
----------
csr : np.ndarray
REST2 clears... | 2dcb8f87fa0782b751e4697a6da024aa3103b0f2 | 59,941 |
def get_paths_threshold(plist, decreasing_factor):
"""
Get end attributes cutting threshold
Parameters
----------
plist
List of paths ordered by number of occurrences
decreasing_factor
Decreasing factor of the algorithm
Returns
---------
threshold
Paths cutt... | d25624ddfde6505ec6e26de12feb8c33a2eb5bf2 | 59,943 |
import shutil
from pathlib import Path
def get_tc_exec(command):
"""Returns the location of the RDAAM_He or ketch_aft executable"""
if shutil.which(command) is not None:
tc_exec = command
elif Path("bin/" + command).is_file():
tc_exec = "bin/" + command
else:
raise FileNotFound... | e9d4a75781bf8aee9f98ab94a59f48cae9eeb0a6 | 59,944 |
def get_image_format(filename):
"""Returns image format from filename."""
filename = filename.lower()
if filename.endswith('jpeg') or filename.endswith('jpg'):
return 'jpeg'
elif filename.endswith('png'):
return 'png'
else:
raise ValueError('Unrecognized file format: %s' % filename) | e003474275607e56f011a6410aeb4a9dfd7adcbd | 59,945 |
def pd_columns_to_string(df):
""" Returns a single string with a list of columns, eg: 'col1', 'col2', 'col3' """
columns = "".join("'" + column + "', " for column in df.columns)
return columns[:-2] | 57b2a24d8a0f88fcd465928465f32dc358c1a020 | 59,946 |
def split_commas(ctx, param, value):
"""
Convert from a comma-separated list to a true list.
"""
# ctx, param, value is the required calling signature for a Click callback
try:
values = value.split(',')
except AttributeError:
# values is None
values = None
return va... | 8aeb193ef83abf3d328988b07a7f014f6b5b2179 | 59,950 |
def _apply_prefix(prefix, model):
"""
Prefix all path entries in model with the given prefix.
"""
if not isinstance(model, dict):
raise TypeError("Expected dict for model, got %s" % type(model))
# We get unwanted leading/trailing slashes if prefix or model['path'] are
# '', both of whic... | 5560247061c7827990c8a8496023e70c385ec7ef | 59,952 |
def computeDerivatives(oldEntry, newEntry):
"""
Computes first-order derivatives between two corresponding sets of metrics
:param oldEntry: Dictionary of metrics at time t - 1
:param newEntry: Dictionary of metrics at time t
:return: Dictionary of first-order derivatives
"""
diff = {k: v - ... | 1f4f2fe17cebc98e5f136f2a68b9b5c772367f40 | 59,953 |
def float_to_python(self, value):
"""
Convert a 'float' field from solr's xml format to python and return it.
"""
return float(value) | 74bc65259288261c47f0168c586b1bff7a7ae615 | 59,958 |
def exec_file(path):
"""Execute a python file and return the `globals` dictionary."""
namespace = {}
with open(path, 'rb') as f:
exec(f.read(), namespace, namespace)
return namespace | 9567a7c5c98a1cc9e71b8fdc563377dd89d68278 | 59,959 |
def _gt_get_all_nodes(self):
"""
Get all the nodes in this tree
"""
return self.tree.get_all_nodes() | 92793d01b0f4a0c347a7e5a717d3bf760b27288b | 59,960 |
def delete_old_account_key(self) -> bool:
"""Delete old account key from Cloud Portal.
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - spPortal
- DELETE
- /spPortal/account/oldKey
Acts as "commit" for a previous a... | d2510744c28d586aa31046c371fbd55f75d69074 | 59,969 |
def fixture_old_tool_version() -> str:
"""Return an old version of an existing tool"""
_old = "3.1"
return _old | 809e6fd91b35bc3ffa989312dc8c7f5785d4f8c2 | 59,972 |
from typing import Callable
def make_f(flavor: int) -> Callable[[int], int]:
"""Return a 1-bit constant or balanced function f. 4 flavors."""
# The 4 versions are:
# f(0) -> 0, f(1) -> 0 constant
# f(0) -> 0, f(1) -> 1 balanced
# f(0) -> 1, f(1) -> 0 balanced
# f(0) -> 1, f(1) -> 1 consta... | c51d9ea7748550ef41ab2d49385f678bbebf5c8d | 59,974 |
import math
def get_board_size(game_board):
"""(str) -> int
Precondition: board_size is a perfect square
Return the side length of the tic tac toe board
>>>get_board_size('x-ox')
2
>>>get_board_size('xoxoxxoxx')
3
"""
return int(math.sqrt(len(game_board))) | 5f60832686654d5fc788d9dcf0154de561f1ecb6 | 59,975 |
from datetime import datetime
def float2timestamp(float_timestamp):
"""Converts POSIX timestamp to datetime.datetime object."""
return datetime.fromtimestamp(float_timestamp) | fd62b0a1a4f4b71acf86db9d3f9d849c339f87a4 | 59,982 |
def get_identifiers(code_string):
"""
Return all valid identifiers found in the C++ code string by finding
uninterrupted strings that start with a character or an underscore and
continues with characters, underscores or digits. Any spaces, tabs,
newlines, paranthesis, punctuations or newlines will m... | b1a22a5218caab57a4c2541acd18ba9027a477d4 | 59,984 |
def get_existing_boundary_indices(mesh):
"""
Returns
----------
list, int.
The boundary indices (data['boundary']>0) that exist on the mesh vertices.
"""
indices = []
for vkey, data in mesh.vertices(data=True):
if data['boundary'] > 0:
if data['boundary'] not ... | 0ba24f8d8f4b2cf36cc16c2d810145e41ac3c229 | 59,989 |
def index_to_voxel(index, Y_size, Z_size):
"""
index to voxel, eg. 0 -> (0,0,0).
"""
i = index % (Y_size)
index = index // (Y_size)
j = index % (Z_size)
index = index // (Z_size)
k = index
return (i, j, k) | f61bea14bec11b0faae15bb119b14fc116953d54 | 59,993 |
def get_fk_from_field(m, f_name, f_value):
"""Read an object to be used as foreign key in another record.
It return a formatted message if it finds an error
"""
msg = ""
try:
obj = m.objects.get(**{f_name: f_value})
except m.DoesNotExist:
msg = f'{f_name} "{f_value}"'
ob... | 97c5898702f023e8634457127029df4d38aa708c | 59,995 |
def get_input_layer_variables(ann, variables, descriptors):
"""
Given a list of descriptor names and a tuple of
variables of the MILP_Relu model,
create and return a dictionary that for each descriptor
gives the corresponding variable
"""
# unpack the variables
x, y, z = variables
# ... | a9767e348adc9d396c949867cec0f58ac8893226 | 59,996 |
def makeiter(var):
"""Converts a variable into a list of it's not already an iterable (not including strings.
If it's already an iterable, don't do anything to it.
Parameters
------------
var
the variable to check.
Returns
------------
var
an iterable version of the par... | f2259d918e9e1b150d59bca9b6c1351b3daea8b9 | 60,000 |
from pathlib import Path
def data_to_dir(data_dir):
"""Ensures that the procided data destination is valid."""
data_dir = Path(data_dir)
if data_dir.is_dir():
is_empty = not any(data_dir.iterdir())
if is_empty:
return data_dir
else:
raise FileExistsError(
... | 35b85f0e5cf5693beeb1aacd56018b0229279229 | 60,002 |
def normalize_bcast_dims(*shapes):
"""
Normalize the lengths of the input shapes to have the same length.
The shapes are padded at the front by 1 to make the lengths equal.
"""
maxlens = max([len(shape) for shape in shapes])
res = [[1] * (maxlens - len(shape)) + list(shape) for shape in shapes]
... | 64776b52dd6ddcc226eb6db8a8373765d5637f88 | 60,004 |
import csv
def getListOfJiraUsersFromCsv(jiraUsersToSearchFor="jira_users.csv"):
"""
Gets list of jira users expected to find.
The csv should contain their name in the format "FIRSTNAME LASTNAME"
and the type "STUDENT" or "ADMIN".
Expects first row to be a header so ignores it.
Ignores blank l... | 17d34848ca56d7631d5dcb1544425f4b0e372007 | 60,007 |
import torch
from typing import Union
from typing import Type
from typing import Tuple
def count_module_instances(module: torch.nn.Module, module_class: Union[Type[torch.nn.Module],
Tuple[Type[torch.nn.Module], ...]]) -> int:
"""Counts the nu... | a991db4d1ac7d916c36fdbd993e28a31e858d62f | 60,008 |
import random
def random_indexes(a, b, feats_in_plot):
"""Support function for tSNE_vis
Args:
a: start index
b: end index
feats_in_plot: # of featuers to be plotted per class
Returns:
Random list of feats_in_plot indexes between a and b
"""
randomList = []
# Set... | 2fad244becdc378dc3cc36ccc786634c7ec0d832 | 60,013 |
def copy_node(node):
"""Makes a copy of a node with the same attributes and text, but no children."""
element = node.makeelement(node.tag)
element.text = node.text
element.tail = node.tail
for key, value in node.items():
element.set(key, value)
return element | 179cc1277c3e5a9b41fdd6ec6392273c8a3c4c64 | 60,021 |
import base64
def _base64(text):
"""Encodes string as base64 as specified in the ACME RFC."""
return base64.urlsafe_b64encode(text).decode("utf8").rstrip("=") | a52dd0a05d00f71b9246d59320cb709ac9f53236 | 60,024 |
import time
import json
import base64
def parse_scitoken(token_string: str):
"""Parse a scitoken string and return the header, payload, and signature
:param token_string: A scitoken as 3 '.'-separated base64 strings
:return: header (dict), payload (dict), signature (str)
:raises: ValueError if there i... | ba34d0416e355821ac3f321f2ea729d7ff5460dd | 60,034 |
def _get_reference_bodyreference(referencebody_element):
"""Parse ReferenceInput BodyReference element
"""
return referencebody_element.attrib.get(
'{http://www.w3.org/1999/xlink}href', '') | c0baeec99e3d9d4a54f17a721d00202e214defcc | 60,038 |
import torch
def to_original_tensor(sorted_tensor, sorted_idx, sort_dim, device):
"""
Restore tensor to its original order.
This is used after applying pad_packed_sequence.
:param sorted_tensor: a sorted tensor
:param sorted_idx: sorted index of the sorted_tensor
:param sort_dim: the dimension... | 80308e9ef98060ab72f90b27cd4949a103b136f6 | 60,040 |
def host_and_port(host_or_port):
"""
Return full hostname/IP + port, possible input formats are:
* host:port -> host:port
* : -> localhost:4200
* :port -> localhost:port
* host -> host:4200
"""
if ':' in host_or_port:
if len(host_or_port) == 1:
... | f31df10657f0eba0a40ca3de5fd43006944501bb | 60,046 |
def last(coll):
"""
Return the last item in ``coll``, in linear time.
"""
e = None
for item in coll:
e = item
return e | e4b7ba628bf7fe1cf68ed208dd14aa431aa08b6d | 60,050 |
from typing import Dict
def _parse_schemata_file_row(line: str) -> Dict[str, str]:
"""Parse RDTAllocation.l3 and RDTAllocation.mb strings based on
https://github.com/torvalds/linux/blob/9cf6b756cdf2cd38b8b0dac2567f7c6daf5e79d5/arch/x86/kernel/cpu/resctrl/ctrlmondata.c#L254
and return dict mapping and doma... | 359672902330e30c8b188f6565b4242f8730ecea | 60,053 |
def force_str_length(string, length):
"""Truncates and/or pads a string to be a specific length"""
string = str(string)
while len(string) < length:
string += " "
return string[0:length] | 352560d6fb60e21968f556c96ba357ac84e60aa7 | 60,055 |
def value2str(value):
"""
format a parameter value to string to be inserted into a workflow
Parameters
----------
value: bool, int, float, list
Returns
-------
str
the string representation of the value
"""
if isinstance(value, bool):
strval = str(value).low... | af94778f70b08f696007bcb42713b35d4d786525 | 60,056 |
def get_family_from(hmm_filepath):
"""Get family name from the name of an individual family hmm filename.
Args:
hmm_filepath: string. Of the form '~/family_name'.hmm, like
hmm_files/PF00001.21.hmm.
Returns:
string. Family name.
"""
hmm_filename = hmm_filepath.split('/')[-1]
return '.'.join(h... | 93ae5f3f7da6d987daaedc45a869c8fc40c5eb3d | 60,058 |
def run_queue_analysis(trace, threshold):
"""
Plot the queuing delay distribution and
severely delayed tasks.
:param trace: input Trace object
:type trace: :mod:`libs.utils.Trace`
:param threshold: plot transactions taken longer than threshold
:type threshold: int
"""
df = trace.da... | aa61892ccf21a2fe4b962630d2c0f4401a3754ef | 60,062 |
def read_file(filename):
"""
Returns content of file provided
:param filename: filename to read
:return: content of the file
"""
with open(filename) as f:
content = f.readlines()
f.close()
return ''.join([l.strip() for l in content]) | fe34f14a9022c44d6da191cf1720ba8f0358c168 | 60,063 |
def fail_suffix(i):
"""Filename suffix for the ith failing file"""
if i == 0:
return '_fail'
else:
return '_fail_' + str(i+1) | 4b4c5344bf510a2c167ced57c78e47ad79f1da7e | 60,068 |
from typing import Tuple
def split_key(ivkey: str) -> Tuple[str, str]:
"""Split IV and key."""
iv = ivkey[:32]
key = ivkey[-64:]
return iv, key | eb5f02b8441aed55d330680450d619c0e1840693 | 60,069 |
def delete_user(connection, id):
"""Delete user for specific user id.
Args:
connection(object): MicroStrategy connection object returned by
`connection.Connection()`.
id(string): User ID.
Returns:
HTTP response object returned by the MicroStrategy REST server.
"""
... | 7a4433c775a4cf233f436bd85c40978a17b75309 | 60,070 |
def ParseBool(value):
"""Parse a string representation into a True/False value."""
if value is None:
return None
value_lower = value.lower()
if value_lower in ('true', '1'):
return True
elif value_lower in ('false', '0'):
return False
else:
raise ValueError(value) | 2bac384894e29aaaba4bee42207d89db11b1badf | 60,073 |
import time
def get_time() -> float:
"""Return time in ms"""
return time.perf_counter() * 1000 | e4a63e14b1107c5ac00279019bd1f1623a3a75cc | 60,074 |
import torch
def pseudo_huber_loss(truth, pred, scale=2.0):
"""Pseudo-Huber loss used in StereoNet.
Described in 2019 Barron - A General and Adaptive Robust Loss Function.
"""
diff2 = ((pred - truth) / scale)**2
loss = torch.mean(torch.sqrt(diff2 + 1.0) - 1.0)
return loss | 4fc533599d10925f270895df1c1e3b8a51a42ed7 | 60,080 |
def make_param_name_single_index(param_parts):
"""
Make the key name from param parts.
For example, ("param", "tag", "1") -> ("param", "1").
"""
return (param_parts[0], param_parts[-1]) | e38d49c93b7cc0f1306839d9fbff4eefce808433 | 60,082 |
def parse_sample_value_map(arguments, samples, default, sample_map, type):
"""Combine arguments specified for a default value and sample-value map file.
Parameters
----------
arguments
Parsed arguments containing some the default value argument
and the optionally the sample-value map fi... | 2e4639f27cc2b47164389dc2085c932792d24f58 | 60,086 |
def tile_bonds(bonds, reps, num_solvent_atoms):
"""
Like the Numpy tile function, tile the bonds array.
The Numpy tile function cannot be used because the
values in the bonds array need to be incremented by
the number of atoms in the solvent molecules.
bonds : Psi-OMM Bonds array
The b... | 57251fd5f543a1b270422d214305596765289f1b | 60,090 |
def strings_AND_bitwise(string1, string2):
"""Returns the bitwise AND of two equal length bit strings.
Parameters
----------
string1 : str
First string
string2 : str
Second string
Returns
-------
string_out : str
bitwise AND of the two input strings
... | 1fb83f15d0b086914667555b5e150e7697792f53 | 60,092 |
from pathlib import Path
import re
def get_decoder_id(decoder_dir):
"""
Get information about a learned decoder from its output directory name.
"""
decoder_dir = decoder_dir.name if isinstance(decoder_dir, Path) else decoder_dir
model, run, step, subject = re.findall("^([\w_]+)-(\d+)-(\d+)-([\w\d]... | 48ca1ac7cc5076618ba2c76308813a914e4f3bbd | 60,096 |
from typing import Tuple
import itertools
def part1(values: Tuple[int, ...]) -> int:
""" Identify a value which is not the sum of the 25 preceding values, and return it """
for i in range(len(values) - 25):
target = values[i + 25]
for j, k in itertools.product(range(i, i + 25), range(i, i + 25... | 280ec40df37b76e9957ef92280eaa577d47030ee | 60,097 |
import re
def first_char_index(lines, regex):
"""Get the index of the first position for a description character
Use this to find where the first character after the : should be placed so
that each comment can line up.
:param lines: list of strings to find the index for
:param regex: Regex to id... | e31794f46f67f79008e761267b42c6766b5dd370 | 60,098 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.