content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def gen_key_refId(dashboardId, panelId, refId):
"""generate the key for finding the right sqlClient object,
using the given (dashboard, panel, sql-id)"""
return "-".join([str(dashboardId), str(panelId), refId]) | 203da05cd8b97f0cb34863b7bd2841113e964705 | 624,106 |
import itertools
def fock_bin(n, k):
"""
Return all the possible :math:`n`-length binary where :math:`k` of :math:`n` digitals are set to 1.
Parameters
----------
n : int
Binary length :math:`n`.
k : int
How many digitals are set to be 1.
Returns
-------
res :... | 00a5ce67e63ca4a58736764de687b744627f4205 | 624,107 |
def make_mysql_url(username: str, password: str, dbname: str,
driver: str = "mysqldb", host: str = "localhost",
port: int = 3306, charset: str = "utf8") -> str:
"""
Makes an SQLAlchemy URL for a MySQL database.
"""
return "mysql+{driver}://{u}:{p}@{host}:{port}/{db}... | cf14fa7582b8242c49964465a37681f5523a1975 | 624,111 |
from typing import Counter
def get_duplicates(song_list):
"""Finds all duplicates in a list.
Args:
song_list: A list of "song by artist" strings which is the
return list of find_similar_songs.
Returns:
A list of all items found more than once in the input list.
"""
duplic... | 002d6f622aecb52c1c90c86d3aaa6f4e464447fd | 624,112 |
def get_attributes(obj, names):
"""Return attributes dictionary with keys from `names`.
Object is queried for each attribute name, if it doesn't have this
attribute, default value None will be returned.
>>> class Class:
... pass
>>> obj = Class()
>>> obj.attr = True
>>> obj.value =... | 603a0411e6ac2d602343306234e0a71fbb3b2f9a | 624,116 |
def create_list_attr_operation(var_attribute_list_name):
"""Return request string for a single operation to create an attribute of type array/list."""
return '{"op":"CreateAttributeValueList","attributeName":"' + var_attribute_list_name + '"},' | 9b8493725efbd4fe008527583300605b6fe19e25 | 624,119 |
def get_value_str(value, type_val):
"""Convert the value from the csv file to the correct str according to the type
Parameters
----------
value : str
value to convert
type_val : str
Type to convert to
Returns
-------
value : str
Value updated to match the type
... | d07d97800dcf5b4ffdf9f87078eaff90092055ef | 624,120 |
from typing import Counter
def count_ngrams(text, n):
"""
:param text: text
:param n: n of n-gram
:return: Counter objects for n-grams in the text
"""
ngrams = [text[i:i + n] for i in range(len(text) - n)]
return Counter(ngrams) | dd68a0c1934acce5358363221d36c86eee3c1ba7 | 624,121 |
from datetime import datetime
def format_generated_timestamp(dt: datetime) -> str:
"""Return standard phrase for the date and time the report is generated"""
dt_as_text = dt.astimezone().strftime('%c %Z')
return f"generated on {dt_as_text}" | 44d09036b1fa5a0e297661aed1f9c5d46745a23a | 624,122 |
def remove_header_lines(lines):
"""Return list of lines without the header."""
lines = lines[2:]
if lines and lines[0] == "\n":
lines = lines[1:]
return lines | a649e15054522b2f938349a269cefa04055fcc1c | 624,123 |
def get_digits(s):
"""
Get digits in the given string, cast to int
:param s: input string
:return: int from string
"""
return int(''.join([c for c in s if c.isdigit()])) | d02b0488f92e2ff159dd31a39248274cd927d13f | 624,124 |
def concat_strings(string_list):
"""
Concatenate all the strings in possibly-nested string_list.
@param list[str]|str string_list: string(s) to concatenate
@rtype: str
>>> list_ = 'cat'
>>> concat_strings(list_)
'cat'
>>> list_ = ['cat', 'dog']
>>> concat_strings(list_)
'catdog... | 32a029bf79f67c3b737cbd8f1f1656781f6eeefd | 624,125 |
from typing import List
def pad_tokens(tokens: List[List[int]], pad_value: int = 0) -> List[List[int]]:
"""pad a batch of tokens to fixed maximum lengh using `pad_value`.
Args:
tokens: list of list of tokens of varying lengths.
pad_value: padding value. Defaults to 0.
Example:
>>... | fe4d4954236063943d8c4131f654518f38751908 | 624,128 |
def is_url(checkpoint):
"""Check whether the checkpoint is a url or not.
"""
is_url = ('https://storage.googleapis.com' in checkpoint)
return is_url | 988e22920de0cd5a1bcf7543261d17fefabf6c29 | 624,129 |
from typing import List
from typing import Dict
from typing import Any
import copy
def create_lookup_table(
list_of_dicts: List[Dict[str, Any]], lookup_key
) -> Dict[str, List[Any]]:
""" Takes a list of dictionaries and converts it into a dictionary of dictionaries indexed by a specified key"""
payload =... | b2210ec470120ee804d133bf7b62e68ea7145eba | 624,133 |
import typing
def get_owner_and_repo(location: str) -> typing.Tuple[str, str]:
"""
Get the owner and repo name from a location string.
Parameters
----------
location : str
The location string.
Returns
-------
owner : str
The owner of the repo.
repo : str
T... | f6a71200a195d75a58ef26574b77a4b3fdb7614e | 624,134 |
def remove_invalid(string: str) -> str:
"""
Removes characters that Windows doesn't allow in filenames from the specified string
:param s: string to remove characters from
:return: the given string without invalid characters
"""
string = string.replace('"', "'")
for invalid_char in ["\\", "/... | afb86470a913d0ed3959d16e6f3248071fbe6da9 | 624,136 |
def extract_pathnames_from_log(filename, prefix_filter=""):
"""
Returns a list of pathnames from a GEOS-Chem log file.
This can be used to get a list of files that should be
downloaded from gcgrid or from Amazon S3.
Args:
-----
filename : str
GEOS-Chem standard log file
... | b31151e067f2092d17dbce84222194b1c6cea82f | 624,138 |
def _parse_table_cell(col, x):
"""
Parse 1 table cell. If col is 0, left margin - 1 should be kept for hierarchical data.
:param col: col index
:param x: data in cell
:return: int, float or str
"""
try:
return int(x)
except ValueError:
pass
try:
return float(x... | 3d62054d08122bf7a49b05b94f9f01ef8fce10b0 | 624,144 |
from typing import Iterable
from typing import Any
from typing import Tuple
import itertools
def pairwise(iterable: Iterable[Any],
zip_function=itertools.zip_longest, **kwargs) -> Iterable[Tuple[Any, Any]]:
"""s -> (s0,s1), (s1,s2), (s2, s3), ...
Args:
iterable: Iterable to iterate over ... | 31eaaff7436e88d9915a1e2be29271f3dfc7f031 | 624,146 |
def feats_at_batch(stensor, batch_id):
"""get features of sparse tensor at batch id
Args:
- tensor (Sparse Tensor)
- batch_id (int)
Returns:
- (Tensor)
"""
mask = stensor.indices[:, 0] == batch_id
return stensor.features[mask] | 9f4e1788b97759763567db3672ac3b85b170b65b | 624,147 |
def remove_comment_lines(a):
"""Return a copy of array with comments removed.
Lines starting with '--' (but not with '---') are removed.
"""
r = []
for s in a:
if s.strip().startswith('--') and not s.strip().startswith('---'):
pass
else:
r.append(s)
retur... | 587b208857a4f676c002802ac136eba90e4bde47 | 624,148 |
def get_event_id(reading_path):
"""
Returns events ids from specified REA file
:param reading_path: path to REA file
:return: event ID
"""
with open(reading_path) as file:
for line in file:
line = line.strip()
if len(line) > 73:
title = line[0:6]
... | 6ce15547fcdd0d8e278f04b9afbfee6dedf25170 | 624,151 |
def base_lm(hparams):
"""Adds base hparams for LM."""
# Language model.
hparams.add_hparam("lm_type", "left2right")
hparams.add_hparam("lm_num_layers", 2)
hparams.add_hparam("lm_num_residual_layers", 1)
# Language model training and loss.
hparams.add_hparam("lm_do_train", False)
hparams.add_hparam("lm... | 9bae4465d70b9e3abb8f732e35be8419ccb4f149 | 624,152 |
def _safe_get(obj, key, default=None):
"""This acts like obj.get(key, default), except that if obj[key] exists but
is None, we still return default rather than the accessed result. Also, if
obj happens to be None, we return default rather than raising an exception.
To see the difference, suppose obj = ... | 1b8c0a5c85c920371473ac46b0ca0a24453fe3e6 | 624,156 |
def edit_distance(word1, word2, sequence_type, max_distance = None):
"""Returns the Levenshtein edit distance between a string from
two words word1 and word2, code drawn from
http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python.
The number is the number of operations... | 0b1fc3ee6469519b8c84d9c09e89c92bdc654313 | 624,161 |
def is_comment(line: str) -> bool:
"""
Return True if the given line is a comment, False otherwise.
"""
return line.startswith('#') | 5488c414268d5f87ce916b08aa4cdb45482141cb | 624,162 |
import torch
def compute_numeric_gradient(f, x, dLdf=None, h=1e-7):
"""
Compute the numeric gradient of f at x using a finite differences
approximation. We use the centered difference:
df f(x + h) - f(x - h)
-- ~= -------------------
dx 2 * h
Function can also expand this ea... | 998d9d5b160729f0c76213ee1a560e167fc6d60a | 624,169 |
def find_similar_chars_n(str1, str2):
"""Returns a string containing only the characters found in both strings
Complexity: O(N)
"""
return ''.join(sorted([char1 for char1 in str1 if char1 in str2])) | 38587683e2316af90e6bef5989aec00ab803230a | 624,171 |
def Btu_lbR2Wh_kgK(x): # By mass
"""Btu/(lbm-R) -> Wh/(kg-K)"""
return 1.1632*x | ee410de5f03864a1beeeb572dfd4b483469d0b05 | 624,173 |
def get_all_predecessors(graph, node, start_node=0):
"""
Find all predecessor nodes of node in graph, given the
start_node.
Parameters
----------
graph: nx.DiGraph
node: abc.hashable
start_node: abc.hashable
"""
predecessors = [node]
while True:
pre_node = list(graph... | 8f66f46a05ee54e5e5706a215e55a24890fa399a | 624,176 |
def kelvin2celsius(kelvin):
"""
Convert temperature in degrees Kelvin to degrees Celsius.
:param kelvin: Degrees Kelvin
:return: Degrees Celsius
:rtype: float
"""
return kelvin - 273.15 | 1e1b73fb754eb41d3ca4cbfb623450740e470d7d | 624,180 |
import hashlib
import click
def calculate_file_md5(filepath, blocksize=2 ** 20):
"""Calculate an MD5 hash for a file."""
checksum = hashlib.md5()
with click.open_file(filepath, "rb") as f:
def update_chunk():
"""Add chunk to checksum."""
buf = f.read(blocksize)
... | fd1b5f771d899839650ada94b8d837c964043147 | 624,183 |
import json
def pretty(event):
"""Prettify an event for printing.
:param event: Dictionary of Eiffel event.
:type event: dict
:return: Preffy json string.
:rtype: str
"""
return json.dumps(event, indent=4, sort_keys=True) | 2e313396e55573b1d4a70a9545fcaf1b22de215e | 624,184 |
def payoff_lotto(x, y):
"""
Returns tuple of normalized (sum == 1) values of (losses, draws, wins).
"""
losses, draws, wins = 0, 0, 0
for x_i in x:
for y_i in y:
if x_i < y_i:
losses += 1
elif x_i == y_i:
draws += 1
else:
... | 20c6fc83e773fdbfce94efa8c87b120dc2d64c1b | 624,188 |
def subtract_one(n):
"""Subtracts 1 from n
>>> subtract_one(5)
4
>>> subtract_one(3)
2
"""
return n-1 | 7135c77df506df53c370e0ffc66bb708f7d5f58c | 624,190 |
def agwEnglishPlural(string, numOf, suffix="s"):
"""You pass in a string like "squid" and a number
indicating how many squid there are. If the number
is one, then "squid" is returned, otherwise "squids"
is returned."""
if 1 == numOf:
return string
else:
return string + suffix
... | bb98657247dbe099eeb8525a29796fa733f68f71 | 624,191 |
def nist_num(nist_data):
"""Converts a NIST style data point to a point.
Parameters
----------
nist_data : str
A nist data point.
Returns
-------
d : float or complex
a data point.
"""
nd = nist_data
while ('(' in nd) or (')' in nd):
nd_pre = nd.partiti... | a1adcff9bad746925e1233ad46e19e7dfa8670bb | 624,193 |
import torch
import math
def rgb2hsv(rgb):
"""Convert a 4-d RGB tensor to the HSV counterpart.
Here, we compute hue using atan2() based on the definition in [1],
instead of using the common lookup table approach as in [2, 3].
Those values agree when the angle is a multiple of 30°,
otherwise they m... | fce985d4d7423678d12aa29b0f3a54379855f7c2 | 624,194 |
def merge_dicts(x, y):
"""A function to merge two dictionaries, making it easier for us to make modality specific queries
for dwi images (since they have variable extensions due to having an nii.gz, bval, and bvec file)
Parameters
----------
x : dict
dictionary you want merged with y
... | e6ce777b3fcfebb33b56b685d695a13d549c039e | 624,200 |
import locale
def cell_format(data):
"""Formats the data to put in a table cell."""
if isinstance(data, int):
# Add commas to integers.
return locale.format_string("%d", data, grouping=True)
elif isinstance(data, float):
# Add commas to floats, and round to 2 decimal places.
... | a91b1a6e14918d19f6100e25fa830ce005c51e1a | 624,202 |
def get_lock_status_flags(lock_status_value):
"""
Decode a lock status value provided as a hex string (like '0880'),
returning an array of strings representing the parsed bits into
textual described flags.
"""
flags = []
try:
status_value = bytearray.fromhex(lock_status_value)
if not status_value:... | a58b57b4ca26f1c5e5ae0ba7e832b76664d29990 | 624,203 |
def follows(trace, distance=1):
"""Returns a mapping (aka. dict) from pairs of activities to frequency.
A pair (a, b) is part of the mapping if activity b directly follows activity a,
in any of the traces.
Parameters
----------
distance: int
Distance two activities have to be appart to ... | b860588bf52a35f879d84cad7da6231135e5c5a8 | 624,205 |
def get_kqshift(ngkpt, kshift, qshift):
"""Add an absolute qshift to a relative kshift."""
kqshiftk = [ kshift[i] + qshift[i] * ngkpt[i] for i in range(3) ]
return kqshiftk | 0fe469cbeea3265705e1eb89bad8c00cb59374a7 | 624,208 |
def update_parameters(parameters, grads, learning_rate):
"""
Update the parameters' values using gradient descent rule.
Arguments
---------
parameters : dict
contains all the weight matrices and bias vectors for all layers.
grads : dict
stores all gradients (output of L_model_ba... | 4e0a93607ab975eebebc44221ec8d8acc84b8ccf | 624,209 |
def _mk_range_bucket(name, n1, n2, r1, r2):
"""
Create a named range specification for encoding.
:param name: The name of the range as it should appear in the result
:param n1: The name of the lower bound of the range specifier
:param n2: The name of the upper bound of the range specified
:para... | 3b72adbf6c44f4e331c5bea607dae24887f851ce | 624,213 |
def ispandigital(m, n):
"""return True iff m is pandigital in base n"""
s = set()
while m > 0:
m, b = divmod(m, n)
if b in s:
return False
s.add(b)
return True | 2e4ff50b6930198d354c5d71856a643eda82f442 | 624,215 |
from typing import List
def num_trainable_params(hidden_nodes: List[int], n_inputs: int,
n_outputs: int):
"""Calculate the number of weights in a neural network
Illustration:
https://stats.stackexchange.com/questions/296981/formula-for-number-of-weights-in-neural-network
Arg... | ec6867775cbca29b92638dbe90e4b10ebd2ced19 | 624,216 |
def precision_recall_f1_support(true_positives, false_positives, false_negatives):
"""Returns the precision, recall, F1 and support from TP, FP and FN counts.
Returns a four-tuple containing the precision, recall, F1-score and support
For the given true_positive (TP), false_positive (FP) and
false_nega... | d0548321330881eba6efd0f6df92b89a57d3f139 | 624,219 |
import torch
def bbox_generator3d(
x_start: torch.Tensor,
y_start: torch.Tensor,
z_start: torch.Tensor,
width: torch.Tensor,
height: torch.Tensor,
depth: torch.Tensor,
) -> torch.Tensor:
"""Generate 3D bounding boxes according to the provided start coords, width, height and depth.
Arg... | e2f284c3d10ee4cffe811d90aa9a88bbea914831 | 624,220 |
def find_freq(wvec, freq_val):
"""
Helper function returns the nearest index to the frequency point (freq_val)
"""
return min(range(len(wvec)), key=lambda i: abs(wvec[i]-freq_val)) | 262605d4b641c36470a2985a0008e4ea0d79d4cf | 624,221 |
from datetime import datetime
def str_to_date_obj(date_str, frmt='%a %d %b %Y %H:%M:%S +0000'):
""" Utility function to return str date to date object. """
return datetime.strptime(date_str, frmt).date() | 4f183bd5e48e147c8e4ae2f91c389691505edd4f | 624,227 |
import re
def parse_grant(grant):
"""Parse for grant number from grant annotation."""
if len(grant):
grant = re.sub(r'RO', 'R0', grant)
grant_info = re.search(r"([A-Z][A-Z](\s|-)*\d{3,})[ /-]", grant, re.I)
if grant_info is not None:
grant_number = grant_info.group(1).upper... | 1d36c5aa1687ea2f86f7a152d367b3a946b4afab | 624,228 |
import base64
def b64_to_bytes(val: str, urlsafe=False) -> bytes:
"""
Convert a base 64 string to bytes
"""
if urlsafe:
return base64.urlsafe_b64decode(val)
return base64.b64decode(val) | 68123b0b166277404f9574ca1ca2c215a2992516 | 624,231 |
def repeat_interleave(input, repeats, dim=0):
"""
Repeat and interleave a tensor along a given dimension. The current PyTorch
implementation of `repeat_interleave` is slow and there is an open ticket for it:
https://github.com/pytorch/pytorch/issues/31980
Args:
input (torch.Tensor): Tensor c... | a35411fb46a48b4a485604106298bb54e9c94a50 | 624,232 |
def get_filepaths(casedir, prefix='stdout_run', suffix='.txt', niter=5):
"""Get the file paths with data to read.
Parameters
----------
casedir : pathlib.Path object
Directory that contains the files to read.
prefix : string (optional)
Common prefix of the file names; default: 'stdo... | 3058da26e8f59e0f24d80a9155eb04603ab839a9 | 624,233 |
def temporal_decimation(data,
mb=1):
"""
Decimate data by mb
new frame is mean of decimated frames
Parameters:
----------
data: np.array (T x d)
array to be decimated wrt first axis
mb: int
contant by which to decimate d... | 4afe62ea2aa7ab9e1d8dedc9588ca515b32ff84a | 624,235 |
def readattr(_obj, _name, _default=None, _error_on_none=None):
"""
Reads an attribute value from an object
:param _obj: The object
:param _name: The name of the attribute
:param _default: If set, the value to return if the attribute is missing or the value is None
:param _error_on_none: If set, ... | 357317473d238b63aa02c5cb7a720ad39a454237 | 624,239 |
def returncode_msg(retcode: int) -> str:
"""interpret retcode"""
if retcode < 0:
sig = -1 * retcode
return f'terminated by signal {sig}'
if retcode <= 125:
return 'error during processing'
if retcode == 126: # shouldn't happen
return ''
if retcode == 127:
ret... | 2ddc3018c2dbda65546469068a58158eff4a234a | 624,247 |
def row_format_resource(*fields):
"""Transform a variable number of fields to a `table-row` format.
```
>>> row_format_resource(a,b,c,d)
'| a | b | c | d |'
```
:param fields: fields to be converted to row.
"""
return ('| {} ' * len(fields)).format(*fields... | bab8eec97396ba8021ce85e9a57d766a6de630ef | 624,250 |
from typing import List
def url_create_payloads(url_information: dict) -> List[dict]:
"""
Returns a list of payloads.
Args:
url_information (dict): The data retrieved from URLHaus db.
Returns:
payloads (list): list of payloads associated with the URL.
"""
... | f4e784f4eeaf808b6495159dabb7cebecbc68e1c | 624,257 |
from typing import Union
import logging
def configure_logging(
logging_level: Union[int, str] = logging.INFO,
logging_fmt: str = "%(levelname)s: %(name)s: %(funcName)s: %(message)s",
logger_obj: Union[None, logging.Logger] = None,
) -> logging.Logger:
"""
Setup logging on the root logg... | e3aa91255653e1c04a6f481bec10b8257968b748 | 624,261 |
def roi_shape(roi):
"""
Shape of an array after cropping with ``roi``.
Same as ``xx[roi].shape``.
"""
def slice_dim(s):
return s.stop if s.start is None else s.stop - s.start
if isinstance(roi, slice):
roi = (roi,)
return tuple(slice_dim(s) for s in roi) | 098ecd4709bc79ace7cf2aee8eb712aa97eaf9f7 | 624,266 |
import re
def extract_placeholders(template):
"""Extract the template's placeholder names."""
return re.findall(r'{(.*?)}', template) | 35149e789988122d667c00542b691da3970caa77 | 624,267 |
from typing import List
def get_cache_types() -> List[str]:
"""
Return the types (aka levels) of the cache.
"""
return ["mem", "disk"] | 8548be4a15166097079914b76f0db815b60233ae | 624,279 |
import random
def propose_random_nni(tree):
"""
Propose a random NNI rearrangement
"""
nodes = tree.nodes.values()
# find edges for NNI
while True:
node1 = random.sample(nodes, 1)[0]
if not node1.is_leaf() and node1.parent is not None:
break
node2 = node1.par... | bc8cee4817e228d1135bf9569ec1b75c849fc5fd | 624,280 |
from typing import Any
def return_true(*_: Any) -> bool:
"""A dummy function that always returns true."""
return True | 61531149f693468a8431aeef0aa0177fd8b1506c | 624,282 |
def take_bet(player: dict) -> float:
"""Prompt the player for how much money to bet."""
while True:
print(f"\nYou currently have ${player['money']:.2f}")
bet = input('How much money would you like to bet on this hand? (min: $20)\n> $')
if not bet.isdigit() or float(bet) < 20:
... | b28d48bdd690cd7ec317fbe00da039de86a2423a | 624,285 |
def subOneThenMult(value, arg):
"""Subtracts one from arg then multiplies by value"""
return (value) * (arg - 1) | 8bfc182e510d6c225349e14c1835b2cfa21be971 | 624,290 |
import torch
from typing import Optional
def _weighted_mean(
tensor: torch.Tensor,
weight: Optional[torch.Tensor],
) -> torch.Tensor:
"""
Compute weighted mean.
:param tensor:
The tensor.
:param weight:
An optional weight.
:return:
The (weighted) mean. If weight i... | d9a6eb2d185990b5d4c5b502c15d6c80bb7734e3 | 624,292 |
def conv_out_shape(in_shape, out_fms, p, k, s):
"""
Gets the output shape [height, width] for a 2D convolution.
(Assumes square kernel).
@param in_shape: The input shape [batch, height, width, channels].
@param out_fms: The number of feature maps in the output.
@param p: The padding type (eithe... | f4cab9933947815304407d92427627f01accb8f4 | 624,293 |
def computeMissScore(cycles, lower, upper, full_score):
"""Computes the score depending on the number of cache misses."""
if cycles <= lower:
return full_score
if cycles >= upper:
return 0
score = (cycles - lower) * 1.0
range = (upper - lower) * 1.0
return round((1 - score / ra... | 6cfc24fc7a6956a411e7c4e4228f7ec1471a2622 | 624,294 |
import math
def rotateSlope(m, theta):
""" Rotates the given slope for a certain angle. """
return (math.sin(theta) + m * math.cos(theta)) / (math.cos(theta) - m * math.sin(theta)) | b0a29b6cd481db80a162d0dd65734c588d1a92b4 | 624,295 |
import math
def _ra_dec_conversion(ra, dec):
"""Given ra and dec in degrees, convert to (rahr, ramin, rasec, decsign, decdeg, decmin, decsec)
where decsign is a string, either '+' or '-'"""
# get ra, dec in hms, dms
rahr = math.floor(ra / 15.0)
if not rahr:
ra_remainder = ra
else:
... | c593194f3c048352ab30ca28b4b405d0268495f9 | 624,296 |
def get_subtask(cmd_action, file_dep=None):
"""Return a dictionary defining a substack for string 'cmd_action'."""
if cmd_action.startswith("poetry run "):
name = cmd_action.split(" ")[2]
else:
name = cmd_action.split(" ")[0]
task = {"name": name, "actions": [cmd_action], "task_dep": ["i... | 105a1c4ae376dd32b5d61f9713eef29061c25d1a | 624,306 |
import json
def json_unstringify(json_to_objify, default=None):
"""Convert a json string to a python object.
Args:
json_to_objify (str): The json string.
default (object): The default value if no json string is passed in.
Returns:
object: The un-stringified object.
"""
tr... | 78ca7128020e72f138b261b5af7335fe7cd785c9 | 624,308 |
def get_repadding(crops, d_shape):
"""
Returns
-------
tuple
padding values to restore 3D np array after it was cropped.
Parameters
----------
crops : list
3 tuples in a list [(nz1,nz2), (ny1,ny2), (nx1,nx2)]
d_shape : tuple
or... | 0bb0a12b1c7d5964b685b9a2622ba32d036a55e1 | 624,310 |
def shorten_duplicate_content_url(url):
"""Remove anchor part and trailing index.html from URL."""
if '#' in url:
url = url.split('#', 1)[0]
if url.endswith('index.html'):
return url[:-10]
if url.endswith('index.htm'):
return url[:-9]
return url | 86c351d857d9e3b140af2f81ab67959f5697e33b | 624,318 |
import random
def generate(model, n, seed, max_iterations):
"""Generates a list of tokens from information in model, using n as the
length of n-grams in the model. Starts the generation with the n-gram
given as seed. If more than max_iteration iterations are reached, the
process is stopped. (This is to prevent... | 16412c50a7082bed5668fd78213bb30f2d6c089b | 624,319 |
def get_edge_label(layer):
"""Define edge label based on layer type.
"""
if layer.type == 'Data':
edge_label = 'Batch ' + str(layer.data_param.batch_size)
elif layer.type == 'Convolution' or layer.type == 'Deconvolution':
edge_label = str(layer.convolution_param.num_output)
elif lay... | 729cafaa01b9f47ac6d4a27f397fef7a18dc9766 | 624,320 |
def convert_hhmmss(hhmmss):
"""Convert hh:mm:ss to seconds."""
fields = hhmmss.split(":")
if len(fields) != 3:
raise ValueError("Received invalid HH:MM:SS data: {}".format(hhmmss))
fields = [int(x) for x in fields]
hours, minutes, seconds = fields
return (hours * 3600) + (minutes * 60) +... | bcbf0911eda403b38ca31a4efc9ef0ca98cb8f82 | 624,324 |
def _get_trids(db, id_val, id_type):
"""Return text ref IDs corresponding to any ID type and value."""
# Get the text ref id(s)
if id_type in ['trid']:
trid_list = [int(id_val)]
else:
id_types = ['pmid', 'pmcid', 'doi', 'pii', 'url', 'manuscript_id']
if id_type not in id_types:
... | 4f4c0bf412bd608efd6623b4681d653c94a8b05d | 624,325 |
def groupby(function, sequence):
"""
Example:
>>> from m2py import functional as f
>>> f.groupby(len, ['Alice', 'Bob', 'Charlie', 'Dan', 'Edith', 'Frank'])
{3: ['Bob', 'Dan'], 5: ['Alice', 'Edith', 'Frank'], 7: ['Charlie']}
>>>
>>>
>>> f.groupby(f.is_even, [1, 2, 3, 4, 5, 6, 7])
{F... | 857bbc415cf2c664370b7b36f1b23469f1769fd2 | 624,327 |
def is_leaf(dmrs, nodeid):
"""
Check if a node has no outgoing links
"""
return not any(dmrs.get_out(nodeid, itr=True)) | b8ecd4056b6488341abd40e5fe4b8053fd1e3454 | 624,331 |
def comparator_eval(comparator_params):
"""Gets BUFF score for interaction between two AMPAL objects
"""
top1, top2, params1, params2, seq1, seq2, movements = comparator_params
xrot, yrot, zrot, xtrans, ytrans, ztrans = movements
obj1 = top1(*params1)
obj2 = top2(*params2)
obj2.rotate(xrot, ... | bfd2892b44b14d9561c26778f062b0ca7ab34bcd | 624,333 |
import re
def count_sentences(string: str) -> int:
"""
Counts quantity of sentences in given text.
"""
sentence_endings = re.compile("[.!?]+")
return len(sentence_endings.findall(string)) | e1e1d2bdfedcd71fb35397e307b036192ab36104 | 624,334 |
def normalize_ssc(name):
"""
Convert a name in SCREAMING_SNAKE_CASE to regular notation,
e.g. "Screaming snake case".
Args:
name: Name to convert.
Returns:
str: Converted name.
"""
if not name:
return
return " ".join(part for part in name.split("_")).capitalize... | 42f4c66aff0ffe9ede73d2700814935a38eb9f4e | 624,340 |
def trim_for_encoding(wav_data, sample_length, hop_length=512):
"""Make sure audio is a even multiple of hop_size.
Args:
wav_data: 1-D or 2-D array of floats.
sample_length: Max length of audio data.
hop_length: Pooling size of WaveNet autoencoder.
Returns:
wav_data: Trimmed array.
sample_le... | 31d51d9242c53b6012948ff33c59b002b0acf927 | 624,341 |
import re
def alpha_only(s):
"""
Strip any non-alpha characters from s, and convert to lowercase
"""
return re.sub(r'[^A-Za-z]+', '', s.lower()) | 71f69ebe8e3d0819ff6b4336bfeac7a0e907364c | 624,344 |
def swift_library_output_map(name, module_link_name):
"""Returns the dictionary of implicit outputs for a `swift_library`.
This function is used to specify the `outputs` of the `swift_library` rule; as
such, its arguments must be named exactly the same as the attributes to which
they refer.
Args:
name: ... | 629a8199142cf584497b188c51d05ad55c457b8f | 624,346 |
def gen_custom_item_windows_group(description, info, value_type, members,
group_name):
"""
Generates a custom item stanza for a windows group membership audit
Args:
description: string, a description of the audit
info: string, info about the audit
value_type: string, "POLICY_TEXT" -- inclu... | c840c9510e863a7c06bb20d13f75a8d2c5a74272 | 624,349 |
def convert_string_to_list_float(string):
"""
Convert the string of a list to the actual floating point list.
"""
return [float(l) for l in string[1:-1].split(", ")] | 77db3e9fa59d27c47a5a0d63185d467293527b2c | 624,350 |
def find_aircraft_id(key, config):
"""
find_aircraft_id
The aircraft identifier can be given either as a dictionary key in the yaml
file or under the fields 'identifier' or 'id' in the aircraft configuration
item. This function test in the parsed yaml to find the aircraft id.
"""
if 'ident... | e3988096a4a3ebf70681efb0595a8a1ad8abaa96 | 624,357 |
def call_reply(msg, call_return):
"""Construct message used by CtrlServer when replying to API calls.
:param msg: Description of API call.
:type msg: string
:param call_return: Return value of API call.
:type call_return: string
:returns: Constructed call_reply dict, ready to be sent over the w... | eadbaf02bf182af228e0c4a1a31603ca5bfa0eb2 | 624,358 |
import torch
def flatten(params):
"""
Turns a module's parameters (or gradients) into a flat numpy array
params: the module's parameters (or gradients)
"""
with torch.no_grad():
return torch.cat([p.data.view(-1) for p in params]) | 1e278028f1878aa1cadc730fe03007cb6062f4c3 | 624,359 |
def pk_same_public_key(key1, key2):
"""Return true iff key1 and key2 are the same key."""
return key1.encode_key(1) == key2.encode_key(1) | 084818c7af42ac52573c14c1e103f91ee882e9a5 | 624,361 |
def safe_mathis_label(tput_true, tput_mathis):
"""
Returns the Mathis model label based on the true throughput and
Mathis model fair throughput. If either component value is -1
(unknown), then the resulting label is -1 (unknown).
"""
return (
-1 if tput_true == -1 or tput_mathis == -1 el... | 26108c82db9e5e5f3deb3affa37326ff2a28f2f0 | 624,363 |
def setup_with_context_manager(testcase, cm):
"""Use a contextmanager to setUp a test case."""
val = cm.__enter__()
testcase.addCleanup(cm.__exit__, None, None, None)
return val | ef60ebfe6ce00ea2a4784a61241dc22dd292b81d | 624,366 |
def get_item(iterable_or_dict, index, default=None):
"""Return iterable[index] or default if IndexError is raised."""
try:
return iterable_or_dict[index]
except (IndexError, KeyError):
return default | 9fb8bcaf2dcc30396cdce6e61610c5d1a51c40ff | 624,369 |
def getDimensions(name):
"""Gets the rows and columns of a matrix from a text file
Args:
name (string): filename for matrix
Returns:
tuple: a tuple of the rows and columns
"""
file = open(name, 'r')
size = file.readline().split() #split at a tab
rows = size[0]
cols = s... | 339fda5cd34ed20b3c2aa1cd5908d642e3ca0d2e | 624,370 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.