content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def decode_pair(left: str, right: str, rep: int, s: str) -> str:
"""Decodes a left/right pair using temporary characters."""
return (
s.replace("", "")
.replace("\ufffe" * rep, left)
.replace("\uffff" * rep, right)
) | 946a106d608adae78cfc0ec26a629192c8aff87f | 652,790 |
def calor_vaporizacion(T, Tc, C1, C2, C3, C4):
"""Calor de vaporización de liquidos organicos e inorganicos [J/(mol.K)]"""
Tr = T / Tc
return C1*(1 - Tr)**(C2 + C3*Tr + C4*Tr**2) / 1000 | ae938a053cf9a4e9cc37a526d2252b5a412dc7f0 | 652,792 |
def get_overtime(hour_out, check_out):
"""menghitung lembur pegawai"""
if check_out > hour_out:
result = check_out - hour_out
else:
result = ' '
return result | 3e9e388a927eb01280cf07151c2ef0b2ae9a278f | 652,793 |
def create_ports_list(values):
"""
Create the ports list for PPTN configuration
:param values: TN Ports Configuration values
:return: the complete ports list in good format
:Example:
result = create_ports_lists(values)
"""
ports_list = values.split(',')
for port in ports_list:
... | a70bd041ecef900596a6b2d9ac916d0239ed4f53 | 652,794 |
import argparse
def get_parser():
"""Get parser for command-line arguments."""
parser = argparse.ArgumentParser(
description="A script to train the HBM models and run the evaluation"
"on a list of images")
parser.add_argument('image', type=str, nargs='+',
... | 97b3f546573104775ffad36b336c2743eec1fcfc | 652,795 |
def get_requires_for_build_wheel(config_settings=None):
"""Returns a list of requirements for building, as strings"""
return [] | 12e139b2052d7f52ea92a04703f118bd0ae436f8 | 652,797 |
def ResolveForwardingRuleURI(project, region, forwarding_rule, resource_parser):
"""Resolves the URI of a forwarding rule."""
if project and region and forwarding_rule and resource_parser:
return str(
resource_parser.Parse(
forwarding_rule,
collection='compute.forwardingRules',
... | 97730ae4a23ee039f4437fb54d277f9845023cc5 | 652,798 |
def get_fmts(df):
"""
reasonable formats for a styler
:param df:
:return:
"""
fmts = {}
def guess_fmt(nm, sz):
named_cols = {'Err': '{:6.3e}', 'CV': '{:6.3f}', 'Skew': '{:6.3f}'}
for n, f in named_cols.items():
if nm.find(n) >= 0: # note -1 means not found
... | 37482b39c41010278aca5738f2dff2c6f10a1cec | 652,799 |
from functools import reduce
def collect_entities(obj):
"""collects (merges) all entities (list/str) down the branch"""
if type(obj) == dict:
return reduce(lambda x, y: x + y, [collect_entities(v) for v in obj.values()], [])
elif type(obj) == str:
return collect_entities([obj])
else:
... | 2afac4528095274416db22163c850baed8c43dcc | 652,800 |
def isproperty(obj):
"""
Is this a property?
>>> class Foo:
... def got(self):
... return 2
... def get(self):
... return 1
... get = property(get)
>>> isproperty(Foo.got)
False
>>> isproperty(Foo.get)
True
"""
return type(obj) == pro... | 14e2a33b89117fdcdcbd99babfd04dd7ff264c73 | 652,801 |
def target_schema() -> str:
"""Get target schema name."""
return "dv" | 17950059542d217c10bd8baad9c062fa32d0a628 | 652,802 |
def feed_url_recent():
"""feed_url_recent return str url for feed recent
Fixture returns url feed recent
Returns:
[str]: url for feed recent
"""
return "https://nvd.nist.gov/feeds/json/cve/1.1/nvdcve-1.1-recent.json.gz" | 8e4189e44130cc73785bfac247f5c4f074a94c11 | 652,803 |
def round_to_odd(x):
"""
:param x: some number (float or int)
:return: nearst odd integer
"""
return int(round((x - 1) / 2) * 2 + 1) | fcacf65850bbe86d009f9959a8d1300f88dfbdbf | 652,804 |
def _findOldPosition3Valence(faces, uFaces, verts, uVerts, neighDict, uNeighDict, edgeDict, uEdgeDict, vIdx, computed):
"""
This is the complex case where vIdx has valence == 3
Updates uVerts in-place
Arguments
faces ([[vIdx ...], ...]): The subdivided face structure
uFaces ([[vIdx ...], ...]): The unsubdivided... | ef656cc3adbe795b0ddfe567fd7312839c4b1e2d | 652,805 |
import os
def get_file_names(dir:str = "ImageData"):
"""
Gets all file names in provided directory
Args:
dir: Directory containing the images
Returns:
List of all files in provided directory
"""
return os.listdir(dir) | ec1deba059e143c7c331cca57a97096f7f8a2006 | 652,806 |
def calculate_change_label(last_close, close):
""" Calculate the label for a given input. The label is the change of the closing price from the last closing price.
:param last_close: closing price of last candle
:param close: closing price of current candle
:return: float
"""
return (close - la... | 2b887cefcc580d26a60e3b3b6bc6c784aebf99bb | 652,807 |
def check_role_requirement(requirement, roles):
"""
Check user roles meets requirement
A requirement looks like:
{
"type": "all|any"
"roles: ["role_A", "role_B"]
}
"""
allow = False
if requirement["type"] == "all":
# require user has all the roles specified
... | 2df641d1a865a3724ea6199ff15056e08735fd15 | 652,808 |
def compare_config(cfg_1, cfg_2):
"""Compare two config dictionaries. Useful for checking when resuming from
previous session.
Parameters
----------
cfg_1 : dict
cfg_2 : dict
Returns
-------
Returns True when the two configs match (with some exclusions), False
otherwise.
""... | 3db7e677f7c3cad552d311c0000aa46c2d9c0b0c | 652,809 |
def has_tag_requirements(tags, required_tags, qtype):
"""
Returns True if `tags` meets the requirements based on
the values of `required_tags` and `qtype`. False otherwise.
"""
has_tag_requirements = False
tag_intersection = set(required_tags).intersection(set(tags))
if qtype == "or":
... | 62ac825ba17babd2cd8b449693658d0394d2f965 | 652,810 |
def getSelectColumns(columns):
"""
Prepare the columns to be selected by the SELECT statement.
"""
if columns == '*':
return columns
else:
return ', '.join(columns) | caef33ffd42027be970107b53ecdd6bed125a381 | 652,811 |
from typing import List
def annotation_name(attributes: List[dict],
category_name: str,
with_attributes: bool = False) -> str:
"""
Returns the "name" of an annotation, optionally including the attributes.
:param attributes: The attribute dictionary.
:param categ... | 8044a5618477e26f10be0a52e3e673de20d060d4 | 652,814 |
import unicodedata
def strip_accents_unicode(s: str) -> str:
"""Transform accentuated unicode symbols into their ASCII counterpart."""
try:
# If `s` is ASCII-compatible, then it does not contain any accented
# characters and we can avoid an expensive list comprehension
s.encode('ASCII'... | 08c0b66e4f70241e4a3585f181c3bbb43361d04d | 652,815 |
def _get_date_from_videofile(videopath):
"""
Input: path to videofile.
Output: something like 2017-10-09_Elen_Kronberg_3.avi (where the 3 is the videonumber)
requirement: Filename is like: /home/path/.../2017-10-09_Elen_Kronberg_3_SUM-10s_pred.csv
"""
parts = videopath.split("/")[-1].split("_")
... | 416631214ff1c945e80622f71a13e11c1c634bc8 | 652,817 |
import re
def to_key(path):
""" get int order from file name """
ints = re.findall(r'\d+', path)
if len(ints) == 0:
return -100
else:
return int(ints[0]) | a9fdd25ad358d869fb5c60e95151b86609cb5e83 | 652,818 |
import os
def get_filename_from_filepath(filepath):
"""Parse the filename (without extension) from a filepath.
Arguments:
filepath -- filepath string
Returns:
filename -- name of the file in the path (without extension)
"""
basename = os.path.basename(filepath)
return os.path.splitext(basename)[... | 4d65bd50778d7f0eec5b85da7132daab4ccec737 | 652,819 |
def get_param_value_by_name(parameters, name):
"""
Return the value from the conditions parameters given the param name.
:return: Object
"""
for p in parameters:
if p['name'] == name:
return p['value'] | aead03bc5fd33762a8ab6660b747bfda2bc418bc | 652,820 |
def _get_db_subnet_group_arn(region, current_aws_account_id, db_subnet_group_name):
"""
Return an ARN for the DB subnet group name by concatenating the account name and region.
This is done to avoid another AWS API call since the describe_db_instances boto call does not return the DB subnet
group ARN.
... | db6736d9e5d56eb2940875f7564c6293db2c080e | 652,821 |
import socket
import struct
def open_socket(addr, mcast=None): # addr: ('host', port)
"""
open a tx/rx socket on the interface corresponding to addr
- (also) listen for multicast datagrams in the mcast group if set
- for a tx-only use, setting the mcast parm is unnecessary
- all interfaces if host is null stri... | 435ffa7ef8f1b815c1500b666e813fe4054f0ae1 | 652,822 |
def count_words(text):
"""Count the words of text passed as argument."""
total_words = 0
for word in text.split("\n"):
if word.strip():
total_words += 1
return total_words | dfdb91870907c02844690c0a198bf993265bfa2d | 652,823 |
def divide(a: int = 0, b: int = 1) -> float:
"""Divide two numbers."""
print(a / b)
return a / b | dd2be970d9a84ff4357895c482e573f2fb5f5689 | 652,824 |
import pickle
def load_from_pickle(load_path):
"""Deserialize data from pickle file.
:param load_path: (str) Path of file to load
:return: (Python obj) Deserialised data
"""
with open(load_path, "rb") as file:
data = pickle.load(file)
return data | 89ac2dfaab0b855fee77111d1d1f1f1a16d22fa6 | 652,826 |
import os
import unicodedata
def extract_type(file_name, delimiter):
"""To extract type from file name
Args:
file_name : face img name
delimiter : delimiter
Returns:
type: type of face
"""
file_name, ext = os.path.splitext(file_name)
type = file_name
if delimiter i... | 08ed35a5a2906c7214b905b0d3a58673eea068de | 652,827 |
def ses_complaint_callback():
"""
https://docs.aws.amazon.com/ses/latest/DeveloperGuide/notification-contents.html#complaint-object
"""
return {
'Signature': 'bb',
'SignatureVersion': '1', 'MessageAttributes': {}, 'MessageId': '98c6e927-af5d-5f3b-9522-bab736f2cbde',
'UnsubscribeU... | ceb2e2f42013ad3bc83baac9dacdc4aca3be4ba7 | 652,828 |
def _get_monthly_values(df):
"""Accepts a Panda's DataFrame with columns ['month', 'average', and 'count'].
Returns a list of dicts ensuring all possible months have values. Months
not listed in DataFrame assigned average and count of 0."""
months = ['April', 'May', 'June', 'July', 'August', 'September',
'Octo... | a75e197ef36d71325f9c66e6a11e1f7ab9b76178 | 652,830 |
import torch
def get_xG_and_goals(preds, labels):
"""
Calculate expected goals and goals.
Args:
preds (tensor or lists of tensors): predictions. Each tensor is in
in the shape of (n_batch, num_classes). Tensor(s) must be on CPU.
labels (tensor or lists of tensors): correspondin... | fdf4bcdd3bbe880362d11c970fd63377d6875269 | 652,831 |
def find_row_header_table(category_table, stub_header):
"""
Constructs a Table from the row categories of the original table.
:param category_table: ~tabledataextractor.table.table.Table.category_table
:type category_table: list
:param stub_header: ~tabledataextractor.table.table.Table.stub_header
... | 16f05044aa48dc5af6c0d0748fd8f99087ff38ac | 652,832 |
def create_list_of_holidays(date_start, modified_end_date):
"""
Here app creating list of holidays every time, when user choise vacation
document. Holidays create for every year from start date to end date
if vacation on border between 2 years
"""
# strong holidays in every year
hdays_strong... | 30c217506b9e41217d8da3cb34f1b4f7b59b5475 | 652,833 |
def _list_comprehensions(obj, item=None, return_tuple=False, make_none=False):
"""
Generates a new list/tuple by list comprehension.
Args:
obj (Union[int, list, tuple]):
If integer, it will be the length of the returned tuple/list.
item: The value to be filled. Default: None.
... | fa23fa13175e7fb3dccd097a05be0080c7a48d4a | 652,834 |
def is_basetype(value):
"""
Returns:
(bool): True if value is a base type
"""
return isinstance(value, (int, float, str)) | d7969ba34f87aa954c9127a0cc89ba3438f3fcbc | 652,835 |
import math
def interleave(left_size, right_size):
""" Finds the number of possible ways to interleave the left and right sub tree
We are interested only in the combinations with fixed ordering, giving the formula:
(left_size + Right_size)! / (left_size! * right_size)
"""
return math.factorial(l... | f23388ba7b9b0c03141e3612328ba9b6740e3502 | 652,836 |
def poly_to_integer(coeffs, order):
"""
Converts polynomial to decimal representation.
Parameters
----------
coeffs : array_like
List of polynomial coefficients in descending order.
order : int
The coefficient's field order.
Returns
-------
int
The decimal r... | 5ab18d47c047ea857eea84226b35b90dc317d557 | 652,837 |
def match_day(text, dtime):
"""
"""
if dtime.strftime(".%Y%m%d-S") in text:
return True
else:
return False | 21100b803959a27af70d96e70b6874e1073fc02d | 652,838 |
from typing import Set
from typing import Tuple
def vertical_flip(state: Set[Tuple[int, int]], additive: bool=False) -> Set[Tuple[int, int]]:
""" Flip the object vertically around the center
:param state: original state
:return: new modified state
"""
max_y = max([t[1] for t in state])
min_y ... | 8eddf7bcbed6b5711e6dceeae524991c93b98d1c | 652,839 |
def sorted_list_difference(expected, actual):
"""Finds elements in only one or the other of two, sorted input lists.
Returns a two-element tuple of lists. The first list contains those
elements in the "expected" list but not in the "actual" list, and the
second contains those elements in the "actual... | bc78dea07aac7a07036428ebca29f478101f8697 | 652,840 |
def signatures():
"""
Multiple signatures can be sent to nushell. Each signature will be registered
as a different plugin function in nushell.
In your plugin logic you can use the name of the signature to indicate what
operation should be done with the plugin
"""
return {
"Signature... | 38330d7ca2a8fdd581e83e5b7de554050e5b6993 | 652,841 |
from typing import Union
import base64
def base64encode(string_or_bytes: Union[str, bytes]) -> bytes:
"""Return base64 encoded input
:param string_or_bytes:
"""
if isinstance(string_or_bytes, str):
string_or_bytes = string_or_bytes.encode()
return base64.encodebytes(string_or_bytes).dec... | 0d321693241e8c3fea34fb3263cba24a51f11546 | 652,842 |
import struct
def read_header(filename):
"""Reads a file's header data and returns a list of wavefile properties"""
wave = open(filename,"rb")
riff = wave.read(12)
fmat = wave.read(36)
num_channels_string = fmat[10:12]
num_channels = struct.unpack('<H', num_channels_string)[0]
sample_rate_... | 74fddcff69951f97094baa576c2ecb6b1e0462e5 | 652,843 |
import ntpath
def get_file_name(file_key):
"""
Returns the name of an email file based on the full s3 file path
:param file_key: the file path
:return: string
"""
return ntpath.basename(file_key) | 898f97c90f6edf862d7b30e2cbd2918bc37c3af2 | 652,844 |
def GenZeroStr(n):
"""Generate a bunch of zeroes.
Arguments:
n -- Number of zeroes
Returns: string
"""
return "".join(["0"] * n) | 744b77789e96cc287b43f1d7080a63722479ce96 | 652,845 |
def patch_response(response):
"""
returns Http response in the format of
{
'status code': 200,
'body': body,
'headers': {}
}
"""
return {
'statusCode': response.status_code,
'headers': dict(response.headers),
'body': response.content.decode(),
'isBa... | 4a4f073e8fa242803b83508c4e581e0be2020fff | 652,846 |
def set_links(graph, *args, **kwargs):
"""Set links between tasks in a :class:`graphcat.Graph`.
This function calls-through to :meth:`graphcat.Graph.set_links`,
and is provided for symmetry with :func:`add_task`.
"""
return graph.set_links(*args, **kwargs) | 6959e1f691e0a43be855c4818e0403fb42f47ce0 | 652,847 |
import argparse
def _make_argument_parser():
"""Create the option parser.
"""
parser = argparse.ArgumentParser(
description='Run SupervisorD check program.')
parser.add_argument('-n', '--check-name', dest='check_name',
type=str, required=True, default=None,
... | 40444b4a898a2952d246cf45f3c3952f9186b3aa | 652,848 |
def formatPrayers(prayers):
"""
Convenience function that re-formats prayer times to a format that is
easier to use with other functions.
For example,
INP: ["2019-01-27", "05:05", "11:53", "14:58", "17:19", "18:49"]
OUT: ["2019-01-27 05:05",
"2019-01-27 11:53",
"2019-01-27 ... | 51fe5bea4831dab2c5be901da0df789b00e053b2 | 652,849 |
import time
def datetime_to_timestamp(date_time):
"""
#把datetime类型转外时间戳形式
:param date_time:
:return:
"""
return time.mktime(date_time.timetuple()) | 0965c71563f01cb22349d1d17cef4d631a835980 | 652,852 |
def format_seconds(ticks):
"""
Given ticks (int) returns a string of format hour:minutes:seconds
"""
seconds = ticks / 20
hours = int(seconds / 3600)
seconds = seconds - hours * 3600
minutes = int(seconds / 60)
seconds = seconds - minutes * 60
seconds = round(seconds, 3)
return s... | 62fa0788ed4db20d5669f99e6423856cf3d46b15 | 652,853 |
def get_plugins_for_doccode(instance, plugins_queryset = False):
"""
Helper to extract all plugin's PK's from DccodePluginMapping instance.
Takes a DoccodePluginMapping instance and extracts all plugin's pk's it uses.
Returns a list of plugin's mapping uses.
WARNING it highly depends on model method... | 46ab93f3139dfdac29d1d877c39098ae65fa4398 | 652,854 |
def f(r: int, t: int, Cf: float) -> float:
"""Calcula el monto de depósito anual teniendo en cuenta la tasa de
interés, el tiempo y el monto a retirar.
:param r: tasa de interes anual
:r type: int
:param t: tiempo
:r type: int
:param Cf: monto a retirar
:r type: float
:return: monto... | 631d65b2376427412483241e52964e70317f7898 | 652,856 |
def single_plotly_figure(site_title: str, figure):
"""
:param figure: plotly graph object or px figure
:return: html style string to generate a site from a single figure
"""
if not isinstance(site_title, str):
raise TypeError("input must be a string")
json_figure = figure.to_json()
... | 20025d46bbbc116830b26a772f8c0c28c3923569 | 652,857 |
import re
def read_data(input_data):
""" Create nodes from input data """
pattern = re.compile(r'(\w+) (inc|dec) ((?:-?)\d+) if (\w+) (>|<|>=|<=|==|!=) ((?:-?)\d+)')
return [re.match(pattern, line) for line in input_data.split("\n")] | 3a38ccdc9496192366afae5ed171df3981f2a427 | 652,859 |
def rescale_layout(Y, scale=1):
"""Return scaled position array to (-scale, scale) in all axes.
The function acts on NumPy arrays which hold position information.
Each position is one row of the array. The dimension of the space
equals the number of columns. Each coordinate in one column.
To resca... | 97d297663a2848e469e021aa1e371535eda6636e | 652,860 |
import json
def gen_send_data(data:str):
"""This function converts the given data to a JSON
string that can be passed to WhatsApp to send a message.
Args:
data (string): The message to be sent.
"""
message_data = {
"data": [
{
"message": data,
... | abdd867f5c27a60fbe65f1327975c09cc2a56d81 | 652,861 |
def blend_channels_multiply(bottom_chan, top_chan):
""" Return combination of bottom and top channels.
Math from http://illusions.hu/effectwiki/doku.php?id=multiply_blending
"""
return bottom_chan[:,:] * top_chan[:,:] | a7778e4188bb76081c64b1ab2d6ec94e8154c917 | 652,863 |
import os
import shutil
def move(source, destination):
"""
moves a file, ensures destination directory exists
:param source: the current full location of the file
:param destination: the desired full location of the file
"""
dest_path, name = os.path.split(destination)
# create th... | e007d1dc191b7e39be36454825a979b1b7076ff8 | 652,865 |
import re
import unicodedata
def get_addon_info(inf_file_name):
"""
Get info about an addon
@param inf_file_name The file name which contains the information about the addon)
@return Dictionary of pairs describing the addon
@returntype dict
"""
info = dict()
param_re =... | 1729320de18a564ca0cc7760b0ca2c99970d4166 | 652,867 |
def modulated_deform_conv_default(ctx, g, input, offset, mask, weight, bias,
stride, padding, dilation, groups,
deform_groups):
"""Rewrite mdcn symbolic function for all backend."""
input_tensors = [input, offset, mask, weight]
if bias is n... | 0e480f261f31f8acc7c64ddda2f67bba84d44e65 | 652,869 |
def _merge_results_by_district(results, iter_data, key, key_name):
"""Return merges data represented by key in iter_data to the results
dictionary.
"""
for row in iter_data:
try:
results[row[key_name]].update({key: row[key]})
except KeyError:
results[row[key_name]... | 10554276c6a98b2fc01879e1a83a8454d029c6ca | 652,870 |
import argparse
from typing import Tuple
from typing import List
import requests
from bs4 import BeautifulSoup
import re
def parse_url(args: argparse.Namespace) -> Tuple[str, List]:
"""
Parse url and extract links
"""
url = args.link
try:
page = requests.get(url)
except requests.excep... | ceb33368cf1dd442934e4bf26e5e87f37c45b4ef | 652,871 |
def _equity_change(net_value, open_cond, cash):
"""
计算资金变化
"""
equity_change = net_value.pct_change()
equity_change.loc[open_cond] = net_value.loc[open_cond] / cash - 1 # 开仓日的收益率
equity_change.fillna(value=0, inplace=True)
return equity_change | 0ddc7b44d75ef52a66f9a328004277e43aa52661 | 652,872 |
def parseElement(e):
"""
almost every element has a Name and a Val so pull these out and
handle null Vals
"""
k = e.find("Name").text
if e.find("Val") is not None:
v = e.find("Val").text
else:
v = None
return (k, v) | cb10f2ec248d0e5a231ef2cba0bad2249398135a | 652,873 |
import torch
def _get_seg_ids(ids, sep_id):
""" Dynamically build the segment IDs for a concatenated pair of sentences
Searches for index SEP_ID in the tensor
args:
ids (torch.LongTensor): batch of token IDs
returns:
seg_ids (torch.LongTensor): batch of segment IDs
example:
... | 22936d9c5d37ab2bb643ae75402710fc097f271e | 652,875 |
def heun_step(f, x0, t0, t1):
"""
One time step of Heun's method
f : function dx_dt(t0, x0)
x0 : initial condition
t0 : this step time
t1 : next step time
"""
# time step
delta_t = t1 - t0
# slope
s1 = f(t0, x0)
# next step by Euler
x1_euler = x0 + s1 * delta_t
... | c36de034d0ec049c3a65a71f217a0e5e1fef2111 | 652,876 |
import requests
def download_insee_excel(url, output_file, verbose=False, check=True):
"""Downloads data from url to an Excel file.
Args:
url (str): An url to request for the excel data.
output_file (str): The output excel filepath.
verbose (boolean): A verbose indicat... | 4c28bbac01e1f8816d9ad02eb71df1333e3f48d2 | 652,877 |
def J2kWh(x):
"""J -> kWh"""
return x/1000./3600. | 63992882b4f8a5bb0c6682f5f0a458e565d4ec4b | 652,878 |
def product_sum(record: list) -> list:
"""Return a list that contains the sum of each prodcut sales."""
return [sum(i) for i in record] | 00db2d32b1b1fc80cb29f6b859edde64d25be78c | 652,879 |
def list_to_empty_dict(data):
"""Recieve list of and return dict with empty keys"""
return {i : "" for i in data} | 8916c523e938eb2a0fc86c2b535f3f086d11afa7 | 652,880 |
def _py_expand_short(subsequence, sequence, max_l_dist):
"""Straightforward implementation of partial match expansion."""
# The following diagram shows the score calculation step.
#
# Each new score is the minimum of:
# * a OR a + 1 (substitution, if needed)
# * b + 1 (deletion, i.e. skipping ... | ef64bbf44707d68d5a528433558dec27a423b619 | 652,881 |
def has_token(request):
"""ユーザーがトークンを持つかどうかをboolで返す
"""
return hasattr(request.user, 'token') | eaa60a28405f0ac1bbbc3c70a8275153df0549fb | 652,882 |
def calc_check_digit(number):
"""Calculate the check digit. The number passed should not have the
check digit included."""
digits = [int(c) for c in number]
checksum = (
7 * (digits[0] + digits[3] + digits[6]) +
3 * (digits[1] + digits[4] + digits[7]) +
9 * (digits[2] + digits[5]... | 05ff30b39c286939d174a01f3f29144a72e3a1df | 652,883 |
def hasextensible(objidd):
"""Return the value of # in extensible:<#>if there is an extensible field.
Return None if there is no extensible fields
from the documentation in the file Energy+.idd:
extensible:<#>
This object is dynamically extensible -- meaning, if you
change the IDD appropriate... | 951cf50a30c2d0fef8f9c97faf9e08b83deff54c | 652,884 |
def sensor_error(raw_sensor_value):
"""Actual sensor error derived from field tests."""
return (raw_sensor_value + 2.5) / 1.32 | bc9cf40071198d38d638326c647c482a49f75a0d | 652,885 |
def is_color(s):
"""Test if parameter is one of Black or Red"""
return s in "BR" | 9fdb97989bfed9596188f1e0b659345afdac4c1d | 652,886 |
from datetime import datetime
import pytz
def utc_offset(time_zone: str) -> int:
"""Convert time zone string to utc offset integer for hour diff."""
now = datetime.now(pytz.timezone(time_zone))
offset = now.utcoffset()
if offset:
return int(offset.total_seconds() / 3600)
return 0 | 0d6e8d69de1f4b374fcff553aa4d105def294f8d | 652,888 |
def data():
"""
A complete dicationary with valid, known, data elements that can
be used in our tests. If it is submitted as is, it should create
all of the elements of the design tables, it can be compromised in
known ways to ensure that the validation captures errors and returns appropriated
e... | 1b391e2c940326bb7572e493a6b58db243d0f40c | 652,889 |
def exponentiate_mod(value, exponent, modulus):
""" Perform the exponentiation."""
result = 1
factor = value
while exponent != 0:
if exponent % 2 == 1:
result = (result * factor) % modulus
factor = (factor * factor) % modulus
exponent //= 2
return result | a82dda9d8e4a3c95769044292eaac3150fcf6ba5 | 652,890 |
def padded_columns(request):
"""Pytest parametrized fixture to return the listed fixtures"""
return request.param | 2e6fb247cc08df07ba2820afec35219829fa5b1f | 652,891 |
def not_rpython(func):
""" mark a function as not rpython. the translation process will raise an
error if it encounters the function. """
# test is in annotator/test/test_annrpython.py
func._not_rpython_ = True
return func | 7d5f36a71844d84093e50485e0598f8e0e257bfd | 652,892 |
def rotate_matrix(m, n):
"""
:type m: list[list[int]]
:type n: int
:rtype: list[list[int]]
"""
max_c = min(len(m), len(m[0])) // 2 if min(len(m), len(m[0])) % 2 == 0 else min(len(m), len(m[0])) // 2 + 1
for c in range(max_c):
for _ in range(n % ((len(m) - 2 * c) * 2 + (((len(m[0]) ... | 253367daaa12be8028503661043a14f7306414d7 | 652,894 |
def type_ev(ev):
"""
Renvoie une chaîne donnant le type de ``ev``. Les types
possibles sont 'ClicDroit', 'ClicGauche', 'Touche' et 'Quitte'.
Renvoie ``None`` si ``evenement`` vaut ``None``.
"""
return ev if ev is None else ev[0] | 9ca55abf57de1669a035e54500c4bccd4891634f | 652,895 |
import re
def collapse_spaces(value):
"""
First replace multiple newlines with a single newline,
then collapse multiple non-newline whitespace characters
"""
return re.sub(r'(?![\r\n])\s+', ' ', re.sub(r'[\r\n]+', '\n', value)) | 60e50e0efe7ca18b8228be8de48a154d159444a6 | 652,896 |
def _adjust_for_radar(obs, prob, prob_from_others):
"""Adds radar-specific weighting to insect probabilities."""
if 'mira' in obs.radar_type.lower():
prob_from_others *= prob['lwp']
return prob_from_others | c779711cd0f32790ecaff0c5190caa6c29e52716 | 652,897 |
def calc_life(trajs, ub=5, lb=-5):
"""
Identifies transition paths and returns lifetimes of states.
Parameters
----------
trajs : list of lists
Set of trajectories.
ub, lb : float
Cutoff value for upper and lower states.
"""
try:
assert ub > lb
e... | 4feeeb9d8dd0e9457db4e8852c38f4de770289b7 | 652,898 |
import re
def is_name_valid(name):
"""
Returns whether a version/project name is valid or not
Args:
name (str): The name of the version
"""
return bool(re.compile(r"^[a-zA-Z0-9.-]+$").match(name)) | c2d14842988db45111912275b84ff7fbbb8003fa | 652,899 |
def pythonize_options(options):
"""
convert string based options into python objects/types
Args:
options: flat dict
Returns:
dict with python types
"""
def parse_string(item):
"""
check what kind of variable string represents and convert accordingly
Args... | 13c79f0d607dfb07bdaafeefaa54f801ebd5b21b | 652,900 |
def nx(request):
"""Number of model states."""
return request.param | 6afb7924e442f30c9d4d5e581b9e51e1a54d0287 | 652,902 |
def get_ns_from_rel(full_ns:str, rel_from:str, comp:str, sep: str = '.') -> str:
"""
Converts a relative import into a full namespace
Args:
full_ns (str): The namespace that import is relative to
rel_from (str): from part of import such as ``..uno.x_interface``
comp (str): Component... | b21ffb2ca3389e9d61a47c793c3cead0e7418621 | 652,903 |
def _walk_stringize_and_case(config): # noqa: C901
"""Walks the various contents of config and:
1. Adds default values if missing
2. Converts to string if not None where appropriate
3. If case_sensitive is False, converts to lowercase where appropriate
Called from normalize()
Args:
c... | 2e79f476669a93d8b8ff5ee39fce11c7087fa550 | 652,904 |
def _empty_filter(arg):
"""Place holder for a filter which always returns True.
This is the default ``image_filter`` and ``collection_filter``
argument for ``fetch_neurovault``.
"""
return True | e131be7b0ee00f5f63c6a2c223aaa274588da74c | 652,905 |
def prepare_embedding_config(args):
"""Specify configuration of embeddings.
"""
# Device
args.ent_emb_on_cpu = args.mix_cpu_gpu
# As the number of relations in KGs is relatively small, we put relation
# emebddings on GPUs by default to speed up training.
args.rel_emb_on_cpu = False
prin... | 790613c3e87e48aae3a50aa14aaec50c12934c2a | 652,906 |
def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
if(len(line) < 1):
return 0
elif(len(line) == 1):
return 1
counter = 0
index1 = 0
index2 = 1
max_temporary = 0
max_finally = 0
run = True
while(run):
... | 21e2b869615567c64055309af9df5748c7c38320 | 652,907 |
def estimatePiSquared(n):
"""
Estimates that value of Pi^2 through a formula involving partial sums.
n is the number of terms to be summed; the larger the more accurate the
estimation of Pi^2 tends to be (but not always).
"""
partialSum = 0 # Initializing
# Implementation of the mathema... | 800506347555f5b6bd693ee5b0e31d66ce696f5d | 652,908 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.