content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import uuid
def is_uuid_like(val):
"""
Check if value looks like a valid UUID.
"""
try:
uuid.UUID(val)
except (TypeError, ValueError, AttributeError):
return False
else:
return True | 0f5113f9fe6e04e2377a0921257030b7c116aa25 | 34,665 |
def rev_dict(l):
""" Reverse dict or list """
return {k: i for i, k in enumerate(l)} | 0fead05ee47e66bc0fc7f20bfa95309bcf810717 | 34,666 |
def get_summary_of_old_data(old_data):
"""Return a string summarizing the OLD resources that will be created.
"""
summary = [u'\nOLD resources to be created.']
for resource_name in sorted(old_data.keys()):
resource_list = old_data[resource_name]
summary.append(u' %s: %d' % (resource_n... | 7af2b605ccc2d131b6841d586f0c7f9a49728481 | 34,667 |
def shares(shares):
"""Returns integer with comma notation"""
try:
shares = int(shares)
except (ValueError, TypeError, UnicodeEncodeError):
return ''
return '{0:,}'.format(shares) | 89b2dcc444b32c642c53967f445f6cab94cd50eb | 34,668 |
def strToList(text):
""" 将Permutation的密钥转换为list形式 """
try:
listKey = list(map(int, text.split()))
except ValueError:
return -1
else:
for i in range(1, len(listKey)):
if i in listKey:
pass
else:
return -1
return listK... | afb02b6ff0783b995827abdcebe72debf198005e | 34,669 |
def averageGuessesFromGuessMap(guessMap: dict[int, int]) -> float:
"""Return average guesses from map using weighed sum in form <guesses: words>,
e.g <1:20, 3:5> returns 1.75"""
weighedSum = 0
wordsCount = 0
for key,item in guessMap.items():
weighedSum = weighedSum + key*item
wordsCo... | 58d494133386915f7c7c7bc3a75becc129c7ff41 | 34,670 |
import time
def epoch_to_local_date(timestamp: float):
"""Epoch timestamp to `day/month/year - time` representation."""
return time.strftime("%d/%b/%Y - %X", time.localtime(int(timestamp))) | cd4036abb4095fcc56cfaf667408ac4befec1766 | 34,671 |
def read_folds(fname):
""" Reads a list of fold index lists.
Format: let the training set indices range from 0... n_samples-1. Each line
in a fold file should contain a subset of these indices corresponding to a
single fold. For example, let n_samples = 11, then:
0 3 4 8
1 5 9 10
2... | 9146f332dc6da9d212f1dbec95e8a9ff229c6220 | 34,673 |
def combinations_list(max_length):
"""
returns list of combinations of ACGT of all lengths possible
"""
letters = ["0", "A", "C", "G", "T"]
# max_length = 4
b = len(letters) - 1
# base to convert to
n = 0
k = 0
while k < max_length:
n = (n * b) + b
k += 1
#... | 692158d3f9f73a5ccaf0729fd8811d95f3f6cbf3 | 34,675 |
from typing import Callable
from typing import Any
import math
def equal_or_close(rel_tol=1e-6, abs_tol=1e-6) -> Callable[[Any, Any], bool]:
"""Return a function that decides if a ~= b"""
def comparator(a, b) -> bool:
try:
v = math.isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol)
ex... | ad6723302d6470bcb36a65f92929dafa94a96146 | 34,676 |
def get_lang_abbr_from_resp(http_resp):
"""
This function takes a requests object containing a response from
detectlanguage.com, parses it, and returns the abbreviation of
the language detected.
"""
return http_resp.json()["data"]["detections"][0]["language"] | 6635b88306fbc4f149307133c0a118542a8709a9 | 34,677 |
def _reindex_values(new_index, values, initial_value):
"""
Conform values to new index
Parameters
----------
new_index : pandas.Index
values : pandas.Series
initial_value : float
Returns
-------
pandas.Series
"""
first_step = values.index[0]
new_values = values.rein... | 31b1c197ebb47e2d641db21ea5ea1763e0bddb18 | 34,679 |
import os
def check_exist(filename, status):
"""
check_exist(filename, status)
checks to see if filename exists
if status==r, must exist, otherwise prints error + returns False
if status==w, if exists and clobber=no then prints error + returns False
else deletes + returns True
"""
if... | 0ca0bfa0af4de6f21e017f9a1efd225e6ffce2ce | 34,683 |
def map_blocks_adresses(raw, column):
"""
Maps the adresses of the individual blocks from a given raw and column identifier of the 4x8 matrix to the corresponding mosaic identifier (1 to 32) given the following convention
|32|31|30|29|16|15|14|13|
|28|27|26|25|12|11|10| 9|
|24|23|22|21| 8| 7| 6| 5|... | ce256a7d41e332e6bd47e38033b0dfa9df235895 | 34,684 |
def attn_weight_core_fetch(attn_weight, peptide):
"""Accoding to attn_weight to fetch max 9 position
Note: we don consider padded sequenc after valid
"""
max_weight = -float('Inf')
core_bind = ''
for start_i in range(0, len(peptide) - 9 + 1):
sum_weight = sum(attn_weight[start_i: start_i... | 2f23db753497cd0db13a341a2714f25292a90ad0 | 34,685 |
def LCA(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if not root or root is p or root is q:
return root
left = LCA(root.left, p, q)
right = LCA(root.right, p, q)
if left and right:
return root
return left if le... | 1d09d5725dcbbbf3eb44d3dc9048fae1f45fca0f | 34,686 |
import math
def prime_sieve(angka: int) -> list[int]:
"""
mengembalikan daftar dengan semua bilangan prima
hingga ke n
>>> prime_sieve(25)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> prime_sieve(10)
[2, 3, 5, 7]
>>> prime_sieve(2)
[2]
>>> prime_sieve(1)
[]
"""
if angka <= ... | 375a02fe2e355f538f6f967cd83d4ba9821cf36d | 34,687 |
def function_polynomial(data, a, b, c, d):
"""Function used in fitting parameter surface to reflectance-transmittance value pairs.
Used in fitting and in retrieving Blender parameter values.
"""
r = data[0]
t = data[1]
res = a*(r**b) + c*(t**d)
return res | bd1e64f94d1110ceb39bec0cc1073428462e52d3 | 34,688 |
def add_file_to_tree(tree, file_path, file_contents, is_executable=False):
"""Add a file to a tree.
Args:
tree
A list of dicts containing info about each blob in a tree.
file_path
The path of the new file in the tree.
file_contents
The (UTF-8 encod... | c1d10dca15cf25f2f638deda423a7807332d4bb0 | 34,689 |
def _is_whitespace_or_comment(directive):
"""Is this directive either a whitespace or comment directive?"""
return len(directive) == 0 or directive[0] == '#' | c11f19ca8047194f2fe35d17dc7d058f029ccab9 | 34,690 |
import re
def get_easy_apply(soup, verbose=False):
"""
Check if the ad offers "Easy Apply" (only with LinkedIn)
"""
# Usually looks like this:
# <span class="artdeco-button__text">
tag = soup.find("span", class_="artdeco-button__text", string=re.compile("Easy Apply"))
if verbose: prin... | b4350d6a5894a2a6fb7cd70ed96425126561bf3f | 34,691 |
def settingDicts():
""" This dicts is used to make settings form"""
dicts = [
{
"id": 1,
"name": "Bot User OAuth Access Token",
"isEncrypted": False,
"properties": {
"rules": [
{
"re... | 241f70e3915373c43612f4dd1668587987faf5b0 | 34,692 |
import six
import io
def txt_filename(f, fname_or_fh, *args, **kwargs):
"""Decorator to allow seamless use of filenames rather than
file handles for functions that operate on a text file.
Usage
-----
To use this decorator, write the function to take a file object
as the function's first argu... | a20f65ecfbba7b101132ba9f43a2918b0706fc2b | 34,693 |
def clean_data(df, primary_key=None):
""" Drops null & duplicate rows """
if primary_key:
df = df.dropna(subset=[primary_key])
df = df.drop_duplicates(subset=[primary_key], keep='first')
df = df.dropna(how='all')
return df | 62ede4fc6d72c0c1b579816339d839ffd62a0122 | 34,696 |
def get_host(request):
"""
Get host info from request META
:param request:
:return:
"""
return request.META["HTTP_HOST"].split(":")[0] | 926710583bc1a7685b6268851fea757bede560c6 | 34,698 |
import json
def parse_question_task(x):
"""Gather task valid answers"""
annotation_dict = json.loads(x)[0]
if annotation_dict["task"] == "T1":
response = annotation_dict["value"]
else:
response = None
return response == 'Yes' | e5cdaa6fd2d4e11e7689fffe791d7b162bd67003 | 34,699 |
def value_to_bool(value):
"""Return bool True/False for a given value.
If value is string and is True or 1, return True
If value is string and is False or 0, return False
Otherwise if value is numeric or None, return bool(value)
"""
if isinstance(value, bool):
return value
elif isins... | 271d0a33b09b651a7705751a51aa7eab9cc76e55 | 34,700 |
import os
def get_num_part_files():
"""Get the number of PART.html files currently saved to disk."""
num_parts = 0
for filename in os.listdir(os.getcwd()):
if filename.startswith('PART') and filename.endswith('.html'):
num_parts += 1
return num_parts | f67d003ef1922808daef4852dcad751a2e59f466 | 34,701 |
def intoBinary(num):
"""
bin() function converts decimal to binary but does not return value in 8
bits. So we need to add the remaining zeros in order to make it 8 bits, for
which the 'switcher' dictionary is created. For instance if bin() returns
3 bits data, remaining 5 zeros are concatenated.
Input:
'num'... | 200c13daa1d7a0bf9dd16015c2c9ac6e299869aa | 34,702 |
def _canonicalize(name, package=''):
"""
If name is in package, will strip package component.
"""
name = name.replace('/', '.')
if name.startswith('java.lang.'):
return name[len('java.lang.'):]
i = name.rfind('.')
if i != -1 and package + '.' == name[:i + 1]:
return name[i + ... | e8fa0586b2b50d63d72090f3d03f2df09721af30 | 34,703 |
from typing import List
def get_color_scheme_3_channel(color_scheme_length: int) -> List[List[int]]:
"""
Use channel 1, 2 to time_frame_length / 2 and channel 2, 3 for the other half of the time frame
:param color_scheme_length:
:return:
"""
time_frame_split_1 = int(color_scheme_length / 2)
... | d786182407d6b481b679c9bdd00ee189a690bf00 | 34,704 |
def help_message():
"""
:return:
"""
help_text = """
**RERO**
*The multipurpose utility bot for Discord.*
Commands
```ruby
. ?names : List of detected name changes
?pm [on, off, 24/7] : Sends you PM if you get mentioned
?8ball question : Answers a question... | 943b0b840b8f7089b2906500feb8c7b8acf7e160 | 34,705 |
def idfy(var: str, *args):
"""Append ids to the variable."""
for arg in args:
var += '_' + str(arg)
return var | 6d768e5fdc1ec916555cb35ef27d2f27ee8a15e9 | 34,706 |
from operator import eq
from operator import ne
from operator import gt
from operator import lt
from operator import ge
from operator import le
def pruneByParamCmp(dataset, param, cmpoperator, value, interpretation="auto", retrievefailresult=False, comparefailresult=False) :
"""Reduce object list according to certai... | 8361e817ede8f6542dca4996da1d0c1f46a7581e | 34,707 |
from typing import List
def normalize_exchange_amounts(list_act: List[dict]) -> List[dict]:
"""
In vehicle market datasets, we need to ensure that the total contribution
of single vehicle types equal 1.
:param list_act: list of transport market activities
:return: same list, with activity exchang... | 34f0eac421fdb2e317415a0854038e418dc1d90e | 34,709 |
def choose_number():
"""
This function returns an integer from 1 to 5 inclusive (1, 5). It will
continually ask the user for a number if they do not enter valid input until
they do.
"""
valid = range(1,6)
while True:
usr_num = int(input("Enter an integer from 1 to 5 (inclusive): "))
if ... | 6d87c5538ad89ce91dbc27ebca6a8092aa91910f | 34,711 |
import functools
import logging
def require_column(*colnames):
"""Wrapper to coordinate the segment-filtering functions.
Verify that the given columns are in the CopyNumArray the wrapped function
takes. Also log the number of rows in the array before and after filtration.
"""
if len(colnames) == ... | 9f7cba8cb4fca0c7632a9a787d33d9b509573c42 | 34,712 |
import base64
def encode_from_bytes(data: bytes) -> str:
"""
Base64-encodes a sequence of bytes for transmission and storage.
:param data: The byte sequence to encode
:return: string representation of base64-encoded bytes
"""
data_encoded_bytes = base64.b64encode(data)
data_encoded_str = s... | ddb35881394ec18be3832b1181abf0538f60146d | 34,713 |
def digest_lines(digest_input):
"""
Read the lines of the Digest file output
"""
outlines = []
with open(digest_input, 'r') as infile:
for line in infile:
outlines.append(line)
return outlines | fe2627af2a15d51f399364bcfd0c0ef68e4973df | 34,714 |
def cached_property(getter):
"""
Decorator that converts a method into memoized property.
The decorator works as expected only for classes with
attribute '__dict__' and immutable properties.
"""
def decorator(self):
key = "_cached_property_" + getter.__name__
if not hasattr(self... | 5f63f088ea02591e35ad3144bf8a71d67dbec45f | 34,715 |
import uuid
def generate_uuid(value):
"""
Create an id for this dataset earlier than normal.
"""
return str(uuid.uuid4()) | ae64159b6bbc6e6b7423cfdfac71d1d0fee27ec0 | 34,717 |
def topBranchWithSampleCount(node, sampleCount):
"""If a descendant of this node is the topmost branch with sampleCount then return the
descendant. Return self if no descendant is the topmost branch but this node has sampleCount."""
if (node['sampleCount'] < sampleCount):
return None;
if (node[... | 4e7b33e77d6e00a23635593cdb0f1e67df061f20 | 34,718 |
import string
import random
def random_str(size=6, chars=string.ascii_uppercase + string.digits):
"""
Формирует строку из случайных символов
:param size: размер строки
:param chars: сприсок символов для формирования строки
:type size: int
:type chars: str
:return: случайная строка
:rt... | 79732f7aa3ecc1ea27dbb7525a3b8878e72118c9 | 34,719 |
def _match_code_type_re():
"""
匹配codetype
"""
return r'^Code\sType:\s*([a-zA-Z0-9\-]+)\s*$' | 5c3b2cb95c447b51f6e7e5f839f2d39b7b235504 | 34,720 |
def log_approx(input, order=2):
"""
Taylor expansion of log function
input - (N,C) where C = number of classes
order - number of expansions
"""
result = 0
for n in range(1, order+1):
result += (-1)**(n-1) * (input-1)**n / n
return result | 6a3e3514027146704c98d6a0f8068812469d5f12 | 34,721 |
import re
def improve_address(address):
"""
Apply some methods to make the address
clearer to the locator.
:param address: a string
:return: str with improved address
"""
if isinstance(address, dict):
return f"{address['street']}, {address['city']}"
parsed_address = re.split(r"... | f18b49065c3f1b4980fce0c71e9e8dec2a5314ba | 34,722 |
def GetParentDir(savename):
"""Get parent directory from path of file"""
#split individual directories
splitstring = savename.split('/')
parent = ''
#concatenate all dirs except bottommost
for string in splitstring[:-1]:
parent += string + '/'
return parent | 511aefc52fa221aecece1287e622235b26bb8024 | 34,723 |
def check_columns(df, previous_df):
"""前ページと現ページのデータフレーム比較"""
diff1 = set(df.keys()) - set(previous_df.keys())
diff2 = set(previous_df.keys()) - set(df.keys())
return (len(diff1) == 0 and len(diff2) == 0) | d4ce86b9c44e367d4d7eb33de07c0f4bb2737ccb | 34,724 |
def winToPosix(win):
"""Converts the specified windows path as a POSIX path in msysgit.
Example:
win: C:\\home\\user
posix: /c/home/user
"""
posix = win.replace('\\', '/')
return "/" + posix.replace(':', '', 1) | cbdb521cbc6128c1d96f4e73c34d051108e30c88 | 34,725 |
def removeprefix(self: str, prefix: str) -> str:
"""
Removes a prefix from a string.
Polyfills string.removeprefix(), which is introduced in Python 3.9+.
Ref https://www.python.org/dev/peps/pep-0616/#specification
"""
if self.startswith(prefix):
return self[len(prefix):]
else:
return self[:] | c26b99313e4350adf082be7c32a9e8773ba8101e | 34,727 |
def convert_dct_to_matrix(val_dct, name_mat):
""" Take the values dictionary parsed from setval.read and convert
it to a value matrix used to build Z-Matrix objects
"""
val_mat = tuple(tuple(val_dct[name] if name is not None else None
for name in name_mat_row)
... | c3e4febbb0f13362abfccf83ad5ed9342283884c | 34,728 |
def runner(contest):
"""Contest wrapper, needed for multiprocessing implementation"""
try:
result = contest.run()
except KeyboardInterrupt:
# need to raise a non-keyboard interrupt error here to get
# the pool to die cleanly.
# XXX Is there a better way to handle this?
... | 24cc4e3de9fc56fee167fa8e70047041682c6498 | 34,729 |
def integrate_trapezoidal(f, a, b, n):
"""
Approximates the definite integral of f from a to b by the composite trapezoidal rule, using n subintervals.
Input:
- f (function)
- a (float)
- b (float)
- n (int)
"""
a = float(a)
b = float(b)
h = (b - a) / n-1
s =... | 00b83bb58520f0f7c3bd736975418633861d205d | 34,731 |
def __guess_key(key, keys, default_value):
"""Attempts to retrieve a key from a set of keys. There's a somewhat insane
amount of domain specific knowledge here. The keys often change subtley,
and therefore need some tweaking to find the right keys. This is extremely
error prone and should not be trusted... | 6ef66a9e343d4b18cad7aa75a17c3423a732d9b0 | 34,732 |
def asline(iterable, sep=' ', end='\n'):
"""Convert an iterable into a line."""
return sep.join(str(x) for x in iterable) + end | b3ce332d8f78089d4df191c06556f7558c48c096 | 34,733 |
def output_passes_filter(data, filter_from, filter_to):
"""
Check if the data passes the given filter.
:param data: The data tuple to check.
:param filter_to: Filter to only values starting from this value...
:param filter_from: ...Filter to only values ending with this value.
:return: True if t... | b2bc203c6e56647240e1d6376a98feda3a8695e8 | 34,734 |
def format_percentage(val: float, suffix: str = ' %') -> str:
"""
Formats a percentage value (0.0 - 1.0) in the standardized way.
Returned value has a constant width and a trailing '%' sign.
Args:
val: Percentage value to be formatted.
suffix: String to be appended to the result.
R... | 682fc3ea39f3de31ace9a72d80a982aea0fe63af | 34,736 |
def hour_number(N, time):
"""
Takes the day number and time (in hours) and
converts to hour number.
Parameters
----------
N : integer
The day number
time : float
The time in hours (24-hour clock)
Returns
-------
hour : float
The hour number
"""
h... | 058c6752fe531c0a5e3fd91cf23094facb6e5277 | 34,738 |
def list_sum(num_list):
"""Returns the sum of all of the numbers in the list"""
if len(num_list) == 1:
return num_list[0]
else:
return num_list[0] + list_sum(num_list[1:]) | 2145e3b52d7df2f36b99b8d44a81141d2cb98d88 | 34,739 |
def form_field(field):
"""Render the given form field."""
return {'field': field} | 02a580d99a3a8569d0bcc820013062359f95fd7c | 34,740 |
import time
from datetime import datetime
def LeapTime(t):
"""
converts strings to datetime, considering leap seconds
"""
nofrag, frag = t.split('.')
if len(frag) < 6: # IAGA string has only millisecond resolution:
frag = frag.ljust(6, '0')
nofrag_dt = time.strptime(nofrag, "%Y-%m-%d... | 79d2f9be510cd2b3565a7facf47e2385db4ad25c | 34,741 |
import os
def path_to_module_name(filename):
"""Convert a path to a file to a Python module name."""
filename = os.path.relpath(filename)
dotted_path = []
while True:
filename, component = os.path.split(filename)
dotted_path.insert(0, component)
if filename == "":
... | cc29d2cf518d35b41043e0cbe23cfc7138474acb | 34,742 |
import time
def retries(times=3, timeout=1):
"""对未捕获异常进行重试"""
def decorator(func):
def _wrapper(*args, **kw):
att, retry = 0, 0
while retry < times:
retry += 1
try:
return func(*args, **kw)
except:
... | 4e7622a6929dec8cdbda2b14f74f81ca81e587a5 | 34,743 |
import torch
def solarize(image, threshold=128):
"""Invert all values above the threshold."""
return torch.where(threshold <= image, image, 255 - image) | 57e414392e655058c97615ad0cd4f75b3e34bf7c | 34,744 |
def scale_model_weights(weight, scalar):
"""Function for scaling a models weights for federated averaging"""
weight_final = []
steps = len(weight)
for i in range(steps):
weight_final.append(scalar * weight[i])
return weight_final | a3bb3bf4ad31a9b646ec96a084e59b6af04355e9 | 34,745 |
import re
def strip_html_markup(html):
"""
Strip HTML tags from any string and transfrom special entities
"""
text = html
if type(text) == bytes:
text = text.decode('utf-8')
# apply rules in given order!
rules = [
{ r'\s+' : u' '}, # replace consecutive spaces
{ r'\s*<br\s*/?>\s*' : u'... | f1d34027ee4e9408e3f2e5a1e9fce3314c6a6ed1 | 34,746 |
def extract_column_from_header(row):
"""
This function returns the landing status from the HTML table cell
Input: the element of a table data cell extracts extra row
"""
if (row.br):
row.br.extract()
if row.a:
row.a.extract()
if row.sup:
row.sup.extract()
... | b8d4e6a2c9c6b276bb67edcddede372948485d93 | 34,747 |
from typing import List
def build_branches(program: List[dict],
branches_end_nodes: List[int]) -> List[List[int]]:
"""
Build branches (currently only 2 branches are possible) by iterating through
the program. Stop once all branches_end_nodes are reached.
Parameters
---
prog... | 45983c9e0204acdc76dec8572b5f1a74cbc8147f | 34,748 |
def listify(x):
"""Turn argument into a list.
This is a convenience function that allows strings
to be used as a shorthand for [string] in some arguments.
Returns None for None.
Returns a list for a list or tuple.
Returns [x] for anything else.
:param x: value to be listified.
"""
... | d295f85eb6a37fd869c493ffd5da2fdc54927bf4 | 34,749 |
def split_channels(data):
"""
Splits a stereo signal into two mono signals (left and right respectively).
Example:
>>> data_left, data_right = split_channels(data)
"""
if len(data[0]) == 2:
data_l = data[:, 0]
data_r = data[:, 1]
return data_l, data_r
else:
... | 75561b8f4afa7aed727a536dcf0e60c31902f532 | 34,750 |
def fwhm_expr(model):
"""Return constraint expression for fwhm."""
fmt = "{factor:.7f}*{prefix:s}sigma"
return fmt.format(factor=model.fwhm_factor, prefix=model.prefix) | 7c7b8872904b94c7ac6b67b87ecfbc197cec520a | 34,751 |
from jinja2 import Environment, FileSystemLoader
import os
from io import StringIO
def upload_template(c, filename, destination, context=None, template_dir=None):
"""
Render and upload a template text file to a remote host.
"""
text = None
template_dir = template_dir or os.getcwd()
jenv = Env... | 9f64a5acde061d2e20acfe5b8b31395a36e328fe | 34,752 |
import math
def acos(value):
"""Returns the arc cosinus in radians"""
return math.acos(value) | c3c793cb712d17a0da545300ffae7e521ec5ab64 | 34,753 |
import json
def _parse_default(version: int, data: memoryview) -> str:
"""
Default parser for user data sections that are not currently supported.
"""
return json.dumps(None) | 68d86c5757d5684e6383ff3355bdc2c6528310f9 | 34,754 |
import torch
def speye(n, dtype=torch.float):
"""identity matrix of dimension n as sparse_coo_tensor."""
return torch.sparse_coo_tensor(torch.tile(torch.arange(n, dtype=torch.long), (2, 1)),
torch.ones(n, dtype=dtype),
(n, n)) | b8fb388ebfd1c3f28fea02345d905cd9e43bc131 | 34,755 |
def exists(array, previous_arrays):
"""Tests if the array has been seen before"""
for i in previous_arrays:
if array == i:
return True
return False | 1329da3bacb6ff42e836efc4f056ea48fdfb4fc3 | 34,756 |
from typing import List
import requests
def option_sina_sse_list(symbol: str = "50ETF", exchange: str = "null") -> List[str]:
"""
新浪财经-期权-上交所-50ETF-合约到期月份列表
https://stock.finance.sina.com.cn/option/quotes.html
:param symbol: 50ETF or 300ETF
:type symbol: str
:param exchange: null
:type exc... | 3f6254d28be8ae03fd2654edcd49b895e8bcbb86 | 34,757 |
import functools
import importlib
def served_by(service, attribute_name=None):
""" Decorator that connects a service to a service consumer.
"""
def f_wrapper(method):
@functools.wraps(method)
def wrapper(self, *args, **kwargs):
if isinstance(service, str):
serv... | 3835562dcef6ba3dae1fc570b794e0d9696b333c | 34,758 |
def post_data(logged_in_apiclient):
"""Fixture for testing collection creation using valid post data"""
_, user = logged_in_apiclient
input_data = {
"owner": user.id,
"title": "foo title",
"view_lists": [],
"admin_lists": [],
}
return input_data | c8bd2b702f8bca1b33ca0b01e37f6ae83becbe55 | 34,759 |
from typing import List
def index_modules(a_dict: object, keys: List[str]) -> object:
"""Recursively find a syft module from its path
This is the recursive inner function of index_syft_by_module_name.
See that method for a full description.
Args:
a_dict: a module we're traversing
key... | f28247fc00eb7ea0514be1e54b7f77a995779ad1 | 34,761 |
import subprocess
def _q_tx_events(msg):
"""
takes in the msg to say withdraw_validator commission and fill the rest of the flags and commands and pass it into the CLI
"""
# fxcored query txs --events 'message.sender=fxvaloper1c4glwxgvs5vjx9j2w4ef7r4480cfs2dkv7h8u2&message.action=withdraw_validator_co... | 5dc463659d8fbe5566dfdb7217f7b92f994fd40b | 34,762 |
def seconds_to_str(seconds):
""" converts a number of seconds to hours, minutes, seconds.ms
"""
(hours, remainder) = divmod(seconds, 3600)
(minutes, seconds) = divmod(remainder, 60)
return "h{}m{}s{}".format(int(hours), int(minutes), float(seconds)) | edaa063c1d5423c0404a41e83f1a1419891e685a | 34,763 |
import os
import re
def recipe_to_append(recipefile, config, wildcard=False):
"""
Convert a recipe file to a bbappend file path within the workspace.
NOTE: if the bbappend already exists, you should be using
workspace[args.recipename]['bbappend'] instead of calling this
function.
"""
appen... | e5570f626ab400266560316970c3c680dee1a1f3 | 34,764 |
def normalize(img, mean, std):
"""
Normalize image with mean and standard deviation.
Parameters
----------
img : array(float)
The image to normalize
mean : float
The mean used for normalization.
std : float
The standard deviation used for normalization.
... | 9d85497ef251a98d7630bcea694e6f12ba8ab608 | 34,765 |
def sum(a, b):
"""Returns the sum of a, b"""
print("Calculating the sum of %d, %d" % (a, b))
return a + b | 114242f453074eeb687f6b895f594c1c7ae358f7 | 34,766 |
def update_process(process, stock, time=1):
"""
Check if process ended
if so, adding it's output to the stock and setting busy to false.
"""
process.update(time)
if (process.done()):
stock.new(process)
process.end()
return process, stock | 7897ab759cdb2b68239961e11c287f17a8c99687 | 34,769 |
def color_str_green(s):
"""Color string GREEN for writing to STDIN."""
return "\033[1m\033[92m{}\033[00m".format(s) | 4d1a74d4f7b4af27e51076cf04d51031b007773a | 34,771 |
def diffa(dist, alpha, r):
"""
Compute the derivative of local-local BDeu score.
"""
res = 0.0
for n in dist:
for i in range(n):
res += 1.0/(i*r+alpha)
for i in range(sum(dist)):
res -= 1.0/(i+alpha)
return res | 9f5b14da7940eec4a91077b000770f55485cdc45 | 34,773 |
def _qr_R(qr):
"""Extract the R matrix from a QR decomposition"""
min_dim = min(qr.shape)
return qr[:min_dim + 1, :] | 5d3270cf3b1430e81dc933cec72e9d38d91b1653 | 34,775 |
import sys
def lazyf(template):
"""Do a f-string formating."""
frame = sys._getframe(1)
result = eval('f"""' + template + '"""', frame.f_globals, frame.f_locals)
return result | 6382fbc9d2d9eaaaa049fd45336f5d9fa05b192d | 34,776 |
import math
def calculate_parameters(latency, jitter, bandwidth, packetloss, current_parameters):
""" From the network Q4S parameters generats the coder options."""
#pylint: disable=unused-argument
if math.isnan(packetloss):
frame_skipping = 0
elif packetloss == 0:
frame_skipping = 0
... | e7ce1c21b8f97b86e59eefa716e8675c45167584 | 34,777 |
def get_action_key(action, category):
"""
Return a key for indexing an action.
"""
return (action, category) | bc4343e4a00913dd289c1df28602df4410a9b7e4 | 34,781 |
import os
def create_file_names_and_files(number_of_files, begin=""):
"""Creates multiple files if they not exists"""
counter = 0
filenames = []
for i in range(number_of_files):
while True:
filename = begin + str(counter)
if not os.path.isfile(filename):
... | aa2ba7d2aea37326a70ee51d759c48a3c5dc3a27 | 34,782 |
import sys
import traceback
def redact_exception(ex: Exception) -> str:
"""Log an exception in a redacted way. Logs the traceback code line and function name but not the message.
Args:
ex (Exception): The exception to log.
Returns:
str: The redacted exception message.
"""
msg = "... | 11aa76907f7a8490b029f354ad58438d72bb4d79 | 34,783 |
def fields(format_mapping):
"""
Create a formatter that performs specific formatting based on field names.
:type format_mapping: ``Dict[text_type, Callable[[Any, text_type], Any]]``
"""
def _format_field_value(value, field_name=None):
f = format_mapping.get(field_name, None)
if f is... | b199e6955eb53354bf6a111277afe619626fc713 | 34,787 |
import os
import torch
def load_network(filename, model, optimizer=None, **kwargs):
"""
Loads state_dicts to model and optimizer
Parameters
----------
filename: string
file to load from
model: torch.nn.Module
modle to load state_dict to
optimizer: torch.optim.Optimizer or ... | 71c17f0c6bafac567ba9c4c51cbc717f69584854 | 34,789 |
from typing import Iterable
from typing import List
def split(chars: Iterable[str], maxlen: int) -> List[List[str]]:
"""Returns char groups with a fixed number of elements"""
result = []
shatter: List[str] = []
for i in chars:
if len(shatter) < maxlen:
shatter.append(i)
els... | cc320baf00ac67aef8a1bfa919b84e687ead46d5 | 34,790 |
def recuperer_valeur_tag(elem,cle_valeur):
"""
Dans OSM, les attributs d'une relation sont dans les objets tag de l'objet XML de la relation.
Récupérer la valeur associée à la clé cle_valeur
:param elem:
:param cle_valeur:
:return:
"""
# Recherche de tous les éléments tag de l'objet el... | 5b600ce792aeda98b73de879685caa73ef3fd5e3 | 34,793 |
def convert_name(cs):
"""Convert the name of prototype to formal name
"""
def convert_single(_cs):
if isinstance(_cs, str): # convert string name
_cs = cs.lower()
if _cs[0] == "z":
return "zincblende"
elif _cs[0] == "w":
return "wu... | 196b0d95435a77c640bbb8e2392d0735f9fe63e6 | 34,794 |
import os
def get_file_name_pieces(file_path):
"""
Split input file path into the path, the file name without extension, and the extension, and return as a tuple.
Example:
Inputting "/Users/Me/python/src/my_file.py" returns ("/Users/Me/python/src", "my_file", ".py").
Args:
file_path ... | 3470abb4247256bb9fe321c9e210437458f677cb | 34,795 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.