content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def get_key_paths(data_dict,
keys_to_consider=None,
keys_not_to_consider=None,
root_path=None):
"""
Example:
get_key_paths({
'a' : {
'b': 1
},
'c' : 2
})
returns:
['a.b', 'c']
:param data_dict: (Nest... | c3548b24aaf49e2e5f5632f503a5fd32d38eb00b | 660,967 |
def update_guess_word(word, guess_word, guess):
"""
Updates the guess_word with the newly guessed letter.
By iterating over the word and comparing each character, we can find
all occurences of that letter and can replace the underscores in the
guess word for each found occurence.
E.g. if the w... | f30bc7af577ce2b16d4a021e73d77f2e1f6cdb7b | 298,650 |
def all_registry_hosts(
CallableRegistry, # noqa: N803
PropertyRegistry,
CachedPropertyRegistry,
CallableParamRegistry,
PropertyParamRegistry,
CachedPropertyParamRegistry,
):
"""All test registries as a list."""
return [
CallableRegistry,
PropertyRegistry,
Cached... | 3af05ff3cd4d55e4a48f186387e6e15c436561bf | 172,674 |
import math
def rounded_bez(angle):
"""
From https://math.stackexchange.com/questions/1671588/b%C3%A9zier-curve-approximation-of-a-circular-arc.
The control points of a cubic Bezier curve for approximating a circular arc with end points
P0, P1, radius R, and angular span A:
... | b061c6e46eac5abb0a4f05788535e029a12856bc | 598,199 |
def even_or_odd(s: str) -> str:
"""
Given a string of digits confirm whether the sum of all the individual
even digits are greater than the sum of all the indiviudal odd digits.
"""
sum_even, sum_odd = sum([int(i) for i in s if int(i) % 2 == 0]), sum([int(i) for i in s if int(i) % 2 != 0])
if su... | 6d43137e1793ab03e4f317dd357bd63d0398649f | 302,472 |
import re
def autolab_assignment_name(filename):
"""Extract the autolab assessment name for an autolab csv grade
file name.
"""
m = re.search("(.*)_(.*)_[0-9]{12}.csv", filename)
if m:
return m.group(2)
return None | f7e168d7aa4397062f2dd75d25f7f65a1492bb00 | 267,374 |
def get_P_cp_ss(pmp_type):
"""ソーラーシステムの循環ポンプの消費電力
Args:
pmp_type(str): ソーラーシステムの循環ポンプの種類 (省消費電力型,上記以外の機種)
Returns:
float: ソーラーシステムの循環ポンプの消費電力 (W)
"""
# 表3 ソーラーシステムの循環ポンプの消費電力の値と適用条件
table_3 = (40.0, 80.0)
if pmp_type == '省消費電力型':
return table_3[0]
elif pmp_type ==... | 1025d09bd0622088866e6ebb79527c60c2fc2afa | 226,607 |
import math
def current_passage_offset(scroll_size, passage_size, reading_every, seconds):
"""Get the offset of the current passage in a scroll. We assume that the scroll has been being
read since the beginning of time, where a new passage of `passage_size` characters is read every
`reading_every` seconds... | 2a976c9b406eb2648e1463fd10277c39e25f2d1f | 270,885 |
def vertical_path(size):
"""
Creates a generator for progressing vertically through an image.
:param size: A tuple (width, height) of the image size
:return: A generator that yields a set of columns through the image.
Each column is a generator that yields pixel coordinates.
"""
width, heigh... | 91d42be4bdd8f501405f226a0a158491932d6b2b | 34,617 |
import base64
import textwrap
def encode_object_data(data):
"""
Encodes bytes using base64 and wraps the lines at 64 charachters.
:param bytes data:
the data to be encoded
:returns:
the line-wrapped base64 encoded data as a list of strings, one string
per line
:rtype: list... | 69e8f14680f66b9afecaf851f26cf99efe5eb962 | 253,352 |
import requests
def getQuote(func, symbol):
"""
Gets JSON string for desired quote. Below is documentation for Alpha Vantage requests:
Available function:
INTRADAY
DAILY
DAILY_ADJUSTED
WEEKLY
WEEKLY_ADJUSTED
MONTHLY
MONTHLY_ADJUSTED
symbol -> Quo... | 3395df5834c5b27186d07732679250f5cf6dd7f7 | 142,955 |
def divide_list(a_list, divide_func):
"""Divide a list like object into two parts.
- a_list: list like object
- divide_func: the divide function to return True/False
Return two parts of the list.
Example:
divide_list([1, 2, 3], lambda x: x > 1) -> [2, 3], [1]
"""
suit, not_suit = ... | f310b15b79c43b5e001db3ac7ea3d55a1292db3c | 444,719 |
def escapeBelString(belstring):
"""Escape double quotes in BEL string"""
return belstring.replace('"', '\\"') | ef2efa04cd356dd17d44f1a2f0b9f518d7c13170 | 633,093 |
import requests
def make_get_request(uri: str, payload):
"""
Function to make a GET request to API Endpoint
:param uri:
:param payload:
:return:
"""
response = requests.get(uri, payload)
if response.status_code != 200:
return None
else:
return response.json() | cf7c97415658b3d7a059f862a7251b66ecf2ca59 | 681,182 |
def interval_pos(test_x, x0, x1):
"""
In 1D space:
x0 x1
############## ################## ##############
# ---- position 0 position + position
:param test_x:
:param x0:
:param x1:
:return:
"""
assert x1 >= x0
if tes... | c24206d54c8b68594dcae1c35ffc44aa366373af | 119,963 |
from typing import List
from typing import Dict
def _process(proc_data: List[Dict]) -> List[Dict]:
"""
Final processing to conform to the schema.
Parameters:
proc_data: (List of Dictionaries) raw structured data to process
Returns:
List of Dictionaries. Structured to conform to t... | ce8a7e10ab12ba58b41c4e8286b054ea4f81dad0 | 664,967 |
import unicodedata
def isNumber(s):
"""
Determines if a unicode string (that may include commas) is a number.
:param s: Any unicode string.
:return: True if s represents a number, False otherwise.
"""
s = s.replace(',', '')
try:
float(s)
return True
except ValueError:
... | df43f7e83cab485c48b21bdb221cb8804e98596a | 128,785 |
import torch
def create_window(window_size: int, sigma: float, channel: int):
"""create 1D gauss kernel
Args:
window_size (int): the size of gauss kernel
sigma (float): sigma of normal distribution
channel (int): input channel
"""
half_window = window_size // 2
coords = t... | a7674277e5977fd7cf80f24af319e28163d62e4f | 410,632 |
def get_metafeatures_dim(metafeatures_spec):
"""Get dimensionality of metafeatures."""
return sum([len(m[2]) if m[1] is str else 1 for m in metafeatures_spec]) | 8b12e83a6a4db7813418509997b85f53cb57be5d | 455,218 |
def gf_eval(f, x, p):
"""Evaluate f(x) over GF(p) using Horner scheme. """
result = 0
for a in f:
result *= x
result += a
result %= p
return result | 2178a931d88b22690231d43652ba172e55d647f7 | 498,656 |
def _use_oss_fuzz_corpus(experiment_config: dict) -> bool:
"""Returns the oss_fuzz_corpus flag of the experiment described by
|experiment_config| as a bool."""
return bool(experiment_config.get('oss_fuzz_corpus')) | bfefd10f3e017479b3402466625ed33fced5a04f | 133,204 |
def reynolds_number(v: float, d_hyd: float, kin_visco: float) -> float:
"""
Calculate Reynolds number.
**Parameters:**
- `v`: (*float*) = flow velocity [m/s]
- `d_hyd`: (*float*) = hydraulic diameter [m]
- `kin_visco`: (*float*) = kinematic viscosity [m^2/s]
**Returns:** (*float*)
""... | b4d7a14facd9405910f64093a02e9b06221eb175 | 216,870 |
def extract_extension_attributes(schema: dict) -> dict:
"""Extract custom 'x-*' attributes from schema dictionary
Args:
schema (dict): Schema dictionary
Returns:
dict: Dictionary with parsed attributes w/o 'x-' prefix
"""
extension_key_format = 'x-'
extensions_dict: dict = {
... | 80829a1e222b7e55d41483592e20b06bb63ea8a2 | 692,654 |
def decline_invite_command(instance, player, arguments = None):
""" Remove a player from the invited list of an instance.
Args:
instance: The instance to uninvite player from.
player: The player wishing to decline an invite.
arguments: Not used, can be any value.
If the player wasn't actually invite... | 76f989a8d5ad93fb0078f305d70979a6d45471a9 | 526,462 |
def de_unit_key(key: str) -> str:
"""Remove the unit from a key."""
if key.endswith("f"):
return key[:-1]
if key.endswith("in"):
return key[:-2]
if key.endswith("mph"):
return key[:-3]
return key | dc71e36f3b51959beec6a659397df8199dca519c | 291,025 |
import base64
import hashlib
def generate_short_url(original_url: str, timestamp: float):
"""generate_short_url generates an 8 character string used to represent the original url. This 8 character
string will be used to "unshorten" to the original url submitted.
parameter original_url: the url that the user passes... | 4704111df15e9eb0f71204732fc5cf2897904cf1 | 54,022 |
import re
import string
def normalize_string(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
text = " " + re.sub(r'(\[PAD\]|\[UNK\]|\[CLS\]|\[SEP\]|\[MASK\])', ' ', text) + " "
text = text.replace(" a ", " ").replace(" an ", " ").replace("... | 0635e5db96ebed1b6236d18dc6e310322a3b116b | 332,625 |
def _convert_kebab_to_snake(kebab_case_string: str) -> str:
"""
Convert a string provided in kebab-case to snake_case
"""
return kebab_case_string.replace('-', '_') | 09e48afdd8bdd2ec1d88ede61b041e63f8682f2c | 139,729 |
from typing import Callable
from typing import Set
from typing import Type
def is_quorum(is_slice_contained: Callable[[Set[Type], Type], bool], nodes_subset: set):
"""
Check whether nodes_subset is a quorum in FBAS F (implicitly is_slice_contained method).
"""
return all([
is_slice_contained(n... | 4a4af3af8ca5a3f969570ef3537ae75c17a8015c | 699,202 |
def unicode_item_filter(item, action_dict):
"""
Filter table items by category and search string
action_dict has the following entries controlling filtering:
cat_filter - filter for the category. if None ignore filter. 'L*' filters any Letter category
name_filter is a keyword to find the th... | 120bedd13cc45d385fe4bfb43bc8530040d8fe88 | 284,842 |
def tochannel(room_name):
"""Convert a Stack room name into an idiomatic IRC channel name by downcasing
and replacing whitespace with hyphens.
"""
return '#' + room_name.lower().replace(' ', '-') | be6c9a2427b5faa1f198b459915a26d9afeff158 | 402,718 |
import inspect
def _extract_method_kwargs(kwargs, method, remove=True):
"""Internal method to extract keyword arguments related to a given method.
Parameters
----------
kwargs : dict
A dictionary of keyword arguments
method : func
A function with keyword arguments
remove : boo... | 8507756708974e2d5ae72de90e6880d052204273 | 274,082 |
import time
def epochtime_to_isodate(commit_time):
"""
>>> epochtime_to_isodate(1518450170)
'2018-02-12'
"""
return time.strftime("%Y-%m-%d", time.gmtime(commit_time)) | c34208c4204068fa57c91fd2c5504aa05c947a16 | 449,917 |
import json
def string_to_dict(value):
"""str to dict, replace '' with None"""
if not value:
return None
values = json.loads(value)
for key in values:
if values[key] == "":
values[key] = None
return values | d9d11241f32dd2d3cddbd89c604da60c3e9a18b7 | 671,974 |
import copy
def copy_mode(mode):
"""
Return a copy the given build mode. Use a deep copy so that flags
can be appended to the new build mode.
"""
return copy.deepcopy(mode) | dc7dbe2a5d0e9195c2c54c511219d5b4884c8242 | 444,076 |
def DatabaseFlags(sql_messages,
settings=None,
database_flags=None,
clear_database_flags=False):
"""Generates the database flags for the instance.
Args:
sql_messages: module, The messages module that should be used.
settings: sql_messages.Settings, the ... | 02ad8bc7e8c7b9806fc145d0e2e049747719d8e8 | 563,343 |
import math
def get_acc(vehicle, meters=False):
"""
Compute acceleration of a vehicle.
Parameters
----------
meters : bool
Whether to use m/s^2 (True) or km/h^2 (False).
vehicle : carla.vehicle
The vehicle for which speed is calculated.
Returns
-------
accelerati... | aff2992f8c1c47cf3b54f4412b8450acf0b2f24c | 260,773 |
def blocktrans_cen2side(cen_size):
""" Convert from center rep to side rep
In center rep, the 6 numbers are center coordinates, then size in 3 dims
In side rep, the 6 numbers are lower x, y, z, then higher x, y, z """
cx = float(cen_size[0])
cy = float(cen_size[1])
cz = float(cen_size[2])
sx... | 8e2791c9cc5798f754c58caeac31251eeb9664eb | 372,531 |
def _make_sql_url(hostname, database, **kwargs):
"""Build a URL for SQLAlchemy"""
url = hostname
if kwargs.get("port"):
url = "{}:{}".format(url, kwargs["port"])
if kwargs.get("user"):
credentials = kwargs["user"]
if kwargs.get("password"):
credentials = "{}:{}".forma... | 53e86dfac1782a655fc4f638501db6dc6a0ecb52 | 411,642 |
from typing import Iterable
from typing import Tuple
def sum_iter(x: Iterable[int], y: Iterable[int], s: int = 1) -> Tuple[int, ...]:
""" Returns the equation x + s * y for each element in the sequence x and y """
return tuple(a + s * b for a, b in zip(x, y)) | 33de4352a9d23a462ae98f91a602037aa631fad6 | 435,336 |
def set_passive_el(xmin, xval, passive_el):
""" Sets the values of passive elements.
Args:
xmin (:obj:`numpy.array`):
xval (:obj:`numpy.array`): Indicates where there is mass.
passive_el (:obj:`numpy.array`): Passive element nodes.
Returns:
A tuple with updated xmin and xv... | f80101a4ea4abdfed5fc3caf20195263519d6074 | 438,259 |
def tknzr_exp_name(exp_name: str) -> str:
"""Tokenizer experiment name."""
return f'{exp_name}-tokenizer' | 24014d31ca10599ad8e289a091d05362b609ce9c | 254,595 |
def do_almost_nothing(value):
"""Do almost nothing."""
value += 1
return value | a95fddb574df02eda84c7e31b85bc239b2e087af | 434,575 |
def fill_category_object(category_id, name, is_un_classified):
"""
category object:
{
category_id: category_id,
name: category_name,
is_un_classified: boolean
}
"""
return dict(category_id=category_id, name=name, is_un_classified=is_un_classified) | 807485164d912c66cb40d8cdb8647ca1b985c33d | 124,474 |
def get_detection_rate(stats):
"""Get detection rate as string."""
return f'{stats["malicious"]}/{sum(stats.values())}' | 1b294eee3b2ddafddaf4851d5a256e63b4b80705 | 594,845 |
import pathlib
import json
def maybe_shim_old_cert_store(
old_path: pathlib.Path, new_path: pathlib.Path, master_url: str
) -> None:
"""
maybe_shim_old_cert_store will detect when an old v0 cert store is present and will shim it to
a v1 cert store.
"""
if not old_path.exists():
return ... | 88bbb9b152da1f3a4dfad4c48a40ce579282ff4f | 281,515 |
def _swap_first_args(op):
"""
Given a binary operator function, return a function that applies it
but with argument order swapped for the first two arguments.
"""
def op_swapped(a, b, *args, **kwargs):
return op(b, a, *args, **kwargs)
return op_swapped | de070bcf22dc11fdd34f8507be14729dd5c0ceb2 | 595,878 |
def _version_to_tuple(version):
"""Converts the version string ``major.minor`` to ``(major, minor)`` int tuple."""
major, minor = version.split('.')
return (int(major), int(minor)) | 921a3855fd23a597f13dab27f660cf4b0113926b | 47,620 |
def double_sum(x, y):
"""Returns twice the sum of the two arguments"""
return 2 * (x + y) | 57386ce717e85f564e50dcc6e3dfa9def24f3975 | 547,340 |
def bytes_find_single(x: bytes, sub: int, start: int, end: int) -> int:
"""Where is the first location of a specified byte within a given slice of a bytes object?
Compiling bytes.find compiles this function, when sub is an integer 0 to 255.
This function is only intended to be executed in this compiled for... | 9e94788a4d9b6c102e56cc95422b5f367754b22e | 683,939 |
def setup_none(lvl):
"""Set up default, empty smoother."""
def smoother(A, x, b):
pass
return smoother | 9c4c91b6c6dd98436932442d595b8fb06e83de5e | 81,215 |
from typing import Union
def get_cell_sizes(cell_size: Union[int, list, tuple]):
"""Handle multiple type options of `cell_size`.
In order to keep the old API of following functions, as well as add
support for non-square grids we need to check cell_size type and
extend it appropriately.
Args:
... | b372c2a960f59d861f08eaecbbc2f7499226272e | 74,874 |
def _fill_zero_counters_dict(counters_config, counters_dict):
""" A util function for filling counters dict with all counters set to 0.
Args:
counters_config: a tuple containing cumulative counters configuration.
counters_dict: an empty dict to fill with zero counters.
Returns:
a filled dictionary wi... | eecd724b49c97b200942285428ea4b98d7dc2f3c | 548,320 |
import torch
def batch_gather(input, index):
"""Similar to tf.compat.v1.batch_gather.
Args:
input: (Batch, Dim1, Dim2)
index: (Batch, N_ind)
Returns:
output: (Batch, N_ind, Dim2)
output[i, j, k] = input[i, index[i, j], k]
"""
index_exp = index.unsqueeze(2).exp... | 0e4d7e9d58ab799d562d1d1c44dee73c77c0c282 | 345,756 |
def average(numbers):
"""
Calculate average of a list numbers.
:param numbers: the number to be calculated.
:return: average of a list number.
>>> average([1, 2, 2, 3, 4, 7, 9])
4.0
>>> average(range(1, 11))
5.5
>>> average(range(1, 101))
50.5
"""
return sum(numbers) / l... | 691758bf8f3bed887595295b264a83c24b434ddf | 528,147 |
from typing import Dict
from typing import Optional
def dict_to_str(data: Dict, sep: Optional[str] = " ") -> str:
"""Converts the given dictionary to a string separated by the given separator.
Args:
data (dict): dict that needs to be transformed
sep (str): Separator to be used.
Re... | f6d58949727bde9cf75b4fd2dd9c155a2a894ccf | 335,127 |
from datetime import datetime
def print_weather_data(data, verbose):
"""Displays the weather data in human readable format.
Args:
data (dict): dictionary that contains the weather data.
verbose (boolean): if `True`, more detail will be printed about
the weather and the city.
"""
... | b2c08f6d678e689b8db05e111985ad77e24830d8 | 431,342 |
import requests
def get_citeas_apa_citation(resource):
"""
Returns a dict with a resource and generated CiteAs citation in APA format.
"""
r = requests.get("https://api.citeas.org/product/" + resource)
citation = r.json()["citations"][0]["citation"]
return {resource: citation} | f01516b54e80304b3b603470f97cb8fa8189f574 | 40,591 |
from pathlib import Path
def guess_zarr_path(path):
"""Guess whether string path is part of a zarr hierarchy.
Parameters
----------
path : str
Path to a file or directory.
Returns
-------
bool
Whether path is for zarr.
>>> guess_zarr_path('dataset.zarr')
True
... | fa19bd7e233d98bde90629fc36a0843e2f0c0ca2 | 620,290 |
def dead_code_remark(dead_code):
"""Generate remark for dead code detection."""
if dead_code["display_results"]:
if dead_code["failed"] != 0:
return "<li>remove dead code</li>"
else:
return ""
else:
return "<li>setup dead code detection tool</li>" | cc122cb5398d5e737eacf418f125c8a0a0311c9b | 451,693 |
def time_to_str(time_in_seconds):
"""
Takes a time in Seconds and converts it to a string displaying it
in Years, Days, Hours, Minutes, Seconds.
"""
seconds = time_in_seconds
minutes = None
hours = None
days = None
years = None
if seconds > 60:
minutes = seconds // 6... | ac79955ae1745180719de7260ad1f3e4e3f7f1e3 | 695,408 |
def limit_count(count, on_device):
"""
Handling of the optional "count" parameter, common in many commands.
Parameters:
- count -- desired number of elements
- on_device -- number of elements on device
If count is None or 0 return what's on device
If count > 0 use count, unles... | d2a12a04980038ff0880cedf9c29ac9df5a9eede | 189,531 |
def calc_sensor_incident_power(camera_input_power,
optical_transmission_factor):
"""
Calculate the optical power incident on the sensor.
Returns
-------
double : Watts
"""
return camera_input_power * optical_transmission_factor | c679593c80a45d450e4377390d2b89d2d85192d8 | 297,369 |
def _squared_dist(point_a, point_b, metric):
"""Compute geodesic distance between two points.
Compute the squared geodesic distance between point_a
and point_b, as defined by the metric.
This is an auxiliary private function that:
- is called by the method `squared_dist` of the class
SpecialEu... | 8b7c47bec4fae15af5e653f45947658dda6fd916 | 461,649 |
import random
import string
def random_alpha(n):
"""How do I generate a random string (of length n, a-z only) """
return ''.join(random.choice(string.ascii_lowercase) for _ in range(n)) | 51d7edb2428fb8ca886aa55a3490e3a3cf71af5c | 455,591 |
def maybe_remove_parens(s: str) -> str:
"""Remove parentheses from around a string if it has them."""
if (len(s) > 1) and (s[0] == "(") and (s[-1] == ")"):
return s[1:-1]
return s | 4c9e128f868463d922808f159b19359d8f2296d2 | 521,835 |
def fofn_to_fns(fn):
"""Return a list of file names of files in input fofn filehandler.
...doctest:
>>> fn = op.join(op.dirname(op.dirname(op.dirname(__file__))), 'tests', 'data', 'bams.fofn')
>>> fofn_to_fns(fn)
['align_p.bam', 'align_m.bam', 'align_f.bam']
"""
return [f.strip()... | 6d95d2ae4c7146874c374d075135dca3d91e050b | 409,479 |
from io import StringIO
import string
def rot_encode(data: str, n: int = 13) -> str:
"""ROT-encode the given string, shifting `n` places."""
if not 1 <= n < 26:
raise ValueError('n must be in range [1, 26)')
with StringIO() as digest:
for char in data:
if char in string.ascii_l... | 662c13fa03e37cf2efbcf20e3f71c7f2aeac9048 | 265,386 |
import pathlib
def get_mlflow_artifacts_path(client, run_id):
"""Get path to where the artifacts are located.
The benefit is that we can log any file into it and even
create a custom folder hierarachy.
Parameters
----------
client : mlflow.tracking.MlflowClient
Client.
run_id : ... | 51e7254a976c71446b062e660e35c2e219d67aa8 | 387,985 |
import torch
def step_function_perturbation(perturb, epsilon_0, alpha=1e-4, norm_type='inf', smooth_approx=False, temperature=0.01):
"""
Step function applied to the perturbation norm. By default, it computes the exact step function which is not
differentiable. If a smooth approximation based on the sigmo... | 9cfcfbdc228696c19256b7d6258177ea7e5e22cb | 522,721 |
def get_period_label(dt, data_frequency):
"""
The period label for the specified date and frequency.
Parameters
----------
dt: datetime
data_frequency: str
Returns
-------
str
"""
if data_frequency == 'minute':
return '{}-{:02d}'.format(dt.year, dt.month)
else:... | d842c6a7f76f0c6109b590eb462dee25473c38ec | 447,976 |
import torch
def rmse_loss(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""Root-mean-square error loss function."""
return torch.sqrt(torch.mean((x - y) ** 2)) | f1a7fa2091693a8903241901d1fae40a549f617d | 252,625 |
def _GrowTreeShape(unused_op):
"""Shape function for GrowTree Op."""
return [[None], [None, 2], [None], [None], [1]] | e884ca24e3a1e3372cf4947819a660c6d8892c93 | 243,479 |
def avg_num_friends(graph):
"""Average number of friends in graph."""
num_nodes = 0
num_friends = 0
for node in graph.nodes(data=True):
if 'friends_total' in node[1]:
num_friends += node[1]['friends_total']
num_nodes += 1
if num_nodes == 0:
return 0
else:... | 33ec3b692ea4eab45f976d9f24a4e7914c38bc2a | 551,733 |
def unique_node_id(graph, prefix):
"""Generate a unique id starting by a prefix.
Parameters
----------
graph : networkx.Graph
prefix : str
Prefix that is prepended to the new unique name.
Returns
-------
str
New unique node id starting with a prefix.
"""
if pre... | 78e67b7ae8c4c5051081f6df11c8baebbe6b345e | 609,780 |
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 get_template_path (filename: str, path_dict: dict) -> str:
"""
Returns the absolute path to the directory with indicated `filename` template.
Parameters:
filename (str) : template file to be populated
path_dict (dict) : dictionary of paths per source di... | f7a212c160877d2d7175d1213431f872a60f10c6 | 194,114 |
import logging
def duration(time):
"""Calculates time span of ECG strip data
The time span of the provided data indicates for how long
the ECG test was administered and provides a benchmark
for the number of expected heart beats.
Args:
time (list): time data of the ECG strip
Returns... | c161b52d53fdc410e905b9b2f8757e363acb5850 | 407,437 |
def list_2_str(data_list, join_del=""):
"""Function: list_2_str
Description: Convert a list to a string. Will be joined together with a
join delimiter. The list can consist of strings or integers.
Arguments:
(input) data_list -> List to join.
(input) join_del -> Join delimiter... | eecaa0799b9340b5c992f8b92e78cb7fdfbf78f3 | 128,194 |
def getTokens(userInput):
"""splits up the userInput via commas, strips spaces
Args:
userInput (string): comma seperated search tokens, filters
Returns:
list: of all tokens that were seperated via comma
"""
allTokens = userInput.replace(" ", "").split(',')
return allTokens | b9efc8e76c807b9858f948c35fb32d290313eacf | 335,082 |
def divide(first_term, second_term):
"""Divide first term by second term.
This function divides ``first_term`` by ``second_term``.
Parameters
----------
first_term : Number
First term for the division.
second_term : Number
Second term for the division.
.. warning::
... | ee5bc7ef5b9c71e02c9e81571060587b2010160c | 528,689 |
import math
def normalize_dict(dictionary, x, y):
"""
Normalize values in dictinoary to be in range [x, y]
:param dictionary:
:param x: range min
:param y: range max
:return: dict with values changed accordingly
"""
min_value = min(dictionary.values())
max_value = max(dictionary.v... | 79913c028998f0bcc347b77f4e6979fe3c13dc81 | 368,830 |
def humanize_duration(seconds):
"""Converts seconds into HH:MM:SS"""
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60
seconds %= 60
if hour > 0:
return "%d:%02d:%02d" % (hour, minutes, seconds)
else:
return "%02d:%02d" % (min... | 96d31a92f5a941d1e83dc91396423b54af6ceeae | 500,509 |
def check_collisions(x, y, collision_radius, objs):
"""
Checks if the position x,y collide with any obj in objs with a
collision_raidus of collision_radius
"""
epsilon = 0.2
for obj in objs:
if (obj.x - x)**2 + (obj.y - y)**2 <= \
(obj.collision_radius + collision... | a4f12eb4da20b0b99632f70a9189ce4969802499 | 421,766 |
def get_frequency(fn: str, start: int = 0) -> int:
"""Takes frequency modulation file and returns final frequency"""
with open(fn) as f:
return start + sum(int(item) for item in f) | ceae0b22f114603a8491241321806cc8b6287db6 | 195,825 |
import json
def generate_config(competitor_count, stream_count):
""" Returns a JSON string containing a config. The config pits vector_add
against a number of dummy_streams instances, specified by competitor_count.
The vector_add plugin always does the same amount of work, so the intention
behind this... | 55ef4691955a5e296f386e451474d659e1e8b1b6 | 230,044 |
def _escape_html(text, escape_spaces=False):
"""Escape a string to be usable in HTML code."""
result = ""
for c in text:
if c == "<":
result += "<"
elif c == ">":
result += ">"
elif c == "&":
result += "&"
elif c == '"':
... | cc501ea996fe971750a448c0b9589934f6b78b04 | 549,967 |
import shlex
def join_args(args):
"""Compose command line from argument list."""
return ' '.join(map(shlex.quote, args)) | daec8c6a334c8a91ccaaad6c17d6b36ce566ffa7 | 129,890 |
import math
def CO2_Calc(PO2, T):
"""
Calculate CO2.
:param PO2: partial pressure [atm]
:type PO2 : float
:param T: cell operation temperature [K]
:type T : float
:return: CO2 [mol/cm^3] as float
"""
try:
result = PO2 / (5.08 * (10 ** 6) * math.exp(-498 / T))
retur... | 727115f6d4c8deb70412abfcb06956a0dade1ba9 | 383,094 |
def split_comma(string):
"""Split the string at the comma and return the list."""
if type(string) is not str:
raise ValueError("This is not a string")
return string.split(',') | d5225af9ba1df728202ec1f6add7047840fdc691 | 497,084 |
def gradient(color_one, color_two, blend_weight):
"""
Blend between two colors with a given ratio.
:param color_one: first color, as an (r,g,b) tuple
:param color_two: second color, as an (r,g,b) tuple
:param blend_weight: Blend weight (ratio) of second color, 0.0 to 1.0
"""
if blend_weig... | 7a3645acf3a83b093e96b706f8d118e47ef85c87 | 641,267 |
def bytes_from_hex(value):
"""There are many ways to convert hex to binary in python.
This function is here to attempt to standardize on a single method.
Additionally, it will return None of None is passed to it
instead of throwing an expected string exception
"""
if not value:
return No... | 574019f671d389f2dbf876156796266c57e9d550 | 643,103 |
def encode_topic_name(original: str) -> str:
"""
Encodes a channel name into a valid SNS topic name. Common characters in topics are '*', '/', '.', ':'. Those are
translated into markers like '_WCD_'.
:param original: the original topic name (e.g., 'my.program/foo')
:return: encoded topic name safe... | ae61877e95b6de287dfaa31efe126668f25fcb31 | 233,924 |
def predict_tf_lite(model, image):
"""
TFLite model prediction (forward propagate)
:param model: TFLite interpreter
:param image: Input image
:return: Numpy array with logits
"""
input_details = model.get_input_details()
output_details = model.get_output_details()
model.set_tensor(in... | 6f651f602498066024aa370531f9afe2f94f8a60 | 618,029 |
def _GetRequestParams(options):
"""Extracts request parameters which will be passed to PostTryJob.
Args:
options: The options object parsed from the command line.
Returns:
A dictionary with parameters to pass to PostTryJob.
"""
params = {
'user': options.user,
'name': options.name,
}
... | 51d39b4a5640351b3b15fb9e6dd0a1f98cacf9f7 | 367,210 |
from typing import List
def midi_note_on(note: int, channel: int = 0, velocity: int = 64) -> List[int]:
"""MIDI 9nH message - note on.
>>> midi_note_on(70)
[144, 70, 64]
>>> midi_note_on(70, velocity=127, channel=15)
[159, 70, 127]
"""
status = 0x90 + channel
return [status, note, vel... | 76522963fc84dae8b60fb5b08317bd65a0d51c7f | 511,405 |
import re
def remove_shape_from_input_value(input_value: str):
"""
Removes the shape specification from the input string. The shape specification is a string enclosed with square
brackets.
:param input_value: string passed as input to the --input command line parameter
:return: string without shap... | 69c497c15172c97037e04dc10641c74f3f51dc4d | 505,094 |
import re
def pretty_label(inStr):
"""
Makes a pretty version of our column names
"zone_1" -> "Zone 1"
"zone_2"-> "Zone 2
...
"zone_strength" -> "Strength"
"""
pattern = re.compile("zone_[12345]{1}|zone_1,2")
if pattern.match(inStr):
out = inStr
else... | 6ca7cb31e7d7996417ba06905cce0ae33709dd7e | 251,088 |
def parse_ip(ip: str) -> tuple:
"""
Returns IP address from str as int tuple
eg: '192.168.43.1' -> (192, 168, 43, 1)
"""
splitted = ip.split('.')
if (len(splitted) != 4):
raise ValueError("Invalid IP format")
ret = []
for num in splitted:
ret.append(int(num))
... | 6eb5d1601e6dd4672b83f3f8ff62603847cc4a65 | 175,204 |
def get_mother_attr(gen_dict, class_dict, key):
"""Get the list of the key value from the class, including mother ones.
Used to get all the properties or method of a class
Parameters
----------
gen_dict : dict
Dict with key = class name and value = class dict (name, package, properties, met... | b7474c8a9f6d9da2848788ece8d99b24c17a523a | 371,447 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.