content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_tweet_rating(tweet):
"""
Function that count tweet rating based on favourites and retweets
"""
return (tweet['retweet_count'] * 2) + tweet['favourites_count'] | 55bd61c49bc3018b2706a824a8724f450f86e1e1 | 686,984 |
def ordinaryAnnuity(pymt, p, r, c, n):
"""Ordinary annuity formula
Returns: future value
Input values:
pymt : payment made during compounding period
p : principal
r : annual interest rate
c : number of compounding periods in a year
n : total number of payments
"""
blo... | 3f31db7d1590d069ee1c69c867ee2285fa753080 | 686,985 |
def ext_euclid(x, y):
"""
Returns (g, a, b) such that g = gcd(x, y) = ax + by
"""
if y == 0:
# gcd = x and gcd = x = (1)x + (0)y
return (x, 1, 0)
else:
# Recursively, g = a1 * (y) + b1 * (x % y)
(g, a1, b1) = ext_euclid(y, x % y)
# a1 * (y) + b1 * (x % y) = b1... | d92b036b5c872d10dcda18d19397fec7feb203b7 | 686,986 |
def is_date_conflict(cls, pk, **kwargs):
"""期間が重複しているかどうか
:param cls: 検索対象となるテーブルクラス
:param pk: 変更の場合は主キー、追加の場合は None
:param kwargs: 検索条件
:return:
"""
qs = cls.objects.filter(**kwargs)
if pk:
qs = qs.exclude(pk=pk)
return qs.count() > 0 | 0841e4769ef873ab551f3d201af5e92f7c7de491 | 686,987 |
def get_leap_seconds(current_epoch):
"""
Computes the number of leap seconds passed since the start of GPST
:param current_epoch: current datetime value representing the measurements epoch
:return: number of leap seconds since GPST
"""
return None | 7a2308e17bb30744ce0bfa8d8c935288fb638451 | 686,988 |
def _dual_var_for_layer(dual_var_getter, layer, name, shape):
"""Creates a dual variable for the given layer shape.
Args:
dual_var_getter: Function(name, shape) returning a dual variable.
layer: Layer for which dual variables should be generated.
name: Name to use for dual variable.
shape: Shape of... | c888ad63a252a79395017ecda5ebf86350616f5d | 686,990 |
import time
import sys
def start_loading(max_loading_time, exit_condition_checker=None,
message='', max_number_of_dots=15):
"""Start and show the loading message, append dots to the end
of the message up to a certain number of dots and repeat.
Args:
max_loading_time (int): Loadi... | c7521e2309bd469eda81f5e667b2b1ecbbc1f748 | 686,991 |
import re
def readable_regex(regex):
"""Make regular expressions more readable
(probably not a good general solution but works for the name regexps)
Note that the caron designates markup where it could be confused with the
literal character. Messy but understandable.
"""
COMB = "\N{COMBINING... | 5ccf2c567a0cf5834c9beb77e9727db3e7c026c6 | 686,992 |
import ipaddress
def _check_values(line_value_list):
"""
Verify the values of each field of the line being processed.
:param line_value_list: contains the line transformed to a list
:return: ``line_value_list`` with corrections, or ``False`` if the list has an invalid value.
"""
_OS_LIST = ... | 8c6bba295fe6de47cd8902b2842aa4e298a42da4 | 686,993 |
def shell_config(shell):
"""
Returns a dict in the following form, depending on the given shell:
return {
'prefix': '<preffix-to-use>',
'suffix': 'suffix-to-use',
'delimiter': '<delimiter-to-use>',
}
Logic from Docker Machine:
https://github.com/docker/machine/blob/master... | 7909990038ccf2b13b9ed883f7a95b1802397230 | 686,995 |
def scramble(password, operations):
"""Scramble a string via a list of operations."""
pass_list = [char for char in password]
for operation in operations:
parse = operation.split(' ')
if parse[0] == 'swap':
if parse[1] == 'position':
temp = pass_list[int(parse[2])... | 4d9462eaa59513068fc0c24c0009f1bb87713f7f | 686,997 |
import re
def format_symbol(symbol):
"""HGNC rules say symbols should all be upper case except for C#orf#. However, case is
variable in both alias and previous symbols as well as in the symbols we get in
submissions. So, upper case everything except for the one situation where mixed-case
is allowed, w... | a995a46965bc75b21388a0bf382092dfe02c3ef0 | 686,998 |
import os
import glob
import csv
def read_data(path: str, extension: str = ".csv"):
"""
Function reads all data from path, can be single file or directory.
:param path: str -> Path of file or directory.
:param extension: str -> extension type of files to read, preset to .csv files.
:return: list, ... | a2d5e16732e6ef33aa1bff9eb562602db0f9b2c1 | 686,999 |
def get_conv_layers(model):
"""FUNCTION::GET_CONV_LAYERS:
---
Arguments:
---
>- model {keras.Models} -- A model to get the parameters.
Returns:
---
>- {list[string]} -- layer Names.
>- {list[tensor]} -- layer Outputs.
>- {list[tensor]} -- layer Weights."""
layerNames = []; layerOutputs = []; layerWe... | 694d2b7c6a1f0059f3736f50acc25154691226e9 | 687,000 |
def build_tr_create_module_page_link(region, module_type_id):
"""
Build the direct link to the corresponding Threat Response page in the
given region for creating a module of the given type.
"""
if module_type_id is None:
return 'N/A'
return (
f'https://securex.{region}.securit... | bde4888194beb532b82e6e2e0cb7c428b7005ac5 | 687,001 |
def space_to_depth_x2_output_shape(input_shape):
"""Determine space_to_depth output shape for block_size=2.
Note: For Lambda with TensorFlow backend, output shape may not be needed.
"""
return (input_shape[0], input_shape[1] // 2, input_shape[2] // 2, 4 *
input_shape[3]) if input_shape[1] el... | 8147b02b489c874291df1bdecdf6a8d3535e2d28 | 687,002 |
def _message_with_time(source, message, time):
"""Create one line message for logging purposes.
Parameters
----------
source : str
String indicating the source or the reference of the message.
message : str
Short message.
time : int
Time in seconds.
"""
start_m... | b9afb954995eb5aa1e89fb6179e1d38c55cdd0b5 | 687,003 |
from typing import Tuple
def post(body) -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", body) | 44ad395de398f548a201446280696f67bfe010c9 | 687,004 |
def get_layer(layer_str, model):
"""get model lyaer from given str."""
cur_layer = model
assert layer_str.startswith(
'model'), "target-layer must start with 'model'"
layer_items = layer_str.strip().split('.')
assert not (layer_items[-1].startswith('relu')
or layer_items[-1].... | 3ed29cd1f58ee5fbb863990ebead43b473323bc0 | 687,005 |
import re
def get_human_from_docstring(doc):
"""
:param doc: if True, also return the 'human name'
:type doc: string
:return: a dictionary of name_* keys/values from the docstring.
:type return: dict
"""
doc = doc.replace(' ', '')
res = re.findall('human_(.*):(.*)', doc)
return... | 3a319df4869502d48a6472a84737c7d90c5c2229 | 687,006 |
def get_group_data_value(data_list, field, value_list=False):
"""to find the field value in group api call
return whole list of values if value_list is True
"""
for entity in data_list:
if entity["name"] == field:
entity_value = entity["values"]
if not entity_value:
... | 770b6ccb6f757762e997c6e6a2ddc463d3769f7c | 687,007 |
import numpy
def calculate_frequency_weighting(frequency, weighting):
"""
Calculates the weighting in [dB] for a given frequency.
"""
if weighting == 'A':
a = numpy.power(12194.0, 2) * numpy.power(frequency, 4)
b = (numpy.power(frequency, 2) + numpy.power(20.6, 2))
c = (numpy.... | f51586a80d14f15fb83224a61f7c4c61d199a6ad | 687,008 |
import re
def parse_styles(text):
""" Parse styles into html """
# Style regex (finally made the regex work, phew)
# Big thanks to the Patterns macOS app, because it
# helps to see if the regex is really doing what it
# is intented to do.
bold = re.compile("\\*{2}([a-z]+)\\*{2}", re.UNICODE)
... | c611ced733cbd7a4569c715ca59a2862385f0a36 | 687,009 |
def read_file(file_name):
""" Builds the raw data list by reading the text file named by file_name
input: string
returns: list
"""
with open(file_name) as f:
ds = f.readlines()
raw_list = ''.join(ds).split('>')[1:]
lc = len(raw_list)
if lc < 2:
print('Input data e... | 9bceda85852f56e19cba7c41ad2c9171afe67d63 | 687,011 |
def is_shape_subset(sub_shape, full_shape):
"""
"""
if len(sub_shape) > len(full_shape):
return False
for i in range(len(sub_shape)):
ind = -1 - i
if sub_shape[ind] != 1 and sub_shape[ind] != full_shape[ind]:
return False
return True | 46747fd944dcdf99357d1e4f2d19e2f1288463e0 | 687,012 |
def get_I(arrs):
"""
Extract and return the indices cudf
:param arrs:
:return:
"""
return arrs[0] | ecce68be71a1095c9014c0e723b4bf7943d6f938 | 687,013 |
import heapq
import sys
def topo_sort(graph):
"""
The algorithm keeps track of all the nodes that have no outgoing edges.
Of the nodes with no outgoing edges, the one with the minimum value is
removed from the graph and added the list containing the topologically sorted
nodes.
Once the node is... | d21e540175cab83e2879c61a63738f196c36d03a | 687,014 |
import bisect
def leftmostBinSearch(vec, val):
"""
Return the leftmost position in the vector vec of val. If val is
absent then we return the lefternmost position for the value:
max(vec[vec < val]). The time complexity here is potentially worse
than log(n) because of the extra step of walking back... | cfa15da61aff3b293cbd170c3522fe8b91afac3a | 687,015 |
def computeHSL(hexValue):
"""
Given a six-digit hex code (no #), compute the hue, saturation, and
luminosity. Returns a list consisting of the hue, saturation, and
luminosity values. Hue is a (float?) between 0 and 360, luminosity and
saturation floats between 0 and 1
"""
red = int('0x' + h... | ec642fa1fdfe32cd36444267e9dd21bc96766e1a | 687,016 |
def inverse(x):
"""Compute the inverse of x if x not null."""
if x != 0:
return 1 / x
else:
return 10e10 | 30ab6eb2e85205cd5154fad431cb3ad2dc353647 | 687,017 |
def last_player(played_cards, players):
"""
Return person who played the last card.
E.g.:
last_player([(1, "S"), (2, "S")], ["Abi", "Bob"])
returns: "Bob"
Args:
played_cards (list):
players (list):
Returns:
return (str): The players name
"""
... | 792f4b749f1dbc64dbc34b4c78e50cb847a63fe1 | 687,018 |
def compute_balmer_dec(row):
"""Calculate the Balmer decrement and error, given a row in the emission_df
Parameters:
row (pd.DataFrame): A row from the emission_df with nonzero HA and HB
Returns:
"""
balmer_dec = row['HA6565_FLUX'] / row['HB4863_FLUX']
balmer_dec_err = balmer_dec * \
... | adfa37bfbd301b10ce68e51cf499beacde69998a | 687,019 |
import os
from pathlib import Path
def data_taxes():
"""Fixture with discounts file path."""
datadir = os.getenv('TOM_DATA', '')
return Path(datadir) / 'taxes.csv' | fd2446eb06126a322f7c2a0dbb1b5f89db4fa831 | 687,020 |
def trgiantsp(stride_index, pivot, stride, c_s1, bounds, sogsp):
"""
Compute giant steps.
stride_index: int
pivot, stride: element
"""
pivot_index = bounds[0]
# pivot == x[1] ** pivot_index
# stride = x[1] ** stride_index
while True:
for tpw in sogsp.retel():
ret... | 432d0ea475d62572747238afcf5aa1d0d222f94f | 687,021 |
def MAINE(N, A, B):
"""
MAINE: MAtrix INversion by Escalator method (symmetric matrix)
p. 11
"""
B[0] = 1.0 / A[0]
if (N==1):
return B
NN = N * N
for I in range(1, NN):
B[I] = 0.0
for M in range(1, N):
K = M
MM = M + M * N
EK = A[MM]
# ... | ae61f3c60d9f67b64082b5ce511196ba1f40c066 | 687,022 |
def productExceptSelf(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
arr = [1]
for num in nums[:-1]:
arr.append(num*arr[-1])
tmp = 1
for i in range(len(nums)-1, -1, -1):
arr[i] = arr[i]*tmp
tmp = tmp*nums[i]
return arr | 6f9a5c6cefd19c90a5ad43d6b0b119564ecbaebe | 687,023 |
import hashlib
def CalculateMD5Checksum(filename):
"""Calculate the MD5 checksum for filename."""
md5 = hashlib.md5()
with open(filename, 'rb') as f:
data = f.read(65536)
while len(data) > 0:
md5.update(data)
data = f.read(65536)
return md5.hexdigest() | 3108bbd28b80f5fc719c9e09f04e8e28f1251cb9 | 687,024 |
def custom_replace_album(artist, album):
"""Make custom spelling replacements to the album"""
# contains artist name already?
if artist in album:
return album
keywords = ("best", "classic", "collection", "definitive", "essential",
"greatest", "live", "hits", "singles", "ultimate"... | 60361f091a13c0935d873315fb25a5b99a29f9b9 | 687,025 |
def return_spro_ch_info():
"""returns array of possible channel parameters for SymphoniePRO txt export files"""
array = [
'Channel:',
'Export Channel:',
'Effective Date:',
'Type:',
'Description:',
'Serial Number:',
'Height:',
'Bearing:',
'... | 1ada7802824e2c4490a25fdbacdd1dd53c0cbc73 | 687,026 |
import os
def center_text(text):
"""
Calculates center based on text length
"""
total_terminal_columns = os.get_terminal_size().columns
text_length = len(text)
space_on_one_side = (total_terminal_columns - text_length)//2
space = " " * space_on_one_side
return space + text + space | 28e16110bebb44420ee0201c772f3e3fb1588668 | 687,028 |
import sys
def ex2_parameters(parameter_lists, test):
"""let the arc task array choose experiment parameters to run
Parameters
----------
test : bool
if test is true we choose some simple parameters to run on arc.
this is to test the file works and produces results before running
... | 46248243e3ee6aed63d79d4161ae97a561f1a2e2 | 687,029 |
import os
def image_path_from_index(index):
"""
Construct an image path from the image's "index" identifier.
"""
# set the prefix
prefix = 'training/image_2/'
data_path = '../data/KITTI/object/'
# lidar_bv_path = '$Faster-RCNN_TF/data/KITTI/object/training/lidar_bv/000000.npy'
image_pa... | 21c41992442b08c733787ef241bd053767d44747 | 687,030 |
import subprocess
import re
def detect_cuda_version():
"""
return a tuple with major and minor version
"""
nvcc_out = subprocess.check_output('nvcc --version', shell=True)
if not nvcc_out:
return None
m = re.search('release ([0-9]+)\.([0-9])', str(nvcc_out))
if not m:
retur... | 603602ce14a3c97cae5651ebd00ddf7899c84ef6 | 687,031 |
def nullify(data: dict) -> dict:
"""
Nullify empty strings in a dict
"""
for key, val in data.items():
if val == "":
data[key] = None
return data | 69fab1a74ab8bfcdab2a9f17e9ba8aa7da2e801c | 687,032 |
import os
def mkdir(path):
"""Make a directory in a particular location if it is not exists, otherwise, do nothing.
Parameters
----------
path : str
The path of a file.
Examples
--------
>>> mkdir('/home/UserName/test')
>>> mkdir('test/one')
>>> mkdir('../test/one... | af8bfe9805ffe7c50322f78f1b3c52b34ac251de | 687,033 |
def compute_chunksize(src, w, h, chunksize=None, max_mem=None):
"""
Attempts to compute a chunksize for the resampling output array
that is as close as possible to the input array chunksize, while
also respecting the maximum memory constraint to avoid loading
to much data into memory at the same tim... | bb1921eea934ebbe3450de69913687af5f4fecb9 | 687,034 |
def listify(s):
"""
Converts s into a list if not already. If s is None, an empty list will be returned.
"""
if s is None:
s = []
elif isinstance(s, (set, tuple)):
s = [i for i in s]
elif not isinstance(s, list):
s = [s]
return s | 1b44b3b3a041b3df5d6cfbd08394e421b3c6e831 | 687,035 |
import re
def normalize_keys(dict_, lowercase=True, separator='_'):
"""
Recoursively changes keys to their normalized version:
- replaces any special symbol by `separator`
- lowercases (if necessary).
Example:
In [1]: input_ = {"Content-Type": "text/html",
...: "Last-Modified": {
... | a15a3f4ccfe860af2ca7e758b293b297f8b0c3b3 | 687,036 |
def dedent_initial(s: str, n: int = 4) -> str:
"""Remove identation from first line of text."""
return s[n:] if s[:n] == ' ' * n else s | 28d27fad508a8d682fefd88d8905c6f60eccc215 | 687,037 |
def quadraticEquationV1(m, x, b):
"""
equation: y = m*x + b
params:
m = slope
x = position on x axis
b = y intercept
returns:
y = position on the y axis
"""
# multiply m and x and store the value into a variable
# add the product of m and x to b and store i... | f6ad17dc15f4eeb9fb6a1f784c43882143a23ec5 | 687,039 |
from typing import Union
import os
def validate_save(save_path: str) -> Union[str, None]:
""" Validate that a save path is a valid folder. If no save path was
specified then the current working directory will be returned. If an invalid
save path is specified, a NotADirectoryError error is raised.
... | 95138e27f812d4a1084d5ec069c68517323252be | 687,040 |
def replace_guide_name_with_bnd_name(guide_jnt_name):
"""
replaces the guide joint name with the bound name.
:param guide_jnt_name: <str> joint name.
"""
if "__" in guide_jnt_name:
return guide_jnt_name.rpartition("__")[0] + '_bnd_jnt'
return True | 128423053a942d80d7d16c8e884375c5571e91d5 | 687,041 |
def remove_recurring_characters(sorted_string: str) -> str:
"""Returns string without recurring characters, sorted input required."""
output_string = ''
for index, char in enumerate(sorted_string):
if index == 0:
output_string += char
else:
if char != sorted_string[i... | cfc5a1b65d9722b64e841a4b128385568de74e51 | 687,042 |
def manage_none_value(diff_result, column_list):
"""
To handle None values,it appends Null to the missing column name in the
result.
Args:
diff_result(list):Result of the datavalidation.
column_list(list):List of column names of the table.
Returns:
Return the list of dictio... | 272b29c43278cb682a5f5fb908186ea97f13ab7e | 687,043 |
import os
def combine_path(left, right):
"""
os.path.join(a, b) doesn't like it when b is None
"""
if right:
return os.path.join(left, right)
return left | d29861238c76442ff44a19d908760cec16da02ae | 687,044 |
import os
import shutil
def dirs_creation(dirs, wipe_dir=False):
"""
"""
for dir in dirs:
if os.path.isdir(dir) and wipe_dir:
shutil.rmtree(dir)
os.mkdir(dir)
elif not os.path.isdir(dir):
os.mkdir(dir)
else:
print(f'Directory {dir} a... | 0cdddf9469da20d4d57ee1f7a0f02ec82644ef75 | 687,045 |
import torch
def concat(z_support, z_query, idx):
"""
:param z_support: (n_way, n_supp, n_feat)
:param z_query: (n_way * n_query, n_feat)
:param idx: (n_way, k)
:return:
"""
pseudo = torch.stack([torch.index_select(z_query, 0, idi) for idi in idx], dim=0)
supp = torch.cat([z_support, p... | 966ca1d47f7cd26beb25910f4933dec4e77068c7 | 687,046 |
def sum_to_leftmost(value, dim):
"""Sum out `value.ndim-dim` many rightmost dimensions of a given tensor.
Args:
value (Tensor): A tensor of `.ndim` at least `dim`.
dim (int): The number of leftmost dims to remain.
Returns:
The result tensor whose ndim is `min(dim, value.dim)`.
"... | b4bd80c149e518b703648107f09cd3a481bb9500 | 687,047 |
def parse_class_names(class_names):
"""
:return:
"""
classname_dct = {}
name_list = []
with open(class_names, 'r', encoding='utf8') as fr:
for i, line in enumerate(fr.readlines()):
name = line.strip()
if name:
classname_dct[name] = i
... | 1c3786fe7e95f0cd5d6ddcb04abbfc58fa323781 | 687,048 |
def load(filename):
""" 读文件
Args:
filename: str, 文件路径
Returns:
文件所有内容 字符串
"""
with open(filename, 'r', encoding='utf-8') as f:
content = f.read()
return content | ef6e83192bd1f06ff530d8369e2f49a07fe677f1 | 687,049 |
def __es_una_tupla(salida1, salida2, evaluacion):
"""Solo para verificar si un objeto es una tupla"""
if (type(evaluacion) != type(tuple())):
return salida1
else:
return salida2 | f288e8b927d01e534f431cd4d6c5cc11b10d57a1 | 687,050 |
import re
def find_release_resources():
"""
Validate the .tx/config file for release files, returning the resource names.
For working with release files, the .tx/config file should have exactly
two resources defined named "release-*". Check that this is true. If
there's a problem, print message... | cafa797d0acdf1db9ae90259b55e91d1d9bcb9bd | 687,051 |
def is_point_process(obj):
"""Determine whether a particular object is a NEURON point process."""
return hasattr(obj, 'loc') | e75a5881fda23282f3cec50d8f5b6d52edec93fc | 687,052 |
def configure_settings(app, settings_override=None):
"""
Modify the settings of the application (mutates the app passed in).
:param app: Flask application instance
:param settings_override: Override settings
:type settings_override: dict
:return: Add configuration settings
"""
app.confi... | e02d6d477f4cf7b36fb59d3cac49f5439b536781 | 687,053 |
def _human_size(size_bytes):
"""
format a size in bytes into a 'human' file size, e.g. B, KB, MB, GB, TB, PB
Note that bytes will be reported in whole numbers but KB and above will have
greater precision. e.g. 43 B, 443 KB, 4.3 MB, 4.43 GB, etc
"""
UNIT_SIZE = 1000.0
suffixes_table = [('B'... | 127ce0f3ce89d9cb294ecb4874c937840ac8c166 | 687,054 |
import codecs
import yaml
import json
def read(path):
"""
:type path: read file (.json, .yml)
:param path:
:return: info, data
"""
info, data = False, False
if path.endswith(".yml"):
with codecs.open(path, "r", "utf8") as f:
data = yaml.load(f, Loader=yaml.SafeLoader)
... | 688e5f5048801ffeabf50e182f0e06eb684c355e | 687,055 |
def save_checkpoint(trainable_weights, ckpt_file_name):
"""
Mock save_checkpoint.
Args:
trainable_weights (list): List of weights.
ckpt_file_name (str): Path to save checkpoint file.
"""
return len(trainable_weights), ckpt_file_name | 08e47268b9d730bff1dd39a874a7a6ee06e9471a | 687,056 |
import os
def block_path(device):
"""return /sys/block/... path"""
return os.path.join("/sys/block", os.path.basename(device)) | b726917c1cad384e9ddc0b5cad11dcdd9ea1973f | 687,057 |
def safe_add(direction, direction_delta, check_constraints=False):
"""Check resulting vector values and add if not violates constraints.
Constraints are [-1; 1].
"""
x, y, z = direction
new_x = x + direction_delta['x']
new_y = y + direction_delta['y']
new_z = z + direction_delta['z']
if... | 5150c7694b26ab1daaad8c149d0dad49c3a37ded | 687,058 |
def _include_branding_code_in_app(dist):
"""Returns whether to omit the branding code from the Chrome .app bundle.
If a distribution is packaged in a PKG (but is not also packaged in a DMG),
then the brand code is carried in the PKG script, and should not be added to
the .app bundle's Info.plist.
... | 477cacaf01b46d024d76456756516f4f4ef04c64 | 687,059 |
from typing import Any
def check_str(data: Any) -> str:
"""Check if data is `str` and return it."""
if not isinstance(data, str):
raise TypeError(data)
return data | c856ce5180b56c79be2218c98ed33e2157f66400 | 687,060 |
def parser_start(next_parser='parse_ethernet'):
"""
This method returns the start of the parser
"""
parser_str = 'parser start { return %s; }\n' % next_parser
return parser_str | adac2da23848c6171e99e221b0da41508fb5b7d9 | 687,061 |
def _parse_memory(s: str) -> int:
"""
Parse a memory string in the format supported by Java (e.g. 1g, 200m) and
return the value in MiB
Examples
--------
>>> _parse_memory("256m")
256
>>> _parse_memory("2g")
2048
"""
units = {"g": 1024, "m": 1, "t": 1 << 20, "k": 1.0 / 1024}... | a5b5dae1b82ac63da84d2a8de77f811a266e2efa | 687,062 |
import json
def Read_Message_Dict(BB, msg_name):
"""
Read_Message_Dict(BB, msg_name):
Reads the named BB message contents, json.loads it, and returns the resulting dict.
Returns an empty dict if the message is not found or could not be read back.
"""
try:
msg_item = BB.ReadMessage(msg_... | daa390ddddf07d0031587f07993b63290e825db7 | 687,063 |
import os
def findfile(name, cwd, results):
"""findfile autodiscovers files by name that can be
located in the current working dir or a parent dir"""
cwd = os.path.abspath(cwd or os.getcwd())
filename = "{}/{}".format(os.path.abspath(cwd), name)
if results.get(filename):
return results.get... | f6db8f7dbcdab351d044e3ee8fdc2c3d664ebf8c | 687,064 |
def init_git(structure, options):
"""Fake action that shares the same name as a default action."""
return structure, options | a57e90881cf9bbc24f6b980391a69a6e72530557 | 687,065 |
import os
def get_absolute_paths(file_paths):
"""Returns the list of absolute paths to each path in file_paths."""
return [os.path.abspath(file_path) for file_path in file_paths] | 661da356d38371dabe3471c358075817dceeb170 | 687,066 |
def parse_scoped_selector(scoped_selector):
"""Parse scoped selector."""
# Conver Macro (%scope/name) to (scope/name/macro.value)
if scoped_selector[0] == '%':
if scoped_selector.endswith('.value'):
err_str = '{} is invalid cannot use % and end with .value'
raise ValueError(err_str.format(scoped_s... | 14ec603c3f4beedd49ca277e1f357140ede82539 | 687,067 |
def prettyprint_tokenized(tokenized: str) -> str:
"""Returns a pretty-printable version of a document that contains tokens."""
return tokenized.replace('\x1b', '<').replace('\x1c', '|').replace('\x1d', '>') | 7a3ee01b6a33104cf5168370b6c65f7fa87264e2 | 687,069 |
def copy_params_dict(model, copy_grad=False):
"""
Create a list of (name, parameter), where parameter is copied from model.
The list has as many parameters as model, with the same size.
:param model: a pytorch model
:param copy_grad: if True returns gradients instead of parameter values
"""
... | e0082f61230f7aeb2fbf8cc2c1855150985bc362 | 687,070 |
def tuple2int(t, cnames, op_widths_dict):
"""Convert list of values in the input parameter t to a hash key by
shifting and adding (OR'ing really) the values together. Must
factor in the max width of each field. The max width of each
component comes from the cnames and op_widths_dict parameters)... | 4ed948a88b2bbbdb06685bcece365c6ced886fec | 687,071 |
import math
def select_ghostdag_k(x, delta):
"""
Selects the k parameter of the GHOSTDAG protocol such that anticones lager than k will be created
with probability less than 'delta' (follows eq. 1 from section 4.2 of the PHANTOM paper)
:param x: Expected to be 2Dλ where D is the maximal network delay and λ is th... | 9731b509e35db024e17d63fbc6ef46235207c3ee | 687,072 |
def list_search(lst, key, value):
"""Search a list of dictionaries for the dict where dict[key] == value."""
try:
return next(dct for dct in lst if dct[key] == value)
except StopIteration:
raise KeyError() | b5f6d23835c731f376574f5e095ff332c8881035 | 687,073 |
def sum_of_squares(n):
""" returns the sum of squares of first n numbers """
iter = 1
sum = 0
while iter <= n:
sum += iter**2
iter += 1
return sum | 724032cf4806fe427d62c9a222b6b7c0e37673a7 | 687,074 |
def isOctDigit(s):
"""
isOctDigit :: str -> bool
Selects ASCII octal digits, i.e. '0'..'7'.
"""
return s in "01234567" | 35c4e09c3f45aaadd2e7642af04ffe472007ffa8 | 687,075 |
def xyxy_to_normalized_xywh(box, size, center=True):
"""
Converts bounding box format from 'xyxy'
to 'xywh'.
Args:
box: [Upper Left x, Upper Left y, Lower Right x, Lower Right y]; unnormalized.
size: [image width, image height]
center (bool): If True, then the x, y refer to cent... | eb20a19323c94c1d36fff7f4f1535aa2797687d5 | 687,077 |
import json
import codecs
def json_load(file_path):
"""
Loads an UTF-8 encoded JSON
:param file_path: Path to the JSON file
:type file_path: string
:rtype: dict
:return: The JSON dictionary
"""
return json.load(codecs.open(file_path, "r", encoding="utf-8")) | e9471165eb90f8bd98545b57c1884264cf2b9a49 | 687,078 |
def load_timestamps(filename):
""" load timestamps of a recording.
Each line of the file contains two numbers:
the frame index and the corresponding time in milliseconds.
Parameters
----------
filename: str
The file to extract timestamps from.
Returns
-------
dict:
Dictionary with fram... | 91cbeef34d187ef6721bfea4fe2bea5ea65f51bb | 687,079 |
import math
def distance(a, b):
"""
Helper function for checking distance
between any two points on a cartesian grid
:param a: First point
:type a: tuple
:param b: Second point
:type b: tuple
:return: Distance between two points
:rtype: float
"""
return math.sqrt((b[... | c1a70824c50699cf51c55aeabf9b94558ec21263 | 687,080 |
def idfn(val):
"""
Function to assign meaningful ids to tests that work with list of expected groups and feeds
"""
return val | cec0d2dd6467d77a891e84b2f99ff30e295bd4aa | 687,081 |
import argparse
def get_args():
"""Get arguments from CLI"""
parser = argparse.ArgumentParser(
description="""Program description""")
parser.add_argument(
"db",
help="""The database to which to add the probe names"""
)
parser.add_argument(
"probe... | 82f24a9617256d6cb07231997be60f6139d19ed7 | 687,082 |
def get_items_of_type(type_, mapping):
"""Gets items of mapping being instances of a given type."""
return {key: val for key, val in mapping.items() if isinstance(val, type_)} | 62bb622074f516f998cdd9f96533ef53e24462a6 | 687,083 |
def intbase(dlist, b=10):
"""convert list of digits in base b to integer"""
y = 0
for d in dlist:
y = y * b + d
return y | 8b7494b914ca947fcfd14a909186f31486cb3bb6 | 687,084 |
def cli(ctx, history_id, dataset_collection_id):
"""Get details about a given history dataset collection.
Output:
"""
return ctx.gi.histories.show_dataset_collection(history_id, dataset_collection_id) | b796386274d1346872bc5035bf1135cc1b65cbbd | 687,085 |
import torch
def get_log_rhos(target_action_log_probs, behaviour_action_log_probs):
"""With the selected log_probs for multi-discrete actions of behavior
and target policies we compute the log_rhos for calculating the vtrace."""
t = torch.stack(target_action_log_probs)
b = torch.stack(behaviour_action... | 13b211f050934b71726d606ba78fdc3ac963e531 | 687,086 |
def mean(iterator, length):
""" Returns the arithmetic mean of the values in the given iterator.
"""
return sum(iterator) / float(length or 1) | 1697af991e7ea3cdb83b63e0238826896e9cd881 | 687,087 |
import mpmath as mp
import sys
def ele_Warburg(w, sigma):
"""
:param
w: Angular frequency [1/s], (s:second)
The first expression:
Warburg = σ * (w^(-0.5)) * (1 - 1j)
sigma: warburg coefficient, no unit
The second expression:
refer:
P... | b709b16250a816040302be9dcb35e0010ea5f9ba | 687,088 |
def inplace_return_series(dataframe, column, series,
inplace, return_series, target_column=None):
"""
helper function to reuse throughout library. It applies logic for
performing inplace series transformations and returning copies of
modified series
:param dataframe: panda... | 16213950f4f25b0993c196cd13751fb794eec484 | 687,089 |
def no_tests(tests):
"""Predicate for number of tests."""
return not tests or len(tests) == 0 | c417b556af900c14b42fa4f7b408db27a7542eff | 687,090 |
def _get_widget_selections(widgets, widget_selections):
"""Return lists of widgets that are selected and unselected.
Args:
widgets (list):
A list of widgets that we have registered already.
widget_selections (dict):
A dictionary mapping widgets
(:py:class:`review... | 25c3f2b8e68aaedba5232c4c3cbe2f3ec73c99df | 687,091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.