content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def trim_doc(doc):
"""
Strips indentation from a docstring; also removes leading and trailing
blank lines.
`doc`: ``str`` or ``None``
A docstring.
"""
assert isinstance(doc, maybe(oneof(str, unicode)))
# Pass `None` through.
if doc is None:
return None
# Convert to... | 3fc3df4288a053001c1d70c098b461d7aa2e2eb5 | 52,400 |
def abbreviate_id(a_string):
"""
1. Hack off the first 6 and the last 4 characters.
2. Then join them with an ellipsis.
:param a_string:
:return: An abbreviated id string
"""
return str(a_string[0:6]+'...'+a_string[-4::]) | 8127ae7e45638d77c7c0b3c414ea96f64dae7228 | 52,401 |
from re import T
import re
def isbn(value: str) -> T.Union[T.Match[str], None]:
"""
Matched isbn 10 or 13
Example:
978-1-4302-1998-9
1–931836–59–0
1593270127
0 321 15420 7
978-0-07-162612-5
Detail: https://en.wikipedia.org/wiki/International_Standard_Book_Number... | b54f063cca768ae8843c76b828de5f8757d6931a | 52,402 |
import torch
def test(net, testloader):
"""Validate the network on the entire test set."""
criterion = torch.nn.CrossEntropyLoss()
correct, total, loss = 0, 0, 0.0
with torch.no_grad():
for data in testloader:
images, labels = data[0].to(DEVICE), data[1].to(DEVICE)
outp... | 3f9c9e118c612b49e771f79ca24248fb72c052ed | 52,403 |
def reverse_integer(x):
"""Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside
the signed 32-bit integer range [-2^31, (2^31) - 1], then return 0.
:type x: int
:rtype: int
"""
x_string = str(x)
if x_string[0] == "-": # in case t... | 0fead2fbc52e09d9442f9c1f4efe5d7eb4a7e0be | 52,404 |
import typing
def _convertbits(
data: typing.Iterable[int], from_bits: int, to_bits: int, pad: bool
) -> typing.Optional[typing.List[int]]:
"""General power-of-2 base conversion."""
acc = 0
bits = 0
ret = []
maxv = (1 << to_bits) - 1
max_acc = (1 << (from_bits + to_bits - 1)) - 1
for v... | 7794d79b158e157ab8623f298cbc7e56eef5c98c | 52,405 |
from sktime.forecasting.base import ForecastingHorizon
def check_fh(fh, enforce_relative=False):
"""Validate forecasting horizon.
Parameters
----------
fh : int, list, np.array, pd.Index or ForecastingHorizon
Forecasting horizon specifying the time points to predict.
enforce_relative : bo... | 543eeb74a82039884b895c6f1513a0b7970ffc15 | 52,406 |
def should_install_lzo():
"""
Return true if lzo is enabled via core-site.xml and GPL license (required for lzo) is accepted.
"""
config = Script.get_config()
io_compression_codecs = default("/configurations/core-site/io.compression.codecs", None)
lzo_enabled = io_compression_codecs is not None and "com.had... | 65b844aeb2a4fa9f7d13a6b876ca7b4ae9cb016a | 52,407 |
def optimal_compatible_subset(requests):
"""
Get optimal weighted subset
Uses dynamic programming to get the subset
of the requests with the largest weight
"""
dp_weights = dict()
dp_subsets = dict()
finishes = {r.finish for r in requests}
while finishes:
x = max(finishes)
finishes.remove(x)... | 70562bf5289f1608b7ffe918678cadcc1b956e14 | 52,408 |
async def load_accounts(db, names):
"""`get_accounts`-style lookup for `get_state` compat layer."""
sql = """SELECT id, name, display_name, about, reputation, vote_weight,
created_at, post_count, profile_image, location, website,
cover_image
FROM hive_accou... | 91cafae0ddd2a7e27b2be222147f05d15a57c256 | 52,409 |
def imgMakeMask(inImg, threshold=None, forgroundValue=1):
"""
Generates morphologically smooth mask with given forground value from input image.
If a threshold is given, the binary mask is initialzed using the given threshold...
...Otherwise it is initialized using Otsu's Method.
"""
if thr... | 2e54491735c03f3593d2f96283340c52b5bb4cbc | 52,410 |
import requests
def fetch_vacancies(keyword, town=None, catalogues=None, currency=None, period=0, page=0, count=100):
"""Fetch vacancies from SuperJob API, return in json.
Args:
keyword (str):
search the specific vacancies by keyword
town (int, optional):
search vaca... | 2d10e3e518141fe9eec8d03dd53817a75148a2b0 | 52,411 |
import codecs
def OpenDictionary(filenames):
"""Reads the dictionary into a list
"""
print("Opening the Chinese Notes dictionary")
words = []
for dictfile in filenames.split(","):
with codecs.open(dictfile, 'r', "utf-8") as f:
for line in f:
line = line.strip()
if not line:
... | f9c473254984e36ac8ae49b24d20be484416cf23 | 52,412 |
import requests
def api_request(url, api_key=None):
"""
This function takes a url and returns the parsed json object. If necessary, it submits the auth header
"""
if api_key:
return requests.get(url, headers={'Authorization': 'Token ' + api_key}).json()
else:
return requests.ge... | ea8572d761dffb952b970ab14e73307a02f67ee8 | 52,413 |
import torch
def get_device(gpu_idx: int = 0) -> torch.device:
"""
Get default gpu torch device.
:param gpu_idx:
:return:
"""
device: torch.device = torch.device(f"cuda:{gpu_idx}" if torch.cuda.is_available() else "cpu")
# device: torch.device = torch.device(f"cuda:0" if torch.cuda.is_ava... | acc8e9b65b21045cb0dc9a6fb2942d6dab0ce6a2 | 52,414 |
def subjects(subjects=None,
recursive=False,
include_tables=False,
lang=DEFAULT_LANGUAGE):
"""List subjects from the subject hierarchy.
If subjects is not given, the root subjects will be used.
Returns a generator.
"""
request = Request('subjects', *subjects,... | 0d8903904ab1d324870c1565d64d3b5fa1af66b6 | 52,415 |
def getGOState(*args):
"""Access protected class data to evaluate if the Fuel, Liquid Oxygen (LOX), and Control Panel system state are a 'GO' as a 1 by 3 numpy array. This approach is a secure method to access saved system state values. If the system sensor values are all nominal and all three controller panels ope... | 4fd041bc4786334f03a9ca1ff056c6f5a64c79fd | 52,416 |
def interpolate(src, trg, vals, Interpolator, *args, **kwargs):
"""
Convenience function to use the interpolation classes in an efficient way
The interpolation classes in wradlib.ipol are computationally very
efficient if they are applied on large multi-dimensional arrays of which
the first dimensi... | 958fd70389327104f5496dde3525db9a5c08030a | 52,417 |
def cluster_commit():
"""
Commit Cluster Changes
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.cluster_commit
"""
ret = {"comment": "", "success": False}
cmd = __execute_cmd("riak-admin", "cluster commit")
if cmd["retcode"] != 0:
r... | 56146ab9fe8ea6275ac5de140a301abc7d71bf6e | 52,418 |
from sqlalchemy import inspect
def get_map_from_sqlalchemy(a_object):
"""A SQLAlchemy utility to make a dictionary out of an object"""
# this can be done at the front-end side using node.js and JS
# if the programming was done at the front-end
# A variable assigned to the SQLAlchemy object inspectio... | 5a58fd6c5f65ff9bfd0b1179596d8c89cfee97a9 | 52,419 |
import time
from io import StringIO
def get_tick_data(code=None, date=None, retry_count=3, pause=0.001, src='sn'):
"""
获取分笔数据
Parameters
------
code:string
股票代码 e.g. 600848
date:string
日期 format: YYYY-MM-DD
... | b66ba33b6e0bbba61f7a003181d3237165f86df3 | 52,420 |
def config_template_files():
""" Fixture for the config template files """
template_file = {
"input": TEST_DATADIR / "templates/config/sparcc.j2",
"output": TEST_DATADIR / "templates/config/sparcc.config",
}
data = {
"compute_correlations": {"niters": 10},
"resampling": {... | ddb31f9ab029d19dc9017e620893ed118ca232bb | 52,421 |
def normalize_ascii(j_string):
"""
Normalize a double-width ascii string, converting all characters to
their single-width counterparts.
:param six.text_type j_string:
The string to convert.
:return:
The converted string.
"""
result = []
for char in j_string:
... | bbdf1d88f69d923f7ee6ac8df4c284547ed0c16a | 52,422 |
def part_2(data: list[str]) -> int:
""" Figure out the sequence of closing characters for incomplete lines.
Start with a total score of 0. Then, for each character, multiply the total score by 5
and then increase the total score by the point value given for the character.
Returns middle sco... | 33f61dfcdbe351a862e794bf56365c1e4e2840e7 | 52,423 |
def checkfile(file):
"""Checks file to to make sire itsx and itsxpress exited with an exit code of
O and that ITSx did not throw a fatal error message
Args:
file: data file path
Returns:
Bool: True
Raises:
AssertError: if two lines with Exit Status 0 are not present
ValueError: if ITSx returned a fatal... | 62f5aa5be467be99c5be324c3104c623bfae2701 | 52,424 |
def product(id):
"""Display selected product"""
if request.method == "GET":
product = db.session.query(Product).get(id)
addons = db.session.query(ProductAddon).all()
return render_template("product.html", error=check_error(), user=session, addons=addons, product=product)
else: # Edit... | dc8b2b5b9096101fcfedd2f138d751dfb4667853 | 52,425 |
import functools
def debug_log(function):
"""Output debug information to the logger for a function call."""
argument_names = list(function.__code__.co_varnames)
@functools.wraps(function)
def write_log(*args, **kwargs):
argument_values = (
"{} = {}".format(arg, value)
... | feb1b35075cf1b4e6513cb595516000b7f954b6a | 52,426 |
def is_string(s):
"""Check if the argument is a string which works for both Python 2 and 3."""
try:
return isinstance(s, basestring)
except NameError:
return isinstance(s, str) | f40bb9d9128807d3f932e2ac3ec5c1355c3347ab | 52,427 |
def retry(exception_to_check, attempts=3):
"""Decorator to retry a function upon exception.
If the decorated function emits an exception that matches exception_to_check,
the function will be repeated. This will happen a maximum of 'attempts' times.
If none of the attempts were successful, this function raises ... | 99ee08871636b185cf569b84b44f83b349113f25 | 52,428 |
def get_all_task_queue():
"""返回所有原子队列的key
返回类型:list
"""
task_queue = "ztq:queue:task:"
return get_keys(task_queue) | 712b706ce17554042b70f93631f56ada64b33d68 | 52,429 |
def print_permissions(permissions):
"""Prints out a users permissions"""
table = formatting.Table(['keyName', 'Description'])
for perm in permissions:
table.add_row([perm['keyName'], perm['name']])
return table | 6589344a8ca90abd9a85afc058ea44e549cc639b | 52,430 |
def create_cloud_xyz32(header, points):
"""
Create a sensor_msgs.msg.PointCloud2 message with (x, y, z) fields.
:param header: The point cloud header. (Type: std_msgs.msg.Header)
:param points: The point cloud points. (Type: Iterable)
:return: The point cloud as sensor_msgs.msg.PointCloud2.
"""... | 789a86174c3ddc687e735977465c0ebf75f9658c | 52,431 |
import utool as ut
def _test_buffered_generator_general2(
bgfunc,
bgargs,
fgfunc,
target_looptime=1.0,
serial_cheat=1,
buffer_size=2,
show_serial=True,
):
"""
# We are going to generate output of bgfunc in the background while
# fgfunc is running in the foreground. fgfunc takes... | dd086a48b59f4540302fe40b081887ee96f6e5b3 | 52,432 |
def cast_in_array(arg):
"""casts argument into np.array"""
if isinstance(arg, np.ndarray):
return arg
msg = f"Can not cast type({type(arg)}), {arg} in array of floats.\n"
try:
arr = np.array(arg)
except Exception as exc:
raise exc(msg)
arr = np.array(0)
if not ... | 45fe2ee75a7a62a6915f29be30ffe730ad9fa38b | 52,433 |
def check_login() :
""" check if the user is correctly logged. This function is called everytime a user function is called """
if not session.get('workspace_contract') and not session.get('username') :
abort(403)
return True | 734067198b7230165b8c4c9d3cb824ed9d970d39 | 52,434 |
def validator_key(validator_account_and_key):
"""Private key of the validator running the confirmation sender."""
_, key = validator_account_and_key
return key | 365120ee93d30f191a51153505f8164cc588a74f | 52,435 |
def nn50(nni=None, rpeaks=None):
"""Find number of NN interval differences which are greater 50ms (NN50) and ratio between NN50 and total amount of
NN intervals.
References: [Electrophysiology1996], [Ewing1984]
Docs: https://pyhrv.readthedocs.io/en/latest/_pages/api/time.html#nn50-nn50
Parameters
----------
n... | 61d55d365e24dc9c0d48de34068409de07a30d25 | 52,436 |
import typing
import ctypes
def get_random(file_handle: typing.TextIO, length: int = 32) -> bytes:
"""Request random bytes from /dev/nsm."""
if length < 1 or length > 256:
raise ValueError('GetRandom supports length between 1 and 256 inclusive.')
nsm_key = 'GetRandom'
request_data = cbor2.dum... | 51e47a954d4021160c8e18000dcffe7c41f06be9 | 52,437 |
import pandas as pd
def todataframe(table, index=None, exclude=None, columns=None,
coerce_float=False, nrows=None):
"""
Load data from the given `table` into a
`pandas <http://pandas.pydata.org/>`_ DataFrame. E.g.::
>>> import petl as etl
>>> table = [('foo', 'bar', 'baz')... | 9588a547fec8e4f532b89a36969764bf3bd13a86 | 52,438 |
def load(instream, where=None):
"""Load a Windows .FON file."""
data = instream.read()
mz_header = _MZ_HEADER.from_bytes(data)
if mz_header.magic not in (b'MZ', b'ZM'):
raise FileFormatError('MZ signature not found. Not a Windows .FON file')
ne_magic = data[mz_header.ne_offset:mz_header.ne_o... | 363416f69b613f3b7b76d2073682ab2b5ea1e42d | 52,439 |
def trace_predicate (predicate_name, partition, out_path):
"""
TODO: migrate this into `kglab` for unit tests
"""
df = model.get_predicate(predicate_name)._data[partition]
df.columns = [ "P1", "P2", "value" ]
df = df.sort_values(by=[ "P1", "P2" ])
df.to_csv(out_path, sep="\t", index=False)
... | 9aca90e2ed1b963f6d4e322016d3cf1b17c6774b | 52,440 |
def api_get_instances_by_nemea_module_name(module_name):
"""
Returns instances of given NEMEA module
"""
# verify that module exists
nm_model.get_by_name(module_name)
insts = i_model.get_by_nemea_module_name(module_name)
return json_resp(insts) | 74fdbd465c1d0e79422ff3b5ff5191067c696587 | 52,441 |
from typing import Dict
from typing import Callable
from typing import Any
def dispatch_value(default_func):
"""Decorator to select a function implementation according to the value of its fist parameter"""
registry: Dict[type, Callable[..., Any]] = {}
default: Callable[..., Any] = default_func
def re... | de460bc64f17dc5bb24a6995c87f3c4da938b50c | 52,442 |
import requests
from datetime import datetime
from typing import Mapping
from typing import Any
def run_retrohunt(http_session: requests.AuthorizedSession, version_id: str,
start_time: datetime.datetime,
end_time: datetime.datetime) -> Mapping[str, Any]:
"""Run a retrohunt.
Ar... | ba2b54732339e661b7a19b95055cf843ed0a6eb4 | 52,443 |
def calc_theta(pref_cood, local_connectivity_dic, xt=139.69167, yt=35.68944):
""" Returns array of the bearing of a linke between two prefectures.
Parameters
----------
pref_cood : dict[str, Tuple[float, float]]
Dictionary of coordinates of all 47 prefectures.
local_connectivity_dic : dic... | efab02ede396ab1e5c03966928937ae1c4570dac | 52,444 |
def encode_int(value):
"""
Encode integer value into RLP format
:param value: int value
:return: RLP encoded bytes
"""
if value == 0:
s = b""
else:
s = int_to_big_endian(value)
if len(s) == 1 and safe_ord(s[0]) < 128:
return s
return get_length_prefix_str(... | 1a32bbca7409e93323cab3c1c6985eef058a8cff | 52,445 |
import logging
import json
def ext_vnet(test_vars):
"""
Creates a resource group containing a new VNET, subnet, public IP, and
jumpbox for use in other tests.
"""
log = logging.getLogger("ext_vnet")
vnet_atd = ArmTemplateDeploy(
location=test_vars["location"],
resource_group=te... | a9fc889bbfe3d58e4ebe707e5ab22fbaf45693bf | 52,446 |
def ood_detection(y_hat: Prediction, _, y_hat_ood: Prediction, __,
score_type: str = 'AUROC', uncertainty_type: str = 'aleatoric') -> Tensor:
"""convenience function which computes the OOD APR/AUROC scores from model predictions on ID and OOD data based on estimates of 'aleatoric' or 'epistemic' u... | dd51946e911e565e79ec8114bd94d10e445874cf | 52,447 |
from datetime import datetime
def summer_start(timestamp):
"""
Returns 00:00:01 on the Sunday following the 2nd Saturday of April for
the year given in «timestamp», which is the end of Piedmont's Summer period.
"""
year = timestamp.year
apr_7th = datetime(year=year, month=4, day=7, second=1)
... | 0f9a1ac81942606b48a8dee9eb468c25ac6469c8 | 52,448 |
def oval_entity_is_extvar(elem):
"""Check if OVAL entity represented by XML element is OVAL
<external_variable> element
Return: True if <external_variable>, False otherwise"""
return elem.tag == '{%s}external_variable' % oval_ns | f73b76913f8f43d09502514a20e8527d2510920a | 52,449 |
def dispatch_file(file: File):
"""
Dispatch file by extension.
"""
if file.extension in ["jpg", "png", "svg", "gif"]:
return _prepare_image(file)
return """
<div class='panel panel-default'>
<div class='panel-body'>
<p>{}</p>
<a class='btn... | 342716cbf6fe30aae237e09d2d1e38dfdfe395f6 | 52,450 |
def next_day(date, dayOfWeek):
"""
:rtype: Column
>>> from pysparkling import Context, Row
>>> from pysparkling.sql.session import SparkSession
>>> spark = SparkSession(Context())
>>> spark.range(1, 10).select(next_day(concat(lit("2019-11-0"), col("id")), "Mon")).show()
+-------------------... | 399fff8eadfe3505c70269b70e519213142c5527 | 52,451 |
def check_sqlalchemy_results_are_equal(results1, results2):
"""Compare two lists of SQLAlchemy results to see if they are equal"""
list1 = [sqlalchemy_obj_to_dict(item) for item in results1]
list2 = [sqlalchemy_obj_to_dict(item) for item in results2]
return list1 == list2 | 6ad8652babcb984e3e10ffd6b1f4b198abdf20fa | 52,452 |
def dp_longest_palindrome(dp, S, i, j):
"""
Recursive function for finding the longest palindromic
subsequence from a string using a modified version
of the algorithm above
"""
if i == j:
return S[i]
if (i, j) in dp:
return dp[(i, j)]
if S[i] == S[j]:
if i + 1 == j:
dp[([i, j])] = 2 *... | 92d20e8960bffad7254450e93951789fdb6ac306 | 52,453 |
def prediction_measurement_significance(measurement, \
measurement_statistical_error, \
measurement_systematic_error, \
prediction, \
prediction_statistical_err... | c0a3b33da340a59e705718e11f432292dc445b01 | 52,454 |
def add(x, y):
"""
add
:param x:
:param y:
:return:
"""
return x + y | 3d883dd7b5379830c0502209e15ca3db2e5702af | 52,455 |
def index():
"""
Get the index page
"""
return render_template("index.html"), 200 | d97ec0e3dcf24d2d382be20b1d8f0b1714254136 | 52,456 |
def extract_structure_from_csv(csv_file):
"""
Load csv file that contains folder structure information and return it as pandas.datafram.
Parameters
----------
csv_file: str
The file to be loaded.
Returns
-------
pandas.dataframe
A dataframe containing the essential ... | 0951b2e521f2ba240f65f70c211224c08f5475e5 | 52,457 |
import torch
def get_available_devices():
"""Return CPU and, if present, GPU device.
Returns:
[torch.device]: Available devices for `torch`.
"""
devices = [torch.device("cpu")]
if torch.cuda.is_available():
devices.append(torch.device("cuda"))
return devices | a97b5601792d8d1fa87e9c353f87cdcb6497dcf4 | 52,458 |
import os
import time
def file_exist(file_path):
"""check file is exist
:type file_path: file abs path
:return bool file not exist return False else return True
"""
count = 0
while 1:
if os.path.exists(file_path):
return True
if count >= 300:
return Fals... | 4cfcc6f85258ce2fc9938b6fccbb786360bf8bef | 52,459 |
import random
def disruptive_uniform_crossover(dna1, dna2):
"""disruptive uniform crossover
uniformly crossover genes between dna1 and dna2,
with children guaranteed to be different from parents,
if the number of differences between parents is larger than 1
"""
differences = sum(1 for i, j in... | f8ba3f3fe95818d126e3449c88f7cb190708a305 | 52,460 |
def getSplicingEntropy(gene_data):
"""
Calculates splicing entropy and frequency for a given gene
Arguments:
tp_data = DataFrame of splicing mutations in given gene
Returns:
splicingEntropy
fi = highest splicing entropy
"""
sp_data = getSplicingData(gene_data)
[splic... | f8285960cf3503beabbe1d40a6aa4cf2a8347689 | 52,461 |
def _run_fabric(data):
"""
Runs fabric commands on a 'remote' host.
"""
host = data.get('host')
if not host:
app.app.logger.warning("No 'host' specified in request")
data['status'] = 'failed'
data['warnings'] = "No 'host' specified in request"
return False
data[... | 97df551be8d47dab8906d56bdbdc10913f2ca072 | 52,462 |
def getbitlen(bint):
"""
Returns the number of bits encoding an integer
"""
return bint.bit_length() | f6ae3253e767382959d372eb5e4612fb85c89ffc | 52,463 |
def lookstr(table, limit=0, **kwargs):
"""Like :func:`petl.util.vis.look` but use str() rather than repr() for data
values.
"""
kwargs['vrepr'] = str
return look(table, limit=limit, **kwargs) | e3ae0cdd09be47b33328bf2d3e19ada03e520738 | 52,464 |
def do_breaks(probes, segments, min_probes=1):
"""List the targeted genes in which a copy number breakpoint occurs."""
intervals = get_gene_intervals(probes)
bpoints = get_breakpoints(intervals, segments, min_probes)
return pd.DataFrame.from_records(bpoints,
columns=... | 97061c71920b7c6e584070af82d5daa40a4efdea | 52,465 |
def convert_dcc_translation(translation):
"""
Converts given tpDcc translation into a translation that DCC can manage
NOTE: tpDcc uses Y up coordinate axes as the base reference axis
:param translation: list(float, float, float)
:return: list(float, float, float)
"""
if get_up_axis_name().l... | ced1006c939be20a991d0862881d65326abfe1f9 | 52,466 |
def parse_log(log_line, watch_duration=10):
"""Parse a log line and extract interesting sections
:param str log_line: W3C formated log line
:param int watch_duration: Watch duration in seconds
:return: Log fields as :class:`dict`
"""
logger.debug("Line: {}".format(log_line[0:-1]))
match = p... | 4bb7c4b529d35224e11e94319972c43982670e18 | 52,467 |
from os import listdir
from os.path import isfile
from typing import Union
from typing import List
import logging
import os
def fetch_filenames(filenames: Union[List[str], str], data_home=None) -> List[str]:
"""
Fetch images fully qualified filenames for given filenames or
direcoty name.
Parameters
... | 8db46102794e6038aa7ee872191dda8bcbebb1ce | 52,468 |
import tdub.rex
import tdub.config
def rex_stacks(rex_dir, chisq, internal, thesis, png, n_test):
"""Generate plots from TRExFitter result."""
outdir = PosixPath(rex_dir) / "matplotlib"
outdir.mkdir(exist_ok=True)
tdub.config.init_meta_table()
tdub.config.init_meta_logy()
if thesis:
td... | 04d2b953a09f422627d18ab6e1280bf1eebe7272 | 52,469 |
from nevow.context import RequestContext, PageContext
from nevow.testutil import FakeRequest
def flatten(stan, ctx=None):
"""Given the stan and the optional context, return a string containing the
representation of the tree in the given context.
"""
if ctx is None:
ctx = PageContext(tag=None, ... | 55ae1713336e2f7beaa3e05aa9d30a418cfb4789 | 52,470 |
def tenant_is_valid(request):
"""Function will return either True or False depending if a subdomain exists or not."""
return JsonResponse({
'access-granted':True
}) | 665ed42f8417a928eeb0d50c62e96401087dffc8 | 52,471 |
def fp_type02_1(cxt: DecoderContext, fmt: FormatF):
""" CVTF.{LD, LS, ULD, ULS} | NEGF.{D,S} | RECIPF.{D,S} | TRNCF.{DL, DUL, DUW, DW, SL, SUL, SUW, SW} """
# 11 27 4 0 20 16
# 0 0 00001 10010 CVTF.LD
# 0 w 00001 00010 CVTF.LS
# 0 0 10001 10010 CVTF.ULD
# 0 w 10001 00010 ... | 806372bb01c4d70ca60ba0244f07ed9b199f6bd0 | 52,472 |
def create(url, username, course_name, target_dir):
"""
Create a new scraper with a url and name
"""
# ignore = ignore.split(",")
scraper_source = f"""
import sys
from iliasScraper import scraper
if len(sys.argv) == 2:
skip = sys.argv[1]
user = '{username}'
sc = scraper.Scraper(url='{url}', nam... | 32ee3d2d3a4cf4ed93de5cd1bcd08eb019d771ad | 52,473 |
def coors_in_cylinder(x, y, z, centre, axis, radius, length, inside=True):
"""
Select coordinates in a cylinder given by centre, axis and length.
"""
vec = nm.vstack((x, y, z)) - centre
drv = nm.cross(axis, vec, axisb=0)
dr = nm.sqrt(nm.sum(drv * drv, 1))
dl = nm.dot(axis, vec)
if ... | b0b68d09a307bcc3aeda91f627a3e84d70b4d26a | 52,474 |
import inspect
def check_elasticity_parameters( parameterDict ):
"""
Check the elasticity parameters to make sure they are
allowable.
:param dict parameterDict: A dictionary of parameters
"""
#Create a list of constraint equations
constraintEquations = [ le_pce.evaluate_g1, le_pce.eval... | 1e3627c444d18d6b54f685d4731df039e4d0c09e | 52,475 |
def random_walk_z(N, y, W1, W2):
"""
A random walk method for sampling the inactive variables from a polytope.
**See Also**
domains.sample_z
"""
m, n = W1.shape
s = np.dot(W1, y).reshape((m, 1))
# linear program to get starting z0
if np.all(np.zeros((m, 1)) <= 1-s) and np.all(np.z... | 2d0b1f96c857274d600ae9b8a6fb73571a81b729 | 52,476 |
def PyImport_ExecCodeModule(space, name, w_code):
"""Given a module name (possibly of the form package.module) and a code
object read from a Python bytecode file or obtained from the built-in
function compile(), load the module. Return a new reference to the module
object, or NULL with an exception set... | 3a0e93ddb74333e54b9fef8cb970dfc034ec1307 | 52,477 |
def get_delay_val(clock_diff,poly_diff,seconds_ref_clock,seconds_ref_poly,seconds,seconds_offset,v=0,diff_pol=1):
"""
Compute delays at seconds_offset+seconds, considering the offsets for each polynomial (seconds_ref_clock and seconds_ref_poly).
Parameters
----------
clock_diff : list of float... | 8c063a855640d66d76928aea07ebc6f31012fbb3 | 52,478 |
def merge_defaultdicts_list(dicts):
"""
Merge one or several default dictionaries
that have list as their values
into a single one
"""
keys = [key for d in dicts for key in d.keys()]
res_dict = defaultdict(list)
for key in set(keys):
res_dict[key] = merge_length_list([d[key] fo... | 9ddb65d694f3547445f0ff2bed6337130cc2a4f1 | 52,479 |
def calc_word_value(word):
"""given a word calculate its value using LETTER_SCORES"""
word_value = 0
for letter in word:
word_value += LETTER_SCORES[letter.upper()]
return word_value | 5b29f565730b06d056fed4609b1151d072535eb0 | 52,480 |
def calc_word_value(word, score=0):
"""Calculate the value of the word entered into function
using imported constant mapping LETTER_SCORES"""
for w in word:
if not w.isalpha():
continue
score += LETTER_SCORES[w.upper()]
return score | 0ba32b0109dfdfcf4dccba5399841819a46f5e8e | 52,481 |
import os
import re
def _resolve_any_to_text(name, ns, dom):
"""Shell out to dig instead of using RPC because of RPC rate-limiting."""
ret = []
cmdline = ("dig +noadditional +noquestion +nocmd "
"+nostats +nocomment %s any @%s | grep ^%s"
% (name, ns, name))
for line in o... | a97be27b50f4e1bcb6a23d806be8d00d249ce375 | 52,482 |
import six
def bi2bt(num):
"""将无符号整数转换为字节序"""
MSBin = b''
while num > 0:
# if six.PY2:
# MSBin = chr(num % 256) + MSBin
# elif six.PY3:
MSBin = six.int2byte(num % 256) + MSBin
num >>= 8
return MSBin | 87d65b017d7c3ea4129fb7f9cfb14cc17055a437 | 52,483 |
import os
import sqlite3
def cache_init(force_update):
"""Create the 'tooltips.sqlite' database for quick access to tooltips.
As parsing the whole bunch of XML files to find the requested content
each time a tooltip is shown is quite inefficient as well as preserving
the whole content int RAM all the... | b313796c8b0ddde9af0aa7dde5c1554a856c2c73 | 52,484 |
def load_dataset_hierarchical(maxlen,
max_sentence_len):
"""
"""
train_data = 'data/delicious/train-data.dat'
train_labels = 'data/delicious/train-label.dat'
val_data = 'data/delicious/valid-data.dat'
val_labels = 'data/delicious/valid-label.dat'
test_data = 'data/delicious/test-data.dat'
test_labels = 'data/d... | 0340ccb327e40aeed752b91c50d9d5fa45e31c85 | 52,485 |
from s3 import s3_set_default_filter
def job():
""" Jobs - RESTful controller """
def prep(r):
# @todo: for assigments, filter person_id to persons not
# currently assigned to this job
# @todo: for assigments, set default to current user if
# not assigned to thi... | 5be9c5ea39e2b5a3facea9b2787945517905a480 | 52,486 |
import types
def get_display_name(entity):
"""
Gets the display name for the given :tl:`User`,
:tl:`Chat` or :tl:`Channel`. Returns an empty string otherwise.
"""
if isinstance(entity, types.User):
if entity.last_name and entity.first_name:
return '{} {}'.format(entity.first_na... | c72836c4e9ab44cd67a2cb086516b26caade2bb8 | 52,487 |
def calc_max_cpu(records):
""" Returns the CPU usage at the max temperature, ever
:param records: a list of records of min, max temp and associated CPU avg load
:return: a record with the highest recorded temperature, and the associated list of CPU loads
"""
max_temp = 0
cpu_loads = []
for ... | bee21fadb3fcf9cdbbce79f6281f48350b3ffceb | 52,488 |
import random
def integer_or_decimal(entropy, signed):
"""Returns integer or non-integer decimal; 50% probability of each."""
if random.choice([False, True]):
# Represent it as a decimal so that arithmetic operations are supported:
return display.Decimal(integer(entropy, signed))
else:
return non_in... | 023f47da150c3d3c9d115dce218d46ca53ef350b | 52,489 |
def index(request): # 定义请求需要跳转到的网页
"""学习笔记的主页"""
return render(request, 'learning_logs/index.html') | 95696bfab0fcffb4bcfcb3ae789493dad995d14a | 52,490 |
def get_auth_token():
"""Use the heroku auth:token command to fetch the user's API token.
By using the heroku CLI itself we remove the requirement to set up
an environment variable for the token.
"""
r = sarge.capture_stdout('heroku auth:token')
if r.returncode == 0:
return r.stdout.te... | 095f98d65ad68cee8911756ee74421c4d5e2c82b | 52,491 |
import os
import codecs
def get_version():
"""
Extract the __version__ from a file without importing it.
:return: The version that was extracted.
:rtype: :py:obj:`str`
:raises AssertionError: When a version cannot be determined.
"""
path = os.path.dirname(os.path.abspath(__file__))
fi... | 054b4d2c90a35cca058b00b132663b141f44ee0e | 52,492 |
from typing import List
def sort_by_deg(G: nx) -> List[tuple]:
"""
Returns sorted list of nodes by degree
"""
return sorted(nx.degree(G), key=lambda vk: vk[1]) | 0058338cbb83233c5506fae0c9b96da785f7ada8 | 52,493 |
def resnet_qc_101(pretrained=False, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNetQC(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model_ft = models.resnet101(pretrained=True)
mo... | 4ec69021d8cf6c0f8e0db1e36b3c51e0281285af | 52,494 |
import astropy.units as u
def ROI_def(xylnht):
"""
:param xylnht: X, Y, length, height in arcsec
:return: Array containing [x0, xf, y0, yf]
"""
if xylnht[2] < 0:
raise ValueError("Please input positive length and/or height")
x = xylnht[0] * u.arcsec
y = xylnht[1] * u.arcsec
l... | 066a247362635b6b9885b0357115eb5253f05a53 | 52,495 |
import os
async def status():
"""
Return the service status
- Route: `/status`
- Method: `GET`
- Response example:
```json
{
app: {
up_since: "2021-02-05 17:42:13",
version: "0.1.7"
},
projects: [
"quotes"
]
}
```... | ade401d1316637274e9a8b112b402487e1975df7 | 52,496 |
import sys
import os
from pathlib import Path
import traceback
def create_batch_file(application_exe_pyw_file_path=""):
"""
Creates .bat file for the given application / exe or even .pyw BOT developed by you. This is required in Task Scheduler.
"""
global batch_file_path
try:
if not appli... | c02f074369674ec6ddd2fda21342a9155d787c88 | 52,497 |
from pylab import linspace, plot
from clawpack.visclaw import colormaps
import os
import shutil
from typing import Mapping
def setplot(plotdata):
#--------------------------
"""
Specify what is to be plotted at each frame.
Input: plotdata, an instance of clawpack.visclaw.data.ClawPlotData.
Output: a... | 61475b17b0ef784559d19e2da219be4199094287 | 52,498 |
def is_norm(layer, exclude=None):
"""Check if a layer is a normalization layer.
Args:
layer (nn.Module): The layer to be checked.
exclude (type | tuple[type]): Types to be excluded.
Returns:
bool: Whether the layer is a norm layer.
"""
if exclude is not None:
if not... | 71c30db3814bb12589267cbb878f5c877b174fb0 | 52,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.