content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def format_recursive(template, arguments):
"""
Performs str.format on the template in a recursive fashion iterating over
lists and dictionary values
>>> template = {
... 'a': 'Value {a}',
... 'b': {
... 'a': 'Value {a}',
... 'b': 'Value {b}',
... },
... 'c': ['Value {a}'... | ce51eefc38288b86c08425c1bb8dea2c0769e239 | 657,475 |
import os
def find_warns(guild_id: int):
"""Returns a list of every warned user's ID."""
warn_files = []
try:
files = os.listdir(f"data/servers/{guild_id}/warns/")
except FileNotFoundError:
return warn_files
for file in files:
if file.endswith(".json"):
warn_fil... | 6d0326d28fd469a66d34b8d382385e3574d6c8ee | 657,476 |
def _get_block_sizes(resnet_size):
"""The number of block layers used for the Resnet model varies according
to the size of the model. This helper grabs the layer set we want, throwing
an error if a non-standard size has been selected.
"""
choices = {
18: [2, 2, 2, 2],
34: [3, 4, 6, 3],
50: [... | 2093dc876e2f6db2cddb4bf836f1b8c3bcd6d789 | 657,478 |
async def get_manifest(db, ref_id: str) -> dict:
"""
Generate a dict of otu document version numbers keyed by the document id. This is used to make sure only changes
made at the time the index rebuild was started are included in the build.
:param db: the application database client
:param ref_id: t... | bc24f543135b4773b55350e80b885b1a4051c8fb | 657,479 |
def countObjects(skel):
"""
Number of object required for exporting the specified skeleton.
"""
if skel:
nBones = skel.getBoneCount()
return (2*nBones + 1)
else:
return 0 | 7ea1d03b98eaa7b8c062b9cdd3fa6efb023bbfab | 657,480 |
def get_active_web_certificate(course, is_preview_mode=None):
"""
Retrieves the active web certificate configuration for the specified course
"""
certificates = getattr(course, 'certificates', {})
configurations = certificates.get('certificates', [])
for config in configurations:
if conf... | 2fa136a2462582100cf1955039f095a8977f7db7 | 657,481 |
def load_raw(path, key=None):
"""
load raw data
parms:
path: data path
key: category of the raw data
"""
with open(path, 'r', encoding='utf-8') as f:
lines = f.readlines()
new_lines = []
if key == None or key == 'base':
for line in lines:
l = eval... | 3148598e53dd87c76f82a3c27bb278dbc41bd2ee | 657,482 |
import ctypes
def struct_pack(structure):
"""
Pack a :py:class:`ctypes.Structure` object and convert it to a packed string.
:param structure: The structure instance to convert
:type structure: :py:class:`ctypes.Structure`
:return: The structure instance converted to a string.
:rtype: str
"""
return ctypes.st... | e590f87d1b4f41f30feab2998ba7a381115654ba | 657,483 |
import random
def build_statement(unpleasantries):
"""Build your unpleasantries"""
base_statement = "You're dishonest & terrible at your job"
random_unpleasantry = random.randint(0, len(unpleasantries)-1)
joined_statement = "{0}. {1}.".format(base_statement, unpleasantries[random_unpleasantry])
... | 91fb53bed4c3db7483fbc026181f38322e042d5c | 657,484 |
def init_key_arguments(parser):
"""
:type parser: ArgumentParser
"""
parser.add_argument(
'--key',
type=str,
help='The private key the csr should be generated for.',
dest='key',
)
parser.add_argument(
'-d', '--domain',
type=str,
dest='domai... | bd60a14a57d36c7ea55739a69d376e0f746c1134 | 657,485 |
import csv
def readTaggedAnimalsCsvFile(path: str) -> list[list[str]]:
"""Read in the latset/greatest animals CSV file"""
rows: list[list[str]] = []
with open(path, "r") as csvfile:
# create a csv reader object
csvReader = csv.reader(csvfile)
# extracting field names through first... | b0fe7296439a089e14872d2a36a75328fca37c1e | 657,486 |
def del_duplicates(df, duplicates):
"""Delete all duplicates from the df only timed out ones."""
print(f"Dropping {len(duplicates)} duplicates (timed-out)")
return df.drop(duplicates.index) | d3a6d1fdb1e2acc5ca132fc18ae31d6dc5edc30f | 657,487 |
def fivePercent(distances, percentage = 0.05):
"""
Calculates the cutoff by which a distance is considered close.
Arguments:
distances -- A dictionary with the distances as keys and their frequency as values
Keyword arguments:
percentage -- Float where the cutoff should be (i.e. 0.05 for the closest 5 percent o... | b6bd25665205fb3a9a6028d18de6bb00d65d41ee | 657,488 |
import os
import yaml
def create_view_data(start_path):
"""Read view names and SQL code from the repository.
Args:
start_path (str): "./views"
Returns:
view_results (array of dict): contains name, owner and SQL code for each view
"""
view_results = []
print("Processing ... | 3658500ff5c6ee1c93445e9c2370613758d221a6 | 657,489 |
import time
def date_to_timestamp(date):
"""
Converts a date, format 2020-01-23
to a timestamp, format 12322342
"""
return time.mktime(time.strptime(date, "%Y-%m-%d")) | eaac0c1f4ac6c003ff0d25ade3ec9f073b89ece3 | 657,490 |
def get_corner_points(contour):
"""
Get all corner points of the hexagonal target.
Returns a list of 8 points, starting with the top left and going clockwise.
"""
# First actually convert to points
points = [point[0] for point in contour]
# Find the top left point
# This should be the l... | d5a5bcf8c4d6c73b10f6aa4762f4769710f58a3a | 657,491 |
import functools
def delegate_manager(method):
"""
Delegate method calls to base manager, if exists.
"""
@functools.wraps(method)
def wrapped(self, *args, **kwargs):
if self._base_manager:
return getattr(self._base_manager, method.__name__)(*args, **kwargs)
return metho... | 7a29e6986836881b6e47d99b33d8a09d1f627e11 | 657,492 |
def unflatten(data, separator=".", **kwargs):
"""
Reference Name ``unflatten``
Turn flat dictionary produced by flatten function to a nested structure
:param data: flattened dictionary
:param separator: string to split flattened keys
:return: nested structure
List indexes must follow in o... | 9af77588d92f4bbe5f83a61afb25d7986a57ccd9 | 657,493 |
def get_values(data, attribute):
"""gets all values from data[attribute] where data is a Pandas DataFrame
>>> data = pd.read_csv('./datasets/credit.csv', delimiter = ',')
>>> get_values(data, 'Housing')
array(['own', 'free', 'rent'], dtype=object)
"""
return data[attribute].unique() | 26b018b3b7fe0a6066477feba8f8e13eadbcda17 | 657,495 |
import re
def tokenize_by_sentence(text: str) -> tuple:
"""
Splits a text into sentences, sentences into tokens, tokens into letters
Tokens are framed with '_'
:param text: a text
:return: a tuple of sentence with tuples of tokens split into letters
e.g.
text = 'She is happy. He is happy.'... | 5d32579334a714c9d9ba866b286d8bacecd202f1 | 657,496 |
def healthcheck():
"""
Healthcheck route
:resjson string msg: status message
:statuscode 200: Started deploy
"""
return {'msg': 'OK'}, 200 | aaa7052ac3d134a6f6efaf5035d84e94831fe3c9 | 657,497 |
def get_rid_grid(mbr, grid_size, rn_dict):
"""
Create a dict {key: grid id, value: rid}
"""
LAT_PER_METER = 8.993203677616966e-06
LNG_PER_METER = 1.1700193970443768e-05
lat_unit = LAT_PER_METER * grid_size
lng_unit = LNG_PER_METER * grid_size
max_xid = int((mbr.max_lat - mbr.min_lat) / ... | 35c2f497a89a300ab8d699b13d397b720aed4cdb | 657,498 |
def list_api_revision(client, resource_group_name, service_name, api_id):
"""Lists all revisions of an API."""
return client.api_revision.list_by_service(resource_group_name, service_name, api_id) | d0acd9099dfc3a4375731da8eacecfdb0c387b2f | 657,499 |
def _get_value(entry_quals, key, cb=lambda x: x):
"""Get the value from the entry and apply the callback
"""
return list(map(lambda v: cb(v), entry_quals.get(key, []))) | 585aad5b0f458e153fe5734a8438e255473c5d19 | 657,500 |
def convertTypes(value):
"""Helper to convert the type into float or int.
Args:
value(str): The value that will be converted to float or int.
Returns:
The converted value.
"""
value = value.strip()
try:
return float(value) if '.' in value else int(value)
except... | 86e3ba932560621bcd3a85d71c375994373386bb | 657,502 |
def masternode_status(status):
"""Get a human-friendly representation of status.
Returns a 3-tuple of (enabled, one_word_description, description).
"""
statuses = {
'ACTIVE': (False, ('ACTIVE'), ('Waiting network to allow Masternode.')),
'PRE_ENABLED': (True, ('PRE_ENABLED'), ('Waiting ... | adcd08265d6de6475b32eb51718862a603b11009 | 657,503 |
def get_undirected(G):
"""
Convert a directed graph to an undirected graph that maintains parallel edges in opposite directions if geometries differ.
Parameters
----------
G : graph
Returns
-------
G_undir : Graph
"""
# set from/to nodes and then make undirected
G =... | bf32f7faad72bb4f4082a17a6b8e540666b4b874 | 657,504 |
def deep_eval(ctx, expr):
"""Recursively replace any callables c in expr (including inside lists) with c(ctx)."""
while callable(expr):
expr = expr(ctx)
if isinstance(expr, list):
expr = [deep_eval(ctx, x) for x in expr]
return expr | 513943154d7b8ad4e10fb972d38b8b2ebfa2e182 | 657,505 |
def _to_amici_noise_distributions(noise_distributions):
"""
Map from the petab to the amici format of noise distribution
identifiers.
"""
amici_distrs = {}
for id_, val in noise_distributions.items():
amici_val = ''
if val['observableTransformation']:
amici_val += val... | 76885ac2533764adf265059562d038b77f2fac76 | 657,506 |
def collect_expected(dataset):
""" Peel of the target values from the dataset """
expected = []
for sample in dataset:
expected.append(sample[0])
return expected | 8e9a39d8ac5e4a26a08ad2727ad0f7c009860de2 | 657,507 |
def parse_waypoints(pt_list):
"""
Retrive way point from the list.
Args:
pt_list: Way points list.
Return:
Parsed way points list for left arm, right arm.
"""
part = []
block = []
for line in pt_list:
if len(line) < 3:
block.append(part)
p... | 5d2540a4b75a621928cdca734ca693052a81d18c | 657,508 |
def get_perfdata(label, value, uom, warn, crit, min, max):
"""Returns 'label'=value[UOM];[warn];[crit];[min];[max]
"""
msg = "'{}'={}".format(label, value)
if uom is not None:
msg += uom
msg += ';'
if warn is not None:
msg += str(warn)
msg += ';'
if crit is not None:
... | a1911bf827ef3111a2ca0a5e5cfdd727c98b09b1 | 657,509 |
def _combined_lists(alist, total=None):
"""
Given a list of lists, make that set of lists one list
"""
if total is None:
total = []
if not alist:
return total
return _combined_lists(alist[1:], total + alist[0]) | 02623d9d376b6c9eb887c37f03ce323d755aefe5 | 657,510 |
def minmax(array):
"""Find both min and max value of arr in one pass"""
minval = maxval = array[0]
for e in array[1:]:
if e < minval:
minval = e
if e > maxval:
maxval = e
return minval, maxval | 3ade508ae82d60694968923ebdffef729a7af880 | 657,511 |
from datetime import datetime
def valida_data(data: str) -> bool:
"""Valida a data de uma requisição
Args:
data (str): 2022-01-19
Returns:
True: Se a data corresponder ao formato yyyy-mm-dd
False: Se a data não corresponder ao formato yyyy-mm-dd
"""
try:
datetime.... | b9761974a115b1e26bdbf784177389c319d848a1 | 657,512 |
def prefixify(d: dict, p: str):
"""Create dictionary with same values but with each key prefixed by `{p}_`."""
return {f'{p}_{k}': v for (k, v) in d.items()} | aaad6b11640df7c5e288bdd039b039ce373dcba1 | 657,513 |
def palindrome(a):
"""
Given a string a, turn it into a palindrome with minimum # of additions.
returns triple (original input, palindrome, # of additions)
"""
if len(a) == 0:
return ("", "", 0)
cache = {}
def inner(i, j):
# returns a palindrome generated from the substr... | d3b96e699294c4cd9d60ab7dbb85dbe861aa4d93 | 657,514 |
import os
def get_css(options, working_directory):
"""
Returns the path of the local css folder
:param working_directory: location of current directory
:type working_directory: string
:return: A dictionary containing relative links to the local css directory
:rtype: dict of strings
"""
... | 702e944dc0728a74ac5bb233ea4d40b44bc7dc66 | 657,515 |
import torch
def is_long_tensor(tensor: torch.Tensor) -> bool:
"""
Returns True if a tensor is a long tensor.
"""
if torch.is_tensor(tensor):
return tensor.type().endswith("LongTensor")
else:
return False | 164b5a27f04d920fd9f186a30b8af5bdfbb71d60 | 657,516 |
def _as_friendly_string(s):
"""Converts a bytestring to a text string.
To avoid encoding errors caused by arbitrary high characters (allowed in
PICO-8 source), this replaces all high characters with underscores.
Args:
s: The bytestring.
Returns:
The text string with high character... | 9853b3024b04408795db5a42917222d5c27c981f | 657,518 |
import torch
def build_classifier_confidence(input_channels: int) -> torch.nn.Sequential:
"""
Create sequential module for classifier confidence score.
:param input_channels: Number of input activation maps.
:return: Sequential module.
"""
return torch.nn.Sequential(
torch.nn.Linear(i... | 8ff194c19f6ab175a56c7d959e495a550cae6f6a | 657,520 |
def get_bitstream_type(field, db_object):
"""Retrieves the bitstream type from the device image object"""
device_image = getattr(db_object, 'image', None)
if device_image:
return device_image.bitstream_type
return None | 6b2fbef569a5b078e8e26dfd5edc563c43218a83 | 657,521 |
def kalman_filter(prior, observation, K):
""" Calculate two iteration kalman filter with given measurement variance.
The higher the variance the more likely will the prior be preserved.
Examples:
low pi => steep response in K to small increases in F, max K = 1.0 (strong prediction-error influence)
... | 21fc2e756835660be8727942ac673f61a98cb7dc | 657,522 |
def params(css, encoding, use_bom=False, expect_error=False, **kwargs):
"""Nicer syntax to make a tuple."""
return css, encoding, use_bom, expect_error, kwargs | bcdf85ddbd577a7a81a1a9e646867f641794cdf9 | 657,523 |
def startswith(x, lst):
""" Select longest prefix that matches x from provided list(lst)
:param x: input string
:param lst: prefixes to compare with
:return: longest prefix that matches input string if available otherwise None
"""
longest_prefix = None
for prefix in lst:
if x.starts... | bbffef79e3f3c03fb5e41564310df143eef5484d | 657,524 |
def modulo(dividend: int, divisor: int) -> int:
"""
Returns remainder of dividend // divisor.
Parameters:
first (int) : First Integer
second (int) : Second Integer
"""
return dividend % divisor | 0682b69c4e1f27c91cd6b9fd0478116bbcb44d52 | 657,525 |
def bytes_to_str(value):
"""Return UTF-8 formatted string from bytes object."""
return bytes(value).decode('UTF-8') | 8e43de7f21cbcde55b79f3ea118b7e29b4e78aa1 | 657,526 |
def convert(ruta):
"""Función para convertir una lista a string con las posiciones de la ruta
separadas por '-'
Args:
ruta: Una lista con las posiciones de la ruta
Returns:
ruta_c: Un string con las posiciones de la ruta separadas por '-'
"""
s = [str(i) for i in ruta]
rut... | 64bfbad8a8eae9b85e1b2d245b89e568af2254a0 | 657,527 |
def kebab_case_to_camel_case(s):
"""
convert a kebab case string to a camel case string
A utility function to help convert a kebab case string into a camel case
string. This is to help convert directive options typically defined in kebab
case to Confluence macro parameters values which are typically... | ea7833dfaa7bf9172db55f56d856d3de8642496a | 657,528 |
def nearest(date,timeSeries,findSeries):
"""
This function will return the datetime in items which is the closest to the date pivot.
"""
nearDate= min(timeSeries, key=lambda x: abs(x - date))
index=list(timeSeries).index(nearDate)
return list(findSeries)[index] | d94b59e54c0ca0d1380732879260f0de3e0b4ac5 | 657,529 |
import functools
def rgetattr(obj, attr, *args):
"""Get chained properties.
Usage
-----
>>> class Pet:
def __init__(self):
self.favorite_color = "orange"
>>> class Person:
def __init__(self):
self.pet = Pet()
>>> p = Person()
>>> rge... | c41d2a490c1a47251f7d307787be9836995d63ff | 657,530 |
def same_entries(a, b):
""" checks if entries a and b represent the same publication """
for key in ['ID', 'doi', 'hal_id', 'title', 'chapter']:
if key in a and key in b and a[key].lower() == b[key].lower():
return True
if 'title' in a and 'chapter' in b and a['title'].lower() == b['chap... | 88ea6155ad342703ef8a74b20938e8099c582f34 | 657,531 |
def create_technologies(connector, technology_list):
"""
Creates the ``technologies`` table in Temoa.
Parameters
----------
connector : sqlite connector
The connection to an sqlite database
technology_list : list of ``Technology`` objects
All of the technologies initialized in ... | ebf9148b7299a367064531659a5d2b55566a14aa | 657,532 |
import glob
def get_myfile():
"""获取文件名为6个字符的文件"""
return glob.glob(r"F:\PythonProject\??????.txt") | 5d1447e4eff500caf581392a838ae97ed5dadccb | 657,533 |
def do_html():
"""
Decorator that makes sure we are sending text/html.
"""
def entangle(handler):
def _do_html(environ, start_response, *args, **kwds):
output = handler(environ, start_response, *args, **kwds)
start_response('200 OK', [
('Content-Type', '... | b4ac69b79a610bbe9a4b853f3b48a93f7b9a165a | 657,534 |
def get_security_args(security, d):
"""
Returns the parameters in d that are prepended with the string in security.
"""
ud = {}
for key in d:
if security + '_' in key:
if key.startswith(security + '_'):
ukey = key.replace(security + '_', '')
ud[uke... | 7b5aeb9cd54cce3851c3973ebbb6fb5d8b59e577 | 657,535 |
def vaporViscosity(T, vVP):
"""
vaporViscosity(T, vVP)
vaporViscosity (micropoise) = A + B*T + C*T^2
Parameters
T, temperature in Kelvin
vVP, A=vVP[0], B=vVP[1], C=vVP[2]
A, B, and C are regression coefficients
Returns
vapor viscosity in micropoise at T
"""
r... | 2b5ef247e2f42e986d6a601ab7023fff82a17ab9 | 657,536 |
import os
def get_current_maya_location():
"""
Get where maya is currently running from.
"""
location = ''
if 'MAYA_LOCATION' in os.environ:
location = os.environ['MAYA_LOCATION']
return location | dbaed18c1a565d6326d4d0b7677774bb4ca4446a | 657,537 |
def bubble_sort(arr):
"""
My Python implementation of bubble sort
Sorts a list of numbers and returns the sorted list
Time complexity: O(n^2)
Space complexity: O(1)
"""
# One iteration for each element
for i in range(len(arr)):
# One pass through list for
for j in ran... | 62694ae73379834137c332385e2a4ab98d6ec27a | 657,538 |
def id_to_python_variable(symbol_id, constant=False):
"""
This function defines the format for the python variable names used in find_symbols
and to_python. Variable names are based on a nodes' id to make them unique
"""
if constant:
var_format = "self.const_{:05d}"
else:
var_fo... | ca6d8a56f70d2ee14215c37d7ffd8c30f0ed030c | 657,539 |
import mimetypes
def guess_mime_type(filepath):
"""Guess the MIME type for the given file path. If no reasonable guess can
be determined, `application/octet-stream` is returned.
Args:
filepath: path to the file
Returns:
the MIME type string
"""
return mimetypes.guess_type(fil... | e797da8eb55e2a0843b4d2e58812c3c0481708ed | 657,540 |
from pydantic import BaseModel # noqa: E0611
from typing import Any
def diff_models(from_: BaseModel, to_: BaseModel) -> dict[str, Any]:
"""
Return a dict with differences of the second in relation to the first model.
Useful for getting only the fields that have changed before an update,
for example.... | bb52c913c2249d9a13d897df17b67edd15085a64 | 657,541 |
def get_day(bs_day):
"""Pega número do dia."""
return bs_day.text.strip().split()[0] | e22ed050b0219609125f2e6b75f121e73126758b | 657,542 |
from typing import Optional
import torch
def mask_from_lens(lens, max_len: Optional[int] = None):
"""Return an element-wise boolean mask of length less that `max_len`.
Args:
lens ([type]): [description]
max_len (Optional[int]): max length. Defaults to None.
Returns:
tensor:
"... | 4e0f16a23a5fdc9a842f6c1ba5ac79581e6180d0 | 657,543 |
def check_args(argv):
"""
Validates `main()` input arguments
:param argv: program arguments
:return: True/False
"""
if len(argv) != 3:
print("Github login and password are expected as script parameters")
return False
return True | 7763f5b2f3ddb2e15da47eb7e3bb06f842758e2b | 657,544 |
def time_to_str(sec):
"""Convert seconds to days, hours, minutes and seconds."""
days, remainder = divmod(sec, 60 * 60 * 24)
hours, remainder = divmod(remainder, 60 * 60)
minutes, seconds = divmod(remainder, 60)
_str = ""
if days > 0:
_str += "{:d} days, ".format(int(days))
if hours ... | d678d8f8b14fd643438778414116515efff5305c | 657,545 |
import torch
def my_collate_fn(old_data):
"""This function will be used to pad the questions to max length
in the batch and transpose the batch from
batch_size x max_seq_len to max_seq_len x batch_size.
It will return padded vectors, labels and lengths of each tweets (before padding)
I... | 6465af7b179aee7541948b9b9058b372cb7738da | 657,547 |
def filedate(filename):
"""Extract the date from the filename"""
return filename[1:9] | fa3f8668668b4fc10f547dca7b12f420febb3ac8 | 657,549 |
def read_emb(src_path: str, trg_path: str, pass_header: bool=True, top_tokens: int=50_000):
"""
Read tokens of word2vec style embeddings to List[str].
:param src_path str: path to word2vec-style source language embeddings
:param trg_path str: path to word2vec-style target language embeddings
:param... | b03f0d71aec99b8b97a77c7605be74cca8b32380 | 657,550 |
import torch
def _pairwise_distances(embeddings, squared=False):
"""Compute the 2D matrix of distances between all the embeddings.
Args:
embeddings: tensor of shape (batch_size, embed_dim)
squared: Boolean. If true, output is the pairwise squared euclidean distance matrix.
If... | 10a8a56b836c75ea2f3a466613fa1e65e0123803 | 657,551 |
def standardize(x):
"""
Standardizes a Series or DataFrame.
"""
return (x - x.mean()) / x.std() | 8fd95bea1515461e3726bd1499c26660df519226 | 657,552 |
import os
import sys
import pickle
def loadPickle(dir_path, file_name):
""" Loads pickle file.
Arguments:
dir_path: [str] Path of the directory where the pickle file will be stored.
file_name: [str] Name of the file where the object will be stored.
"""
with open(os.path.join(dir_path, file_... | a51b16b70f81b48f8c265154475615dd86120526 | 657,554 |
def json2xml(json_obj, line_padding=""):
"""Function to create xml-report for vulerabilities found by IoTCrusher"""
result_list = list()
json_obj_type = type(json_obj)
if json_obj_type is list:
for sub_elem in json_obj:
result_list.append(json2xml(sub_elem, line_padding))
re... | 21de680117ea7f9b5a16b9483ed2f7a7a216574a | 657,555 |
def replace(smap):
"""With dictionary argument, subsitute each instance of key with value."""
def generator(coll):
for item in coll:
if item in smap:
yield smap[item]
else:
yield item
return generator | 79a51d853c7d3bf5513a694ba4a367fdfe97d743 | 657,556 |
from datetime import datetime
def sanitize(output):
"""Sanitize a dictionary or a list of dictionaries as follows:
* remove 'tel:+'/'alias:' prefixes from 'to'/'from'/'address' keys' values
* add 'obfuscated' key when 'from' key is present
* convert 'timestamp' keys' values to datetime obje... | c4bc02afbddc771197eacf2ed27e350f34fa5a52 | 657,557 |
import numpy
def get_obs_e_from_obs(h, d):
"""gets the observatory e component given the observatory components.
Parameters
__________
h: array_like
the observatory h component.
d: array_like
the observatory d declination.
Returns
_______
array_like
the observ... | 0c45287275cc7730c066f96bee1e1541238f8c5b | 657,558 |
def collapse_values(current_field_name: str, target_dict_name: str):
"""Add the current field value to a dict. Changes the current value to None"""
def transform_function(current_value: object, record: dict, complete_transform_schema: dict, custom_variables: dict, is_nested_record: bool=False):
additi... | 331d0b96f8fcc7b138f097d8c0041ab8f125af13 | 657,559 |
import numpy as np
def normalize_no_neibhours(dpeaks):
"""
"""
select = np.isnan(dpeaks['S coeff']) * (dpeaks['d0'] > 5)
indices = np.where(select)[0]
for peak in list(indices):
if dpeaks['d0'][peak] > 5:
if dpeaks['Np'][peak]%2 == 0:
dpeaks['S coeff'][peak] = ... | fe2cf13a2d4a08466eb46461ec45ddb7cf92391c | 657,560 |
def backCost(item):
""" item <state, actions, backwardCost> """
return item[2] | 75744e20441b2337879ac663e0770eb39900d82d | 657,561 |
def hex2rgb(color):
"""Turns a "#RRGGBB" hexadecimal color representation into a (R, G, B)
tuple.
Arguments:
color -- str
Return: tuple
"""
code = color[1:]
if not (len(color) == 7 and color[0] == "#" and code.isalnum()):
raise ValueError('"%s" is not a valid color' % color... | 75db92c4ddf2d9ac70a7ee1b0a99b57143d08182 | 657,562 |
def ltof(values):
"""
Converts the special integer-encoded doubles back into Python floats.
See the Arduino's equivalent ftol().
"""
assert isinstance(values, (tuple, list))
return [int(_)/1000. for _ in values] | d94b9917b229a28754130aaa12d6ed0da513995e | 657,563 |
import time
import os
def getFileYearMonth(filename, args):
"""gets the year and month a picture was modified (taken)"""
mtime = time.localtime(os.path.getmtime(filename))
return args.year or mtime.tm_year, args.month or mtime.tm_mon | 5d8740952af34c54b6198bdfb17c7e2999514a11 | 657,564 |
from typing import Dict
def build_trial_facets(trial_file_counts: Dict[str, int]):
"""
Convert a mapping from trial ids to file counts into a list of facet specifications.
"""
return [
{"label": trial_id, "count": count}
for trial_id, count in trial_file_counts.items()
] | bb9bdb2086c4af9b338f78f7fd0aa4c4090345df | 657,565 |
def filter_options(symbol, option_df, strike_price, putcall, dte):
"""Filter options to standards"""
## Add filters here or in webhook##
#t = '2021-12-05'
#expiry_date = custom_expiry_date(t) # Convert string date to expiry timestamp
#dte = 0
# Apply filters
filtered_df = option_df[(option_... | 68fbc44e035ef0127a72a1d7285ba63e7fc6086e | 657,567 |
import torch
def stack_softamx_unbind(
pi,
pi_2,
pi_3,
pi_4,
):
"""Softmax and split mixture weights (pi)."""
pi_all = torch.stack([pi, pi_2, pi_3, pi_4])
pi_all = torch.softmax(pi_all, dim=0)
(
pi,
pi_2,
pi_3,
pi_4
) = torch.unbind(pi_all, dim=0)
... | 3d5bcca8849f8be1ee37484ad21606abc5a68dbf | 657,568 |
import ast
def safe_conversion(value):
"""
Safely convert parameter value from .cfg file
"""
try:
value = ast.literal_eval(value)
value = list(value) if isinstance(value, tuple) else value
return value
except ValueError:
return value | 4f79dc43989a964b5ea7af439f05d0cdae17226b | 657,569 |
def XmlDataTable_to_XmlFile(xml_data_table,file_name="test.xml"):
"""Converts the XMLModel DataTable to a file on disk using the save method"""
xml_data_table.save(file_name)
return file_name | ac95bbc85d2a61a82dc5972bd78f70435eae3624 | 657,570 |
def set_default_attr(obj, name, value):
"""Set the `name` attribute of `obj` to `value` if the attribute does not already exist
Parameters
----------
obj: Object
Object whose `name` attribute will be returned (after setting it to `value`, if necessary)
name: String
Name of the attri... | 651538a814dee5c3af69a99f1a97be0e49734d88 | 657,571 |
from typing import Tuple
def get_next_branch_state(branch_symbol: str, state: int) -> Tuple[int, int]:
"""Enforces the grammar rules for SELFIES Branch symbols.
Given the branch symbol and current derivation state, retrieves
the initial branch derivation state (i.e. the derivation state that the
new ... | 642010289c78c0ca54cebebe86fb3101d3cccfa2 | 657,572 |
def warning(sisaPeringatan, userGuessed, duplicateGuess, display):
"""
Fungsi ini ditujukan untuk
operasi warning (peringatan)
"""
sisaPeringatan += 1
if not userGuessed.isalpha():
print("Simbol ini tidak diperbolehkan. Kamu kena Peringatan!!" + display)
elif userGuessed in duplicat... | 940dc1264b4e015bfbd800d956b906369e763d02 | 657,573 |
def A_approx_deph(Qload_deph, deltaT_diff_deph, Kt_approx):
"""
Calculates the approximate heatransfer area.
Parameters
----------
Qload_deph : float
The heat load of dephlegmator, [W] , [J/s]
deltaT_diff_deph : float
The coefficient difference of temperatures, [C]
Kt_approx ... | 0a811b019763d480865ed7221bdf82e159722b38 | 657,574 |
def update_dict_using_dict(dict1, dict2, operator):
"""
Updates the elements of dict1 with the elements of dict2 using the given operator.
Returns a
Args:
dict1 (dict): Dictionary.
dict2 (dict): Dictionary.
operator (function): Can use the operator module to get basic operators... | 4ed1305bf4f299ab16f50885301081188c080f12 | 657,575 |
import math
def bern_utility(x: float, a: float = 0, mult: float = 1) -> float:
""" A simple utility function based on bernoulli's initial formulation of EU with an additional multiplier like KR 2006"""
try:
res = mult * math.log(a + x)
except ValueError:
res = math.nan
# raise Pos... | 099ec93f50145eca4fd8f20c9cc8e30ec2b14ecc | 657,577 |
def mobius_avg(n):
"""
Returns the average order of mobius function for the positive integer n
Parameters
----------
n : int
denotes positive integer
return : float
return mobius function average
"""
if(n!=int(n) or n<1):
raise ValueError(
"n must be... | 1435d5aa502e9a22b3d261d4305e68c2396b86c6 | 657,578 |
def relu_number(n):
"""Calculate the relu of a number
Keyword arguments:
n -- the number
"""
return max(0, n) | 2863346d60788fb9cce882f740a9efa326d9e360 | 657,579 |
import requests
import json
def get_push_shift_data(query, after, before, sub):
"""
Gets comments for a given keyword between two dates for a single subreddit
up to a limit of 1000
Args:
- query: keyword to search for
- after: start search date as a unix timestamp
... | 039df15eca41aa48364f44370803dcb72f363e2b | 657,580 |
def _report_error(info):
""" Interprets the return code of the odr routine.
Parameters
----------
info : int
The return code of the odr routine.
Returns
-------
problems : list(str)
A list of messages about why the odr() routine stopped.
"""
stopreason = ('Blank',
... | 2420429b8f4ef9d98a91712b5fa9e6ae44f0d91b | 657,581 |
def append_class(form_field, arg):
"""Returns the given form_field with appended classes"""
css_classes = arg.split(',')
current_class = form_field.field.widget.attrs.get('class') if form_field.field.widget.attrs.get('class') else ''
form_field.field.widget.attrs['class'] = f'{current_class} {" ".join(c... | 754ddfe045bcc43443e709d95e83dd8d3fc3a958 | 657,582 |
import time
def str_to_timestamp(utc_str: str, utc_format: str, offset: int):
"""
UTC时间字符串转换为时间戳
"""
timeArray = time.strptime(utc_str, utc_format)
timeStamp = (int(time.mktime(timeArray)) + offset * 60 * 60) * 1000
return timeStamp | 5f55d6d97c85f4dab68cc27d5bcdd9e4bb38f197 | 657,583 |
def cs_to_ms(cs):
"""Convert Centisecods to Milliseconds"""
return cs * 10 | 58e44e3607763935744391e183023d0662c6ab12 | 657,584 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.