content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def yaml_dump(doc, target=None, transform=None):
"""Dump to the target file. If target is None, return the
dumped yaml as a String. Otherwise return the path to the file."""
yaml = _StringYAML()
yaml.indent(mapping=2, sequence=4, offset=2)
if target is None:
return yaml.dump(doc, transform=t... | eb7c56741f40f45ee9376e0701c1375cb493fea5 | 71,700 |
from .common import CONFIG_TO_CLASS
def create_instance(config, asdict=False):
"""create machine learing model by config"""
class_name = CONFIG_TO_CLASS[config.__class__.__name__]
if asdict:
return class_name(**config.asdict())
else:
return class_name(config) | badd7e1f6edb6fbdbd2dd7a195552036335b5b4e | 71,701 |
def closeMines(user: User) -> int:
"""
Close all open mining games whose end time is due; return
the number of closed games.
"""
client = makeCrabadaWeb3Client(
upperLimitForBaseFeeInGwei=user.config["closeMineMaxGasInGwei"]
)
openGames = fetchOpenMines(user)
finishedGames = [g f... | e21214dd2580dc3fb8f7b3c34b8b6050ba91e2c0 | 71,702 |
def estimate_meters_to_deg(meters, precision=PRECISION_PERSON):
""" Meters to degrees estimation
See https://en.wikipedia.org/wiki/Decimal_degrees
Args:
meters (float)
precision (float)
Returns:
float: meters in degrees approximation
"""
line = PRECISION_TABLE[precision... | 759572fdfb1ee7c33217cb3a15f2d1df272595f3 | 71,703 |
def convert_resolv_conf(nameservers, searchdomains):
"""Returns a string formatted for resolv.conf."""
result = []
if nameservers:
nslist = "DNS="
for ns in nameservers:
nslist = nslist + '%s ' % ns
nslist = nslist + '\n'
result.append(str(nslist))
if searchdo... | 47175fb2dddac151a94b99b1c51942a3e5ca66a1 | 71,704 |
from pathlib import Path
def resolve_model_name(name):
"""
If spaCy is loaded with 'de', check if symlink already exists. If
not, user may have upgraded from older version and have old models installed.
Check if old model directory exists and if so, return that instead and create
shortcut link. If... | 5d40d464f54874c0fdb19144de818e0999218732 | 71,705 |
def slow(data, fs):
"""
Apply slow (S) time-weighting.
"""
return time_weighted_sound_level(data, fs, 1.0) | 7018daa6fbca57f1f424873656bd8bf9ef48eda5 | 71,706 |
def not_found(error):
"""This shows a better looking 404 page."""
return render_template('404.html'), 404 | e62b3eaf7665c01de252600817a17ee79c9a0a91 | 71,707 |
def finiteDifference2D_baru(v, w, nt, dt, nx, dx, nz, dz, g):
"""
2D finite central difference 2nd order. Based on von Neumann Stability analysis,
alpha = v*dt/dx <= 1/sqrt(2).
Parameter
---------
v = velocity model
w = model represented by wavelet
nt,nx,nz = number of time, x and ... | 6c4579941e619b6e43c35629b29083f1edfdb27d | 71,708 |
def fibonacci(n):
"""
Return the nth fibonacci number, that is n if n < 2,
or fibonacci(n-2) + fibonacci(n-1) otherwise.
@param int n: a non-negative integer
@rtype: int
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(3)
2
"""
if n < 2:
return n
else... | 34e0828848130a16dcd0151165941ed6cdcf714d | 71,709 |
def password_okay_by_char_count(pwd_row):
"""
Process list of rows from a file, where each row contains pwd policy and pwd.
Pwd is only valid if the indicated character is found between x and y times (inclusive) in the pwd.
E.g. 5-7 z: qhcgzzz
This pwd is invalid, since z is only found 3 times, bu... | 4571d1d6e47aef1c31257365cd0db4240db93d6c | 71,710 |
def md2py(md, *args, **kwargs):
"""
Converts markdown file Python object
:param str md: markdown string
:return: object
"""
return TreeOfContents.fromMarkdown(md, *args, **kwargs) | 7106e52f12bbce6df2d5155131c3a5b2758f647d | 71,711 |
def calculate_r2(endogenous, residuals):
"""Calculate r2 value of fit.
:param iterable endogenous: vector of observations of endogenous variable.
:param iterable residuals: vector of residuals between modeled fit and observations.
:return: (*float*) -- r-squared value of fit.
"""
sumres = np.sq... | abc4b5488513f613b02eddff9c2ff6ffe728e430 | 71,712 |
def waiting_ride_order() -> jsonify:
"""
获取待乘车的订单
:return:
"""
try:
return jsonify({'code': '1000', 'message': get_waiting_ride_order(g.user.id)})
except NFUError as err:
return jsonify({'code': err.code, 'message': err.message}) | 1fa1477187f7be321796d473b5d011dd43fb2801 | 71,713 |
import numbers
def plot_kmf(df,
condition_col,
censor_col,
survival_col,
strata_col=None,
threshold=None,
title=None,
xlabel=None,
ylabel=None,
ax=None,
with_condition_color="#B38600",
... | 04fdf73dca6d892b21c49c3e0e81c46ff14eacd2 | 71,714 |
import itertools
def tee():
"""Duplicate a sequence by making independent iterators."""
duplicates = itertools.tee('ABC', 2)
duplicates = [''.join(copy) for copy in duplicates]
return duplicates | 33ce3884589c14b789243eb50d74b1f19e942356 | 71,715 |
from typing import Tuple
from typing import List
from typing import Optional
import tokenize
def nlp_preprocess(text: str,
vocab: Vocab,
lowercase: bool = False,
lemmatize: bool = False,
with_lemmas: bool = False,
with_toke... | 7ac3fe883fd07f2328a34bf67ca68a2c4c645d3c | 71,716 |
def pmax(high, low, close, length=None, multiplier=None, offset=None, **kwargs):
"""Indicator: PMAX"""
# Validate Arguments
length = int(length) if length and length > 0 else 7
multiplier = float(multiplier) if multiplier and multiplier > 0 else 3.0
close = verify_series(close, length)
offset = ... | 1629cb472ecc893c8c2592c5911585d686d28ae4 | 71,717 |
import gc
def correlationpass(
fmridata,
fmrifftdata,
referencetc,
fmri_x,
os_fmri_x,
tr,
corrorigin,
lagmininpts,
lagmaxinpts,
corrout,
meanval,
ncprefilter,
optiondict,
rt_floatset=np.float64,
rt_floattype="float64",
):
"""
Parameters
--------... | e3462159906d12dd5cac43884116edabaf37a2a9 | 71,718 |
import re
def check_lookahead(text: str) -> ResultComparison:
""" post: _ """
return compare_results(lambda t: groups(re.match("a(?=b)", t)), text) | a0c069da836fb491e5ef6e27f87a7e3b6f839af3 | 71,719 |
def _getSubjectivityFromScore( polarity_score ):
"""
Accepts the subjectivity score and returns the label
0.00 to 0.10 - Very Objective
0.10 to 0.45 - Objective
0.45 to 0.55 - Neutral
0.55 to 0.90 - Subjective
0.90 to 1.00 - Very Subjective
"""
status = "unknown"
if ( 0... | 16e126032fea92d0eac2d4e6b35c9b6666196ad1 | 71,720 |
import os
import shutil
def upload_file(file, storage_path, allowed_content_type, service):
"""
This will handle all file uploads for malliva
TODO: Remember to create thumbnails of images, resize images and restrict maximum size of uploaded file
"""
if service != "local":
raise HTTPExcepti... | 50ce7cc8ac58da6ec99a635e1934341aa23dc50f | 71,721 |
def has_date_or_time(conf):
"""Check at least date or time is true."""
if conf[CONF_HAS_DATE] or conf[CONF_HAS_TIME]:
return conf
raise vol.Invalid("Entity needs at least a date or a time") | ca404ba5ceade10e8a5b91300b43ea61e13b3a7b | 71,722 |
def get_trajectory_duration(trajectory):
"""This function returns the duration of a given moveit trajectory.
Parameters
----------
trajectory : :py:obj:`!moveit_msgs.msg.DisplayTrajectory`
The computed display trajectory.
Returns
-------
:py:obj:`float`
Trajectory duration ... | d74b2ca3adcc54d938b9031f974cb3cd7ca16f90 | 71,723 |
def calculate_average_popularity(tweet_set):
"""
Calculates average popularity of week_3.tweet set.
Args:
tweet_set: A set of week_3.tweet objects.
Returns:
A float corresponding to the average popularity.
"""
return mean([tweet.calculate_popularity() for tweet in tweet_set]) | 4d47bda24131372a906ce9e95777bb9d470c13a6 | 71,724 |
def order_from_hits(hit_file, by_order=False):
"""
if by_order is True, then the start/stop positions
are the order, not the basepair positions,
so just use that.
"""
if by_order:
return order_from_ordered(hit_file)
seen = {}
list_order = []
bcmp = cmp # faster lookup.
... | d187f17e0268fb1668bcfb94ebb384485a09dcea | 71,725 |
import base64
def extract_basic_auth(auth_header):
"""
extract username and password from a basic auth header
:param auth_header: content of the Authorization HTTP header
:return: username and password extracted from the header
"""
parts = auth_header.split(" ")
if parts[0] != "Basic" or l... | 8f3830bc78b0e9fb6182f130e38acea4bd189c86 | 71,726 |
from typing import List
from typing import cast
def parseUserConfig(userNumber: int, teams: List[ConfigTeam]) -> ConfigUser:
"""
Get the configuration of the given user from the environment
TODO: Use something like Cerberus to make parsing sustainable
"""
userPrefix = f"USER_{userNumber}"
add... | 9aa37264a1fdc4ddd57fe2ec64453232e6f2e93e | 71,727 |
def xor(b1, b2):
"""Expects two bytes objects of equal length, returns their XOR"""
assert len(b1) == len(b2)
return bytes([x ^ y for x, y in zip(b1, b2)]) | 3376df85b52cea276417e29ae81c80208dc28b86 | 71,728 |
def setOfWordsToVecTor(vocabularyList, smsWords):
"""
SMS内容匹配预料库,标记预料库的词汇出现的次数
:param vocabularyList:
:param smsWords:
:return:
"""
vocabMarked = [0] * len(vocabularyList)
for smsWord in smsWords:
if smsWord in vocabularyList:
vocabMarked[vocabularyList.index(smsWord)... | f14d8fed8a59deb44fc14161de8ae1eaf3ee8b00 | 71,729 |
from pathlib import Path
import secrets
def load_env():
""" Loads common settings into the env object.
"""
env = {}
env_path = Path('.') / '.env'
load_dotenv(dotenv_path=env_path)
env['client_id'] = environ[constants.AUTH0_CLIENT_ID]
env['callback_url'] = environ[constants.AUTH0_CALLBACK_... | 6dbf63bcd03488b7058aaa39f087b32097137ef3 | 71,730 |
def non_contradiction_instance_1(person_list,
place_list,
n,
vi_function=vi,
not_vi_function=not_vi):
"""
T = {v(x1,P1), ..., v(xn,Pn)}
new = not v(xi,P*) ----------- 0
P* ... | eea26798c451f8772e62df8e1085594bccdf8fbc | 71,731 |
def delete_exploit():
"""
Changes exploit relevent to 0
"""
if not is_logged():
return render_template('login.html', projects=projects, show_create_project=IS_ENV_SAFE)
exploit_id = request.args.get("id")
db.change_relevent_to_zero(session["db"], "exploits",exploit_id)
retu... | 457ebc8c3d2f2250871080037c416010d4f3d35d | 71,732 |
def getTestSuite(select="unit"):
"""
Get test suite
select is one of the following:
"unit" return suite of unit tests only
"component" return suite of unit and component tests
"all" return suite of unit, component and integration tests
"pending" ... | c33b95db028f462ad5912fcf1ac0e9e9413e7fb7 | 71,733 |
import re
def is_valid_file(filename):
"""
Validates file is of type obj
:param filename: str
"""
return re.match(r'^.+\.?(obj|asm)$', filename) is not None, filename[-3:] | 6f0032693f0097f85ec09e802a2ab870095a232e | 71,734 |
import re
def clean_description(text):
"""The original datasource introduces some common, incorrect encodings.
Fix them here"""
text = text.replace("\u00c2\u00bf", "'")
text = re.sub(r"<\s*br\s*/?>", "\n", text, flags=re.IGNORECASE)
text = re.sub(r"</\s*br>", "", text, flags=re.IGNORECASE)
ret... | 6778c32058137c7af1d99bf52baaa0889a559e95 | 71,735 |
def LinearTransformation(translation, rotation, x, y):
"""
Apply linear transformations to a set of positions in 2 dimensions.
INPUTS
translation : translation vector
rotation : rotation matrix
x : x-coordinates
y : y-coordinates
OUTPUTS
x : transformed x coo... | e674f215c46ecc6f46da0c1e7074210583f59088 | 71,736 |
def seaborn_cdfplot(data, y, **kwargs):
"""
Wrapper to CDF calculated by hand.
Please see seaborn_FacetGridplot() for parameter list
"""
return seaborn_FacetGridplot(data, y, kind="cdf", **kwargs) | 7f2e1aa22338cd40d3b93b0bfd5e4172cd20d4fc | 71,737 |
import os
def dbscan_pharmacophore(ligands, radius=1, eps=2, min_samples=0.75, feat_list=None, feat_def=None):
"""
Compute a ligand based pharmacophore from a list of ligands, using a density based
clustering algorithm.
Parameters
----------
ligands : list of rdkit.Chem.rdchem.Mol or rd... | b8131a497dd3a27d316c72224b819f734b0898d9 | 71,738 |
def get_safe(dic, *keys):
"""
Safely traverse through dictionary chains
:param dict dic:
:param str keys:
:return:
"""
no_d = dict()
for key in keys:
dic = dic.get(key, no_d)
if dic is no_d:
return None
return dic | 17f810ba995314088f93152179e988df436adb47 | 71,739 |
import torch
def squeeze(input_, axis=None):
"""Wrapper of `torch.squeeze`.
Parameters
----------
input_ : DTensor
Input dense tensor.
axis : None or int or tuple of ints, optional
Axis or axes to operate on, by default None
"""
return torch.squeeze(input_._data, dim=axis) | 57bde66b7fb7f3c91ce8661291bd40d233d98c6f | 71,740 |
from typing import OrderedDict
import collections
def vg_reader(locus_file, gam_file):
"""
input: sorted locus and sorted GAM file output from vg.
output: sorted readset for core DP.
assumptions:
1. locus file consists of linear ordering of simple bubbles only and hence sorted. Each locus file does not contain ... | ccdf6ffaf18475321b553e8e2ecfa1130ac69f2c | 71,741 |
import uuid
def check_constraint_naming_convention(constraint, table):
"""
Creates a unique name for an unnamed CheckConstraint.
The generated name is the SQL text of the CheckConstraint with
non-alphanumeric, non-underscore operators converted to text, and all
other non-alphanumeric, non-undersc... | 5f697be2fa59d9913a79f2dcdae22de4d3268b2f | 71,742 |
import os
import torch
def model_fn(model_dir):
"""Load the PyTorch model from the `model_dir` directory."""
print("Loading model.")
# First, load the parameters used to create the model.
model_info = {}
model_info_path = os.path.join(model_dir, 'model_info.pth')
with open(model_info_path, 'r... | c6ca81e49b7c7de170f8c44aeb0b3fec230505ac | 71,743 |
import random
import string
def random_string(length=1, unicode=False):
"""
Returns random ascii or unicode string.
"""
if unicode:
def random_fun():
return chr(random.choice((0x300, 0x2000)) + random.randint(0, 0xff))
else:
def random_fun():
return random.c... | 45760b3e3c42e484d51abf76f9eb2ae0c8132fd1 | 71,744 |
import os
from pathlib import Path
import urllib
import gzip
def _download_uri(parsed_uri: ParseResult) -> bytes:
""" Return decompressed data from url """
if parsed_uri.scheme == "s3":
assert BOTO3_AVAILABLE, "Use 'pip install boto3'"
s3_client = boto3.client(
"s3",
en... | ce2d164b3bdc50bcad7a138b13fa6774f5ff77b6 | 71,745 |
from typing import Union
import numpy
def get_default_image(
shape: ImageShape,
tile_factor: int = 0,
shade: bool = True,
as_image: bool = False,
name: str = "lena",
) -> Union[numpy.ndarray, Image.Image]:
"""
Loads default image from resources and reshape it to size
shape.
:param... | de007c5570854b1eba4bf60709f8dabdf5f0c29a | 71,746 |
import re
import sys
def convert_clrmame_dat(input_dat, is_folder):
""" Converts CLRMAMEPro dat format to LogiqX dat format """
input_dat.contents = ''.join(input_dat.contents)
clrmame_header = re.search('^clrmamepro \($.*?^\)$', input_dat.contents, re.M|re.S)
def header_details(find_string, replac... | 1074d8ff829ca5b45cc35943bbc01653c64596d5 | 71,747 |
def validate_file(file_name, package):
"""Validate a file, return array of errors"""
errors = []
if package is None:
all_allowed = ALL_ALLOWED_ORDER[:]
else:
all_allowed = [EXTERNAL] + \
INTERNAL_ALLOWED_ORDER[INTERNAL_ALLOWED_ORDER.index(package):] + [RELATIVE]
allowed =... | 5ab5629b1233ee75a452fa50f830136308749bb6 | 71,748 |
def compact(number):
"""Convert the number to the minimal representation. This strips the
number of any valid separators and removes surrounding whitespace."""
court, registry, number, qualifier = _split(number)
return ' '.join(x for x in [court, registry, number, qualifier] if x) | 8db23f329057b48450509b61f221e2b1ab2888bb | 71,749 |
def dynamicauth_api3(request):
"""
动态二维码验证的第三步,PC 端检查自己是否登录成功
"""
return json_response_zh(get_json_ret(0 if request.user.login_status else 51)) | 0db1369bd84b675f193f7e9af547be77d51cb957 | 71,750 |
import random
def audio_data():
"""
POST:
description: save audio recording to cloudinary
request body:
required: true
content:
multipart/form-data:
'recording': <blob>
'english_term': <string>
responses:
... | 8ffaf14a20f70e20b7b5b315ef0ef905d7c11819 | 71,751 |
import os
import subprocess
def is_mysql_running():
"""
Returns True if mysql is running, False otherwise.
"""
# We need to check whether or not mysql is running as a process
# even if it is not daemonized.
with open(os.devnull, 'w') as os_devnull: # lint-amnesty, pylint: disable=bad-option-v... | 56aa092863f9de700952c423901326660bd29383 | 71,752 |
def showlastmonth(request):
"""Show last month environment pressure, humidity and temperature."""
logger.debug('start')
tMonth = timezone.now().replace(day=1)
lMonth = tMonth - timedelta(days=1)
bme280s = BME280.objects.filter(measure_date__month=lMonth.month)
title = 'Show last month pressure, ... | 702ada4ed70646b884d57e94373a264671170df8 | 71,753 |
def comparePaths(path1,path2,pointsToCheck=3):
"""
open paths before closed paths
outer paths come before inner ones
otherwise, top to bottom bounds, left to right
"""
if closed(path1) and not closed(path2):
return 1
elif closed(path2) and not closed(path1):
return -1
... | fea7cd2566334d3ff1de42241a0109f9d828e05a | 71,754 |
import math
def probability(ec, en, t):
"""
Probability function
:param ec: current energy
:param en: next energy
:param t: temperature ratio
:return: probability value
"""
return math.exp((ec - en) / t) | c055081cd93473ecf4abeab1c8b5cc36fb38f0a4 | 71,755 |
def pad_X(X, maxsize):
"""
Pad Xs out to same length
"""
X_padded = []
X_lengths = []
for x in X:
diff = len(x) - maxsize
X_lengths.append(len(x))
if diff < 0:
X_padded.append(list(x) + ["*"]*np.abs(diff))
elif diff > 0:
X_padded.append(lis... | c08cc410dd864c931aec7beb30838aad38bc9405 | 71,756 |
from typing import Dict
from typing import Any
from typing import Tuple
def tag_batch(
model: EncodersDecoders,
batch: Dict[str, Any],
criterion=None,
optimizer=None,
) -> Tuple[Dict[str, float], Dict[str, Sentences]]:
"""Tag (apply POS) on a given data set."""
preds, losses = run_batch(model,... | 819dcb0f1457ce6e5f28cccba6dda12d79160124 | 71,757 |
def request(coap_url, method=MethodCode.get, payload=None):
""" A wrapper to make a single request.
Example - coap.request('coap://coap.me/hello')
"""
url = urlparse.urlparse(coap_url)
if url.scheme.lower() not in ['coap', '']:
raise Exception('Not a CoAP URI')
coap = Coap(host=url... | dca9008863bc7794c291da7f2e6401c778c3bda2 | 71,758 |
def helicsQueryExecuteComplete(query: 'helics_query') -> "char const *":
"""
complete the return from a query called with /ref helicsExecuteQueryAsync
the function will block until the query completes /ref isQueryComplete can be
called to determine if a query has completed or not
Parameters
... | a87e2712371847916fef79b8dd84ec316bd90937 | 71,759 |
from typing import Union
from typing import Mapping
from typing import Iterable
def hist(data: Union[pd.DataFrame, pd.Series],
column=None, key_column=None,
bins=35, ticks=None, xmin=None, xmax=None, ylog=False,
color=None, cumulative=False, stacked=False,
xlabel=None, ylabel=None,... | a81d1d81c37d7e373b6461c442584cd480c97c03 | 71,760 |
def make_adj_set():
"""Get the set of adjectives that appear in the corpora both as <adj> and
un<adj>.
This avoids picking up adjectives that don't make since with an un or
without an un.
"""
all_adj = make_adj_superset()
un_adj = make_unadj_set()
return set(word for word in all_adj if ... | b4324010d576534a55b246bd70ec5075e3e7a9c6 | 71,761 |
def RL_num_steps():
""" returns integer """
return num_steps | ad27af9ab17022c2c12ec513edca594430eecda9 | 71,762 |
def run_as_thread(func):
"""
Decorator for making a function run as a new thread
:param func: the function to run
:return: the resulting thread object
"""
@wraps(func)
def thread_func(*args, **kwargs):
thread = Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = Tru... | b30fd47b1b7df4063356e41c09506a036de149b5 | 71,763 |
def project_to_output_distributions(
inputs,
output_spec,
project_to_discrete=layers.factored_categorical,
project_to_continuous=layers.normal,
outer_rank=1,):
"""Project a batch of inputs to distribution objects.
Args:
inputs: An input Tensor of shape [batch_size, None].
output_spec: A... | e71afad9d5c3b61eb4c5fa137283595acb43bf58 | 71,764 |
def grid(m, dtype=np.float32):
"""Return the embedding of a grid graph."""
# Adapted from https://github.com/mdeff/cnn_graph/blob/master/lib/graph.py
M = m**2
x = np.linspace(0, 1, m, dtype=dtype)
y = np.linspace(0, 1, m, dtype=dtype)
xx, yy = np.meshgrid(x, y)
z = np.empty((M, 2), dtype)
... | 7dde58309b05050b0b7895fb07fc32176206f546 | 71,765 |
def handle_db_exception(error):
"""TODO just a demo function."""
return {'message': str(error.error)}, error.status_code | d416cef03ed836bab7e750acb17c158ffda9e3e6 | 71,766 |
import functools
def getModel(mdlParams, placeholders):
"""Returns a function for a model
Args:
mdlParams: dictionary, contains configuration
is_training: bool, indicates whether training is active
Returns:
model: A function that builds the desired model
Raises:
ValueError: If model name is no... | b08dde9a3e22af8749ec16ae2fd0b697da673f08 | 71,767 |
import re
def get_crumble_and_cookie(symbol):
"""gets auth keys for the url i.e. crumble and coookie"""
link = crumble_link.format(symbol)
response = urllib2.urlopen(link)
match = re.search(cookie_regex, str(response.info()))
cookie_str = match.group(1)
text = response.read()
match = re.se... | e41599de76a30136ce16b28f4dd0844ed7e5584c | 71,768 |
def getGamesListUrl(user_name, page, block_size=100):
"""Returns lichess url for downloading list of games"""
URL_TEMPLATE = "https://en.lichess.org/api/user/{}/games?page={}&nb={}"
return URL_TEMPLATE.format(user_name, page, block_size) | 314bc8771628944dde1e52299697362482afd9b1 | 71,769 |
def set_motor_manual(motor, motor_state):
"""
Turn a motor, defined by <motor>, on or off, according to <motor_state>.
:param motor_state: On (1) or off (0).
:param motor: The string that identifies one of the four motors on the process.
:return: Empty HTTP 200 response
"""
plc.set_motor(mot... | aba9f95e70b833c84c2acbe64a6bcbd3e62c572c | 71,770 |
def _equalize(image, _):
"""Equalizes the image (as defined in PIL).
Args:
image: A tf.uint8 tensor.
Returns:
The equalized image.
"""
return autoaugment_utils.equalize(image) | 74928125cb1dde2b611eaded727291ea70e309b2 | 71,771 |
from typing import List
def get_current_nodes(inventory) -> List[str]:
"""Return the current nodes' names (group 'nodes') from the inventory as a list."""
return get_nodes_for_homek8s_group(inventory, 'nodes') | 3132a2d6142b0328716574f3a0923110ec41f0df | 71,772 |
def msg2question(msg: dns.message.Message) -> str:
""" Helper function to return a string of name class and type
"""
question = "<empty>"
if len(msg.question):
q = msg.question[0]
name = q.name.to_text()
qclass = dns.rdataclass.to_text(q.rdclass)
qtype = dns.rdatatype.to_... | b425ae4878980f77063b01e07af7b9bb5d8999c4 | 71,773 |
def snp_induced_protein_changes(snp_df, genome):
"""Given a df of {chr, pos, ref, alt} SNP information,
this extracts all ensembl transcripts where the snps induce a protein change.
Result is a dictionary: transcript_stable_id -> altered amino acid sequence"""
potentially_affected_transcripts = snp_hit_... | f80ace15c7d0a9538ddbc39fb9d96fc21e663a67 | 71,774 |
def add_ext(name, ext, seq=-1):
"""add_ext constructs file names with a name, sequence number, and
extension.
Args:
name (string) - the filename
ext (string) - the file extension
seq (int) - the number in a sequence with other files
(Default -1) means that it is a standalone
file
"""
#add peri... | 650eee088ae58d182c49f35f37e5b8deac57fa1d | 71,775 |
def mjd_fromheader2(hd):
"""
return modified Julian date from header
"""
secinday = 24*3600.0
date = hd['DATE-OBS']
ut = hd['UTC']
datetu = date.replace('-',':')
mjd0,mjd,i = GLOBALutils.iau_cal2jd(int(datetu[0:4]),int(datetu[5:7]),int(datetu[8:10]))
ut =... | 49cef2c7e29ab4c8d28feda68213367ace9ec2ff | 71,776 |
import unicodedata
def is_chars_diff_by_diacritic(char1, char2):
"""Check whether two characters differ only by diacritic.
"""
if isinstance(char1, str):
char1 = unicode(char1, encoding='utf-8')
if isinstance(char2, str):
char2 = unicode(char2, encoding='utf-8')
char1_d = unicoded... | 88d3d63154a258f73f589d1f561eb215071cde60 | 71,777 |
import tqdm
def fetch_many_docs(iso_ids, nproc=1):
"""
Args:
iso_ids ([int]): list of iso_ids to fetch
nproc (int): number of processes to use, if greater than 1, will use
larger number of processes
Returns:
([dict]) list of fetched documents
"""
if nproc > 1... | 504e5b19c96ee2936361836dd4c917284491004b | 71,778 |
def my_filter(func, k):
"""Функция"""
res = []
for i in k:
if func(i):
res.append(i)
return res | e0c5367c0aa5f2da6bf07fc6b9c8e4b10a88d86b | 71,779 |
def assd(pred, label, voxelspacing=None, connectivity=1):
"""compute the average symmetric surface distance
It's not the mean value of asd1(average surface distance) and asd2,
which is calculated in medpy's assd.
Args:
pred: prediction array
label: label array
... | 157c798a36709dafcf63734d64c628a30be3a751 | 71,780 |
def requires_end(func):
"""
Decorator raises error if there is no end specified for the EventList
"""
@wraps(func)
def _requires_end(self, *args, **kwargs):
if not self.end:
raise ValueError(
f"EventList's {func} method requires the 'end' attribute to be set."
... | c523eb51c19c219b6e7330c79077d49cd4a221c5 | 71,781 |
def is_rgb(image):
"""
Check if given image is in RGB color space.
:param image: checked image
:return: result of the check (boolean value)
"""
RGB_DIMENSION_COUNT = 3
return len(image.shape) == RGB_DIMENSION_COUNT | fc5ef58d96f60c105aa4b526c3d710906ea8c343 | 71,782 |
def life_support_rating(numbers):
"""
Calculates the life support rating of a list of numbers.
"""
return calc_co2_rating(numbers) * calc_oxygen_rating(numbers) | 4fa8d400e9ded1ec9f907520b3eade59db85d63f | 71,783 |
def get_coding_annotation_fasta(seq_record):
"""
When passed a sequence record object returns an array of FASTA strings for each annotation.
:param seq_record: A Biopython sequence record object.
:return: A FASTA file string containing all sequences record object CDS sequence features.
"""
fasta = []
features =... | 4fa24279ebb89ea7c61eeae6614c1fa309ffad87 | 71,784 |
from typing import Union
def bars_to_atmospheres(bar: float, unit: str) -> Union[float, str]:
"""
This function converts bar to atm
Wikipedia reference: https://en.wikipedia.org/wiki/Standard_atmosphere_(unit)
Wikipedia reference: https://en.wikipedia.org/wiki/Bar_(unit)
>>> bars_to_atmospheres(3... | d460021395af77acda01296710f145e9b52d8594 | 71,785 |
def get_ast(token):
"""
Recursively unrolls token attributes into dictionaries (token.children
into lists).
Returns:
a dictionary of token's attributes.
"""
node = {}
# Python 3.6 uses [ordered dicts] [1].
# Put in 'type' entry first to make the final tree format somewhat
# ... | 3074b6a64061dd5cfb2209d803ab060203dfec06 | 71,786 |
def find_frequent_itemsets(data_iter, minSupport):
"""
run the apriori algorithm. data_iter is a record iterator
Return both:
- items (tuple, support)
- rules ((pretuple, posttuple), confidence)
"""
# read from csv
itemSet, transactionList = getItemSetTransactionList(data_iter)
fre... | 00d21f251b409d17b4ba51ec7b9f86941060bd6d | 71,787 |
def dropbox_fileupload(dropbox, request):
""" accepts a single file upload and adds it to the dropbox as attachment"""
attachment = request.POST['attachment']
attached = dropbox.add_attachment(attachment)
return dict(
files=[dict(
name=attached,
type=attachment.type,
... | 84a89a8b8a21c3a78105d8ef911ee6aba71206f2 | 71,788 |
def series(expr, x, point=0, n=6, dir="+"):
"""Series expansion of expr around point `x=point`.
See the doctring of Basic.series() for complete details of this wrapper.
"""
return expr.series(x, point, n, dir) | fee3fff7a29136813c7d6bf5d1cf7c576651368d | 71,789 |
from typing import Literal
def context_command(type: Literal["user", 2, "message", 3], name=None, guild_ids=None, default_permission=None, guild_permissions=None):
"""
Decorator for cogs that will register a context command in discord
``Right-click message or user`` -> ``apps`` -> ``commands is di... | 97ed539c903dc2004af5804769fcfafa2b5a17b0 | 71,790 |
import numpy
def hz2mel(hz):
"""Convert frequency to Mel frequency.
Args:
hz: Frequency.
Returns:
Mel frequency.
"""
return 2595*numpy.log10(1+hz/700.0) | 0d0138d038ed402fd158379ab023addda93e7bcb | 71,791 |
def live_color_command_formatter(src):
"""Formatter wrapper."""
try:
console, colors = execute(src.strip())
el = _color_command_console(colors)
if not colors:
el += '<div class="swatch-bar"></div>'
el += colorize(console, 'pycon', **{'python3': True, 'stripnl': Fal... | 7c49a79121468d9600a5910550ae03c8475c535b | 71,792 |
from src.model import CNN3
def load_model():
"""
加载本地模型
:return:
"""
model = CNN3()
model.load_weights('./models/cnn3_best_weights.h5')
return model | 2c164dffc7f45a2e7455349ac583121b187681f5 | 71,793 |
def process_transform_funcs(trans_funcs, func_args=None, func_kwargs=None):
"""Process input of the apply_transform_funcs function.
:param iterable trans_funcs: functions to apply, specified the function or a (function, args, kwargs) tuple
:param dict func_args: function positional arguments, specified as ... | 2e9fe4bec55f0a13a0644cfe27ba887f00e85c55 | 71,794 |
def _flattensome(state, write, schedule, result):
"""
Take strings from an iterator and pass them to a writer function.
@param state: An iterator of C{str} and L{Deferred}. C{str} instances will
be passed to C{write}. L{Deferred} instances will be waited on before
resuming iteration of C{... | 9780ae0944b428693716ce61c697072410f57990 | 71,795 |
def not_found(environ, start_response):
"""serves 404s."""
start_response('404 NOT FOUND', [('Content-Type', 'text/html')])
return [to_bytes('''<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /??????? was not ... | 080c5dfb5c4f301f2c327e9773526b24608683eb | 71,796 |
import math
def _get_fov(pillow_image) -> float:
"""Get the horizontal FOV of an image in radians."""
exif_data = pillow_image.getexif()
# 41989 is for 'FocalLengthIn35mmFilm'.
focal_length = exif_data[41989]
# FOV calculation, note 36 is the horizontal frame size for 35mm
# film.
return ... | 9b8101010a980079d950b6151a3d5280d5eedb73 | 71,797 |
def split_vertex(G, v, splitInstructions):
"""
Splits the vertex v into two new vertices, each with
edges depending on s. Returns True if the split
divided the graph, else False.
"""
new_index = G.vcount()
G.add_vertex()
G.vs[new_index]['CONGA_orig'] = G.vs[v]['CONGA_orig']
# adding... | 9e48ede85275f0bc7649d85f9351837fd7d8dbea | 71,798 |
def effective(file, line, frame):
"""Determine which breakpoint for this file:line is to be acted upon.
Called only if we know there is a bpt at this
location. Returns breakpoint that was triggered and a flag
that indicates if it is ok to delete a temporary bp.
"""
possibles = Breakpoint.bpli... | e630dd5c64699229839cf0d4cc686d14dab2ea2c | 71,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.