content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def getDistance(long1,
lat1,
long2,
lat2):
""" getDistance(long1, lat1, long2, lat2)
Get distance betwen 2 coordinates in log/lat.
Parameters
----------
long1 : float
Longitude 1st coordinate.
lat1 : float
... | e37eefd358ae4647d54188e1481589942a7e90c4 | 608,486 |
def convert_binary_to_pm1(matrix):
"""
Convert a 0/1 matrix to a -1/1 matrix.
:param matrix: A binary matrix.
:return: Converted matrix.
"""
converted_matrix = (matrix - 0.5) * 2
return converted_matrix | d16090b9b02b4ca185dffe9403ac2ef11c69b421 | 608,490 |
import io
import zipfile
def _unpack_db(content, db_file):
"""Unpack the sqlite database from a .zip file content."""
zip_contents = io.BytesIO(content)
with zipfile.ZipFile(zip_contents) as zip_file:
inner_file_name = zip_file.namelist()[0]
with zip_file.open(inner_file_name) as zipped_db... | b01f3377008754fdbd075e86e70912497968487d | 608,491 |
def get_type_of_api_response(response):
"""
Takes API response as input and returns the type of the response
whether it is json or xml or text
Arguments:
response: It takes API response as input
Returns:
returns the type of the response
"""
content_typ... | 86f41827223f5acfc7807406e80805e77d9811f6 | 608,493 |
import json
def _get_json(confounds_raw, flag_acompcor):
"""Load json data companion to the confounds tsv file."""
# Load JSON file
confounds_json = confounds_raw.replace("tsv", "json")
try:
with open(confounds_json, "rb") as f:
confounds_json = json.load(f)
except OSError:
... | 8eb30a021010f6d8ec37c8b9c4ce24e1e03af00f | 608,495 |
def log_step() -> int:
"""Log step."""
return 10 | 8c7502bcbad51ead73ff1bc28deb4c15dc80de59 | 608,498 |
import base64
def b64url(value):
"""Return a base64url-encoded str without trailing ='s"""
return base64.urlsafe_b64encode(value).rstrip(b'=') | e350c8f8d3e10836c1ce723c4000cd363e0a2778 | 608,500 |
def isValidPosixFilename(name, NAME_MAX=255):
"""Checks for a valid POSIX filename
Filename: a name consisting of 1 to {NAME_MAX} bytes used to name a file.
The characters composing the name may be selected from the set of
all character values excluding the slash character and the null byte.
... | 9bb1999c8ef1c301697bb090d5570a78dfef1b1f | 608,502 |
def get_iface_speed(iface):
""" Converts iface speed from bps to DNS-friendly string """
speed = iface["iface_speed"]
if speed:
speed = int(iface["iface_speed"])
else:
return None
if speed < 1536000:
return None
elif speed == 1536000 or speed == 1544000:
return "... | 16149a97b76b7f7a61433c665d5ca222c95ec01d | 608,506 |
def print_table(tablelist):
"""
neatly print a table to the terminal
Note: finds out the maximun length of each column then adds whitespace
padding to each of the fields
Args:
tablelist(list): a list of lists each list is a row on the table
Returns:
tablelist(list): inpu... | 968cbb4a3fda6cdf41fd18ae90b0c5cb9fb19253 | 608,510 |
def list_to_dict(dict_list: list) -> dict:
"""
Return a dictionary from a list `[key, value, key_2, value_2...]`
.. code-block:: python
>>> lst = ["A","T", "R", 3]
>>> list_to_dict(lst)
{"A": "T", "R": 3}
Args:
dict_list (list[str]): Dictionary as a list
Returns:
... | 618eda573f49cf4bdacbae4335fc6b3c1bd3e7ed | 608,512 |
def get_widget_by_id(form, widget_id):
"""Get a widget by it's rendered DOM element id."""
# convert the id to a name
name = widget_id.replace('-', '.')
prefix = form.prefix + form.widgets.prefix
if not name.startswith(prefix):
raise ValueError("Name %r must start with prefix %r" % (name, pr... | 1e535e5c35ac3cfd391e8dbc73832cfd74535e1e | 608,514 |
def get_size(bytes, suffix="B"):
"""Scale bytes to its proper format, e.g. 1253656 => '1.20MB'"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
return f"{bytes:.2f} {unit}{suffix}"
bytes /= factor | 381b89eb59e1ea7395c3abdea0275c8184634cb3 | 608,515 |
def get_paramset_type(key: str) -> str:
"""
Return parameterset type from unique key.
:param key: str
:return: str
"""
return key.split(':')[0] | 31368fedef523f812cda09a00003390d9a8d0a5a | 608,516 |
import requests
def pip_installable(pkg_name: str, index_url: str = "") -> bool:
"""Can a package with some given name be "pip installed"?
Results are cached and repeated calls of with function will return
those previously cached results.
:param pkg_name: The name of a package to be checked.
:pa... | 88deb3b52469d965e90c43026ebc146ee5a805ce | 608,517 |
import struct
def boolean(value):
"""Encode a boolean value.
:param bool value: Value to encode
:rtype: bytes
"""
if not isinstance(value, bool):
raise TypeError('bool type required')
return struct.pack('>B', int(value)) | 99da6522c172c482c5790e9e30091c988293f778 | 608,522 |
def remove_nulls(input_dict):
"""Remove keys with no value from a dictionary."""
output = {}
for k, v in input_dict.items():
if v is not None:
output[k] = v
return output | c9bbb885959631644c5ae4822075aea59c0f3a0d | 608,523 |
import torch
def mae_each_forecast_horizon(output: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
"""
Get MAE for each forecast horizon
Args:
output: The model estimate of size (batch_size, forecast_length)
target: The truth of size (batch_size, forecast_length)
Returns: A tens... | 365e9897e952425db06f79f5bf83404a2ed4db2e | 608,528 |
def create_core_state_space_columns(optim_paras):
"""Create internal column names for the core state space."""
return [f"exp_{choice}" for choice in optim_paras["choices_w_exp"]] + [
f"lagged_choice_{i}" for i in range(1, optim_paras["n_lagged_choices"] + 1)
] | 61d4fe1ac728871d9d837307f6bd31041a299873 | 608,530 |
def format_non_null_ratio(rows, nulls):
"""Format percentage of non-null value of the column
Args:
rows (int): number of rows
nulls (int): number of null-values
Returns:
str: non-null ratio with the format '%.2f'.
"""
if rows is None or nulls is None:
return 'N/A'
... | 10ffc72e2021d0b7903f98c6833a448d23525e66 | 608,531 |
def update_parameter(clf, key, value):
"""
Copies clf to a new dict and updates
clf_new[key] = value
Also updates the title by replacing the
placeholder '{key}' by value
"""
# copy old keys and update the current one
new_clf = clf.copy()
new_clf[key] = value
# set title
if 't... | 9e93f7324e8fa7e17be63cce3ffe90d731e4a6de | 608,532 |
def get_car_changing_properties(car):
"""
Gets cars properties that change during a trip
:param car: car info in original system JSON-dict format
:return: dict with keys mapped to common electric2go format
"""
return {
'lat': car['Lat'],
'lng': car['Lon'],
'address': car... | 91b1710088cf2f90a6f7b3c647e9da8398e58e45 | 608,533 |
def h(X, theta):
"""Linear regression hypothesis.
:param X: Features' dataset plus bias column.
:type X: numpy.array
:param theta: Column vector of model's parameters.
:type theta: numpy.array
:returns: The projected value for each line of the dataset.
:rtype: numpy.array
"""
retu... | 554a6b7a4662abed0caf1db728aa152b00661c6f | 608,534 |
def plugin_viewname(model, action):
"""
Return the view name for the given model and action. Does not perform any validation.
"""
return f"plugins:{model._meta.app_label}:{model._meta.model_name}_{action}" | 59d84465a3268cb271dd6f4ec28a75b20711edd1 | 608,535 |
def calc_percent(value: float, total: float) -> float:
"""Calculate a percentage and round to 2dp.
:param value: the value.
:param total: the total.
:return: the percentage.
"""
return round(value / total * 100, 2) | 396d2bbeff6eaf976a7630d745442c7202dfd170 | 608,539 |
def generate_sliding_windows(window_shape, window_strides, image_shape):
"""Generate sliding windows
Args:
window_shape (2-tuple): (h, w)
window_strides (2-tuple): (sy, sx)
image_shape (2-tuple): (H, W)
Returns:
boxes (list of list): (N, 4), where N = (H-h+1)//sy * (W-w+1)/... | 9812aea1758e7319c5ca534bd967904143f10867 | 608,541 |
import re
def _ParseGitRepoPath(repo, subdir):
"""Parses a Git repo path and subdirectory.
Args:
repo: string, a Git repo path.
subdir: optional string. The directory within the Git repo to use.
Returns:
(string, string, string), a tuple of the Git repository, Git ref, and
subdirectory
"""
... | de95d762e96e1000d59a49457957437f159cecf4 | 608,543 |
def transform_recurrent_kernel(kernel):
"""Transforms weights of a single CuDNN recurrent kernel into the regular Keras format."""
return kernel.T | 872c6f8db38cc275fc0fcf87fc59f45955fcd5b7 | 608,547 |
def get_fiscal_year(dt):
"""Get fiscal year from a date."""
if dt.month >= 7:
return dt.year + 1
else:
return dt.year | 0e958e84551be7a6155cc5ebeeeeb47b33707181 | 608,550 |
def create_lecture_collection_slug(video_attributes):
"""
Create a name for a collection based on some attributes of an uploaded video filename
Args:
video_attributes (ParsedVideoAttributes): Named tuple of lecture video info
"""
return (
video_attributes.prefix
if not video... | 2637fc24c23a027c9749c2ea35c7b157c9888555 | 608,551 |
async def multiply(first:int, second:int):
"""Multiplies the two numbers."""
return first * second | dab9ea6cc3c38a668c2f2442e022c6042f90f1b6 | 608,554 |
import torch
def concat(*args, dim=-1):
"""Wrapper to torch.cat which accepts tensors as non-keyword
arguments rather than requiring them to be wrapped in a list.
This can be useful if we've built some generalized functionality
where parameters must be passed in a consistent manner.
Parameters
... | 6f3253875e59f6b6a5369307ba8eb025a67a4bc9 | 608,555 |
def optionally_prefixed_path(path, prefix):
"""Returns a path with an optional prefix.
The prefix will be treated as an ancestor directory, so for example:
```
optionally_prefixed_path("foo", None) == "foo"
optionally_prefixed_path("foo", "bar") == "bar/foo"
```
Args:
path: The path... | bae2131142aee593e336692b3de2cb6e5a4fdf06 | 608,556 |
from typing import List
def extend_interval(interval_to_extend: List[int], interval: List[int]) -> List[int]:
"""Extends an interval to encompass another.
Args:
interval_to_extend: The interval to extend.
interval: The interval to extend by.
Returns:
A new interval with the same st... | 9aeb644056d8ec8397926ff48727a3b846abf96e | 608,557 |
def extract_id(url):
"""
:param url like http://data.finlex.fi/ecli/kko/1998/138:
:return: 1998_138
"""
splitted = url.split('/')
return splitted[-2] + '_' + splitted[-1] | 3b788be247bb7039b419a79fa0216459b078e552 | 608,561 |
def GetComment(plist, comments):
"""Get comment for a given property list."""
try:
label = plist["Label"]
except KeyError:
return None
if label in comments:
return comments[label]
return None | bb21c28d932da42cb06311ae09bab846a6edabd7 | 608,564 |
def yr2sec(time):
"""Converts time from years to seconds."""
return time * 60.0 * 60.0 * 24.0 * 365.25 | 27f9900b6968cfe0b54550f317550e58afde04da | 608,565 |
def find_insertion(lines, insert_regex):
###############################################################################
"""
Find the index that matches insert_regex. If not found, return None
>>> lines = ["foo", "bar", "baz", "bag"]
>>> find_insertion(lines, re.compile("baz"))
2
>>> find_inser... | 8367548361c259f65257803acb5791f451272129 | 608,572 |
import ast
def str_to_attr(argument):
"""Convert string to attribute."""
out = argument
try:
out = ast.literal_eval(argument)
except Exception:
pass
return out | 17f816ac1b6327608b07f996a081b38660070e53 | 608,575 |
def generate_parameter_field_number(parameter, used_indexes, field_name_suffix=""):
"""Get unique field number for field corresponding to this parameter in proto file.
If field number is not stored in metadata of parameter, get the next unused integer value."""
field_name_key = f"grpc{field_name_suffix}_field_... | 970f65f4ed2e9a4ccb8bfd44a78b5a55ff035bf7 | 608,576 |
def SplitLines( contents ):
"""Return a list of each of the lines in the unicode string |contents|."""
# We often want to get a list representation of a buffer such that we can
# index all of the 'lines' within it. Python provides str.splitlines for this
# purpose. However, this method not only splits on newli... | deb0ff55217c18ff78443667d22f23f740945733 | 608,578 |
def compute_features(fe,frames,phashes,phash_thresh=1):
"""Get vector embedding using FeatureExtractor
:param fe: FeatureExtractor class
:param frames: list of frame images as numpy.ndarray
:param phash_thresh: perceptual hash threshold
:returns: list of feature vectors
"""
vals = []
phash_pre =... | 1a1d1b3a3584877e08d2d255f61eff96de0c5af1 | 608,579 |
def kvp_escape_string(val):
"""
Escapes the input string to be safe for use as a key or value.
:param str val:
:return: escaped string
"""
return str(val).replace('%', '%%') | 2d3910a625d0c126b33bf47ed134ad9f727d3a73 | 608,580 |
def ideal_share(share, total_shares, total_alloc):
"""
Calculate the ideal share of proportions and totals.
Parameters
----------
share : int
The proportion to be checked.
total_shares : int
The total amount of shares.
total_alloc : int
The ... | 9f3f2924c66538087a16ae9714dd19b66fc5c3a9 | 608,583 |
def getcount(inputstr):
"""Function counts num of vowels in string."""
vowels = ['a', 'e', 'i', 'o', 'u']
count = 0
for letter in inputstr:
if letter in vowels:
count += 1
return(count) | 3576c0177fe861f9123704e306fd9b8c1919ab04 | 608,589 |
def get_train_val_split_from_idx(src, val_list):
"""
Get indices split for train and validation subsets
src -- dataset size (int) or full range of indices (list)
val_list -- indices that belong to the validation subset
"""
train_idx = []
val_idx = val_list
if not hasattr(src, '__i... | 8b3e579a884069287e78dd023a91f5f6517f5bcc | 608,592 |
def _get_name(type_, value):
"""Returns the name for the given value of the given type_ unless value is
None, in which case it returns empty string"""
return type_._VALUES_TO_NAMES[value] if value is not None else "None" | 3b10e7f761d4796d3d4bc4ff40c76cd78cb4358e | 608,593 |
def input_yes_no(default='y'):
"""
Demand user input y[es] or n[o].
The user is asked repeatedly, until the input is valid.
Parameters
----------
default : {``'y'``, ``'n'``}, optional
The output if the user enters empty input.
Returns
-------
inp : {``'y'``, ``'n'``}
... | 9aca3cd92aa286f9c02dc0f4db8020f2d013f4e1 | 608,594 |
import sndhdr
def is_wav(fn):
"""Returns True if ``fn`` is a WAV file."""
hinfo = sndhdr.what(fn)
if hinfo is None:
return False
elif hinfo[0] != 'wav':
return False
return True | d2fd1ac897406791a89b9cd8b198b2eb75718f09 | 608,598 |
def repr_args(args, dlim=", ", start=None):
"""
Represent arguments.
Parameters
----------
args : Iterable[Any]
Arguments.
dlim : str, optional
Delimiter. The default is ", ".
start : str, optional
Start of return value. Defaults to delimiter value.
Examples
... | fac8edecbf0d0ef5dbd87d6d072f0e9737afade2 | 608,600 |
def str_if_not_none(value):
"""Return the string value of the argument, unless
it is None, in which case return None"""
if value is None:
return None
else:
return str(value) | a0494eef2b192f3a4f2ed312c61aefdfaa7155e4 | 608,601 |
def filter_not_empty_values(value):
"""Returns a list of non empty values or None"""
if not value:
return None
data = [x for x in value if x]
if not data:
return None
return data | c4f927b3faeb201a70c99654a404011083d3658d | 608,602 |
import typing
def AssembleIssuerData(row: typing.List[str]) -> typing.Dict:
"""
入力文字列をdictに変換する。json出力用
下記は、Profileとあるが、Issuerと同じ。
Open Badges v2.0
https://www.imsglobal.org/sites/default/files/Badges/OBv2p0Final/index.html#Profile
{
"@context": "https://w3id.org/openbadges/v2",
... | cffa4e74ae1350ef1e31ad1c402cf3da34d51c38 | 608,605 |
def _connect(session):
"""Connect to securitas."""
session.connect()
return True | 0599edd5f75e0ee9b06c6bf80d2d0496ba431144 | 608,606 |
def induce_subgraph(G, node_subset):
"""
Induce a subgraph of G.
Parameters
----------
G : networkx.MultiDiGraph
input graph
node_subset : list-like
the subset of nodes to induce a subgraph of G
Returns
-------
H : networkx.MultiDiGraph
the subgraph of G ind... | 952dea186a93dacdbabda64d64484c6d4aebf889 | 608,607 |
def _clamp(value):
"""Clamps value to range [0.0, 1.0]."""
return min(max(0.0, value), 1.0) | 4abf24b9d65bc381937ee6d8d6473c936189f89c | 608,610 |
from typing import OrderedDict
def load_mhd_header(filename):
"""Return an OrderedDict containing metadata loaded from an mhd file."""
metadata = OrderedDict()
with open(filename) as header_file:
for line in header_file:
(key, val) = [x.strip() for x in line.split("=")]
i... | f69031727735f0279c895aea2d70701efbfe0a38 | 608,613 |
def split(df, target):
"""Split off target col to make X and y"""
if not isinstance(target, list):
target = [target]
return df.drop(columns=target), df[target].values.ravel() | 1d0c03c5a4dfd5ced9f609e9f39368a7848755b1 | 608,614 |
import re
def str_pattern_valid(sname, pattern_group):
"""
Whether the sname matches the pattern in pattern_group
"""
for patt_str in pattern_group:
pattern = re.compile(patt_str)
match = re.match(pattern, sname)
if match is not None:
return True
return False | b9f86b58a068d88a9defeb279ab1a9a24cec9fdf | 608,616 |
def test_results_to_score(test_results, verbose=True):
"""Calculate a score from 0-100 based on number of failed/total tests"""
tests_failed, tests_total = test_results
tests_passed = tests_total - tests_failed
score = int(100 * tests_passed / tests_total)
if verbose:
print("Score: %d/100" %... | a78fe56425f1abcaa2d3d99112492119b9982f29 | 608,618 |
import random
def cxOrdered(ind1, ind2):
"""Executes an ordered crossover (OX) on the input
individuals. The two individuals are modified in place. This crossover
expects :term:`sequence` individuals of indices, the result for any other
type of individuals is unpredictable.
:param ind1: The first... | 9b4b42b7ef1844f18e0fde1eba4fbb0cd75ed67e | 608,619 |
def get_sampling_interval(func_img):
"""
Extracts the supposed sampling interval (TR) from the nifti file header.
@param func_img: a NiBabel SpatialImage
@return: float
The TR value from the image header
"""
return func_img.get_header().get_zooms()[-1] | 3d6fde44996377bc6ed06645a1e2471084493fff | 608,622 |
from pathlib import Path
def executable(dir_chrome: Path, chrome_version: str) -> Path:
"""Get file path for current env executable."""
return dir_chrome / "install" / chrome_version / "chrome-linux" / "chrome" | 463641126eb86b511a444c77fbbdc47470e8a2da | 608,624 |
from typing import Callable
def iter_dct(dct: dict, operation: Callable):
"""Recursively iterate the dictionary and operate on the leaf nodes. Return the processed dictionary."""
dct2 = dict()
for key, value in dct.items():
if isinstance(value, dict):
dct2[key] = iter_dct(value, operat... | dc74ba2c9baa14cbdefb3243e732e4cd7b9b8f66 | 608,629 |
import random
def gen_port(num=1):
"""
Generate a port number or a list
"""
ports_list = [random.randrange(10000, 60000) for x in range(num)]
if num == 1:
# s.bind((Network.get_ip(4), 0)) is enough
return ports_list[0]
else:
return ports_list | aba2ad59d7d4154bbdb7c4379815fa723ac28052 | 608,630 |
from typing import Iterable
from typing import Set
def multi_union(sets: Iterable[Set]) -> Set:
"""Union of multiple sets."""
return set().union(*sets) | 0f876a97c779efd252143e174494aea36ad8fe6b | 608,632 |
def is_all_char(s, ch):
"""
All characters in 's' are 'ch'.
"""
for c in s:
if c != ch:
return 0
return 1 | ae7754beede4b340d30419d90d8e65d69b4f11a3 | 608,634 |
def Pluralize(count, singular='', plural='s'):
"""Return the pluralization suffix for "count" item(s). For example:
'item' + Pluralize(1) = 'item'
'item' + Pluralize(2) = 'items'
'activit' + Pluralize(1, 'y', 'ies') = 'activity'
'activit' + Pluralize(0, 'y', 'ies') = 'activities'
"""
r... | 385da9729d5088374a09250001da4bfa3c206644 | 608,636 |
def find_percent_val(minval, maxval, percent):
"""Find the value that is the desired percent between a min and max number.
minval -- The low number of the range.
maxval -- The high number of the range.
percent -- A number between 0.0 and 100.0."""
if not 0.0 < percent < 100.0:
print("\n" + "... | 7f8ccc88332be063d7f38f6d2d6ecb938fc6a93a | 608,642 |
def read_file(path, mode="r"):
"""Read data from a file.
Args:
path (str): path to the file.
mode (str): mode which the file will be open.
Returns:
(str): contents of the file.
"""
with open(path, mode) as f:
return f.read() | d33ae08aef692baa0037e94f099ee9f354f507db | 608,644 |
def scan_lis_w_data(cdl_scanner):
"""
A scan for a small 2d mesh including an LIS.
"""
test_cdl = """
netcdf data_C4 {
dimensions:
faces = 3 ;
nodes = 6 ;
lis_faces = 2 ;
face_n_vertices = 4 ;
variables:
double sample_data(lis_faces) ;
sa... | 17ec1b11ef538de994ddc8a3f6e0d6cf35dfd660 | 608,646 |
import copy
def ApplyFunToRadii(fiber_bundles, fun):
"""
Applies function to fibers radii
Parameters
----------
fiber_bundles : [[(,4)-array, ...]]
list of fibers
fun : function
Returns
-------
res : [[(,4)-array, ...]]
fiber_bundles
"""
fiber_bundles = c... | a562df71107c6f0f856e3c0d967107b44eddb782 | 608,649 |
def repeated(f, n):
"""Return the function that computes the nth application of f.
>>> def increment(x):
... return x + 1
>>> def square(x):
... return x**2
>>> def triple(x):
... return x*3
>>> add_three = repeated(increment, 3)
>>> add_three(5)
8
>>> repeated(tr... | 23d19e739e9406e5bb967d71c7a90ca212473b6a | 608,652 |
def _format_experiment_run_resource_id(experiment_name: str, run_name: str) -> str:
"""Formats the the experiment run resource id as a concatenation of experiment name and run name.
Args:
experiment_name (str): Name of the experiment which is it's resource id.
run_name (str): Name of the run.
... | c61c866ac34943c178410173577aee54bc170616 | 608,653 |
import requests
def get_csv_zip_url(table_id)->str:
"""
Returns the url for a table_id to extract raw data from Stats Canada.
Parameters
--------
table_id : int
Statistics Canada Table ID
Returns
--------
str
http address for downloading zipped csv file
Refer... | 9292c2e09f2c29f1c234499e7a0632b5c5605c58 | 608,654 |
def add_variables(df):
"""Create helper variables."""
y = df.transaction_date.dt.year * 100
m = df.transaction_date.dt.month
df['ym'] = y + m
return df | 53c8524267e9b8464c4141d5ff2b539eae162d3a | 608,655 |
def _IsDigest(url):
"""Return true if the given image url is by-digest."""
return '@sha256:' in url | 25b1d9416ac935611c54f46fe772bda23027d44c | 608,656 |
from typing import List
def _add_docstring_to_top_level_class_method(
line: str, docstring: str) -> str:
"""
Add docstring to the line string of top-level class's method.
Parameters
----------
line : str
Target class's method line string.
e.g., ` def sample_method(self)... | 212f4f13bab4eb5540c8623334966656782e701d | 608,657 |
def bare_name(msg_type):
"""
Get bare_name from <dir>/<bare_name>[x] format
"""
bare = msg_type
if '/' in msg_type:
# removing prefix
bare = (msg_type.split('/'))[1]
# removing suffix
return bare.split('[')[0] | 8d57e55a4fb41e0ffda54489c38950382a8fab03 | 608,658 |
def holes(diagram):
"""
Calculates the rank of the free group of a connected graph
Equal to #edges - #vertices + 1
"""
return diagram.num_edges()-diagram.num_verts()+1 | 6925c32688a4a9edb3984dfac415b73a5446d1cd | 608,661 |
def calculate_slpercentage_base_price_long(sl_price, base_price):
"""Calculate the SL percentage of the base price for a long deal"""
return round(
100.0 - ((sl_price / base_price) * 100.0),
2
) | 4ff6591836e2b97048aa70c3ee9619b71b84ec6c | 608,662 |
from typing import List
def render_subcommand_completion(current_command: str, commands: List):
"""Renders case statement for subcommand completion."""
return """
({current_command})
coms="{commands}"
COMPREPLY=($(compgen -W "${{coms}}" -- ${{cur}}))
__ltrim_colon_completions "$cur... | cb299292abda47eca4211a20728ef52041676eaa | 608,665 |
def format_task_config_key(config_parameter):
"""
Format the name of config parameter to be included as in the final task config, without any language references
(because the names of parameters in Luigi tasks are language agnostic).
:param config_parameter: Name of config parameter.
:type conf... | e3e427ff4a04e2ea9767cee5ffbdcbfce1927528 | 608,666 |
import torch
def euclidean_dist(x, y):
"""
Distance calculation between two sets of vectors x (n x d) and y (m x d)
"""
n = x.size(0)
m = y.size(0)
d = x.size(1)
assert d == y.size(1)
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)
return torch.pow(x... | 31d1e60eac411e87b8c269a713b86b16ef7aa481 | 608,669 |
def update_state_dict(original_state_dict, dataparallel=False):
"""
Add or keep 'module' in name of state dict keys, depending on whether model is
using DataParallel or not
"""
sample_layer = [k for k in original_state_dict.keys()][0]
state_dict = {}
if not dataparallel and 'module' in samp... | fc388f80bbaaa5c615a21991a93a73cfc1b0bf08 | 608,673 |
def right_strip_lines(lines):
"""Remove trailing spaces on each line"""
return [line.rstrip() for line in lines] | 76fe5480248b7fef05c0ed8094d608b0b8fb70f6 | 608,676 |
import random
def randstr() -> str:
"""return a random string, e.g. test-xxx"""
return f"test_{str(random.randint(1, 10000000))}" | 1829feb0cabefd7d5e22ca7e7174b115e1e6f3b7 | 608,681 |
def GetInnerHtml(soup, tag, id):
"""
Searches the soup for the given tag+id, and returns the inner HTML, or an empty string when the tag+id doesn't exist.
soup - BeautifulSoup object for the page
tag - The tag type to search for
id - The ID attribute of the tag
"""
t = soup.find(tag, {"i... | 5611b067c8f55b8f15fd720344ce659a8e5a3760 | 608,683 |
import functools
def loading(btn, alert):
"""Decorator to execute try/except sentence
and toggle loading button object
Params:
btn (v.Btn): Button to toggle loading
alert (sw.Alert): Alert to display errors
Example:
class A:
# ...
... | 19270e75f57186062153bfa085cbe088efe8bc09 | 608,684 |
def extend_knots(internal_knots, k):
"""
Extend the knots sequence to add the external knots. This is done because
:meth:`extract_coeffs_knots_from_splines` returns only the internal knots.
Therefore they should be extended on both sides by **k** knots.
:param internal_knots: [array] containing the... | d4d33a5c47f7c30bde9c60e4ac15f56f44eb5446 | 608,685 |
def is_within_bbox(lon: float, lat: float, bbox: list[float]) -> bool:
"""
Checks if lon / lat coordinate is within a bbox in the format of [min_lon, min_lat, max_lon, max_lat]
"""
return bbox[0] <= lon < bbox[2] and bbox[1] <= lat < bbox[3] | 322b45cd20bddeca2c8f72245a0380968495ecfd | 608,686 |
def get_X_y(df, target_name):
"""Split DataFrame to feature and target
Parameters
----------
df : DataFrame
target_name : str
Name of target column present in DataFrame
Returns
-------
X : DataFrame
Original DataFrame without target column
y : Series
... | b5ff7c3db720ad7e3ab597b5e2d64ecde91beeca | 608,687 |
def url(anchor, uri):
"""Return a Markdown URL."""
return f"[{anchor}]({uri})" | 330bb36a77e40b62ad33d897f6043e825f1fb156 | 608,692 |
def iterable(obj):
"""
Grabbed from Python Cookbook / matplotlib.cbook.
Returns true/false for *obj* iterable.
"""
try:
len(obj)
except:
return False
return True | 8f6f17fe595f1f83d8262e44809b9ab74d539fd2 | 608,693 |
def _ssl_cn(server_hostname):
"""
Return the common name (fully qualified host name) from the SERVER_HOSTNAME.
"""
host_port = server_hostname.rsplit(":", 1)
# SERVER_HOSTNAME includes the port
if len(host_port) == 2:
if host_port[-1].isdigit():
return host_port[-2]
ret... | 428c7623b282caef5bd23e76cdce0bbf663837ea | 608,697 |
import math
def sigmoid(x: int) -> float:
"""Calculate the sigmoid function
Args:
x (int): the x value for the sigmoid function
Returns:
float: f(x) of the sigmoid function
"""
return 1 / (1 + math.exp(-1 * x)) | 81cf2bbf2fc8f530ef512ccd12b44178f6eadc08 | 608,698 |
def setupKillProcess(setupBasicExecutable, mocker):
""" Setup for tests of killing a process.
Returns:
tuple: (executable, expected, mGetProcess, mKill) where executable is an executable object and expected are
the expected parameters, mGetProcess is the mock for ``executable.getProcessPID(... | 815622aadc45dc6ffb4ab708be2b47bec9afc1e5 | 608,699 |
def get_min_max_box(box):
"""
Get x_min, x_max, y_min, y_max, z_min, z_max from boxes
Input: box, a 3-by-8 matrix, each coloum represents the xyz coordinate of a corner of the box
(e.g.
array([[42.62581635, 46.09998703, 46.09998703, 42.62581635, 42.62581635, 46.09998703, 46.09998703, 4... | 71f8e22d48ac78819c613588ac7adb1e6ced28cf | 608,703 |
def get_default_attr(obj, name, default):
"""Like getattr but return `default` if the attr is None or False.
By default, getattr(obj, name, default) returns default only if
attr does not exist, here, we return `default` even if attr evaluates to
None or False.
"""
value = getattr(obj, name, def... | 4932beac6b33e2995088a222a15c9d281e772be5 | 608,704 |
def gauss_sum(a, b):
"""Sums a sequence of integers from `a` to `b`
- https://everything2.com/title/Gaussian+formula
- https://en.wikipedia.org/wiki/Gaussian_function
- https://en.wikipedia.org/wiki/Gauss_sum
"""
return ((a + b) * (b - a + 1)) / 2 | 12fe0672407d958f85527796f58273be2b50de06 | 608,706 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.