content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def set_diff(seq0, seq1):
"""Return the set difference between 2 sequences as a list."""
return list(set(seq0) - set(seq1)) | 5,352,400 |
def convert_examples_to_features(examples, label_list, max_seq_length, tokenizer, output_mode):
"""Loads a data file into a list of input features."""
'''
output_mode: classification or regression
'''
if (label_list != None):
label_map = {label : i for i, label in enumerate(label_list)}
features = []
for (ex... | 5,352,401 |
def test_set_wrapper():
"""
Wrapper function to compute test datasets of fixed widths using multiprocessing.
Widths are defined in the parameter file.
Ouputs are in Neural/ folder
"""
from .parameter import ModelParameters
import multiprocessing as mp
from .neural import test_dataset
a = ModelParameters()
wid... | 5,352,402 |
def get_unapproved_csr_names(kubeconfig_path: str) -> List[str]:
"""
Returns a list of names of all CertificateSigningRequest resources which
are unapproved.
May raise SubprocessError
"""
return [
csr["metadata"]["name"]
for csr in oc_list(kubeconfig_path, "csr")
if not ... | 5,352,403 |
def iteritemsdeep(dct):
"""
Works like ``dict.iteritems`` but iterate over all descendant items
>>> dct = dict(a=1, b=2, c=dict(d=3, e=4))
>>> sorted(iteritemsdeep(dct))
[(('a',), 1), (('b',), 2), (('c', 'd'), 3), (('c', 'e'), 4)]
"""
for (key, val) in dct.items():
if isinstance(va... | 5,352,404 |
def nmea_decoder(sentence: str, data: dict, mag_var: float) -> None:
"""
Decodes a received NMEA 0183 sentence into variables and adds them to current data store
:param sentence: received NMEA sentence
:param data: variables extracted
:param mag_var: Magnetic Variation for conversion true to magnet... | 5,352,405 |
def function(n, m, f):
"""Assumes that n = m = 1. The argument f is a Python function that takesas input an n-bit string alpha and
returns as output an m-bit string f(alpha). See deutschTest for examples of f. This function returns the (n +
m)-qbit gate F that corresponds to f. """
F = np.zeros((... | 5,352,406 |
def get_study_list_qs(user, query_dict):
"""Gets a study list query set annotated with response counts.
TODO: Factor in all the query mutation from the (view) caller.
TODO: Upgrade to Django 2.x and use the improved query mechanisms to clean this up.
Args:
user: django.utils.functional.SimpleL... | 5,352,407 |
def get_life_stages(verbose: bool = False) -> pd.DataFrame:
"""Get table of life stages.
Parameters
----------
verbose : bool
If True, prints the SQL statement used to query the database.
Returns
-------
pandas DataFrame
"""
return __basic_query(LifeStage, verbose=verbose) | 5,352,408 |
def bytes_to(value_in_bytes: float, rnd: int | None = ...) -> str:
"""
:param value_in_bytes: the value in bytes to convert
:param rnd: number of digits to round to
:return: formatted string
"""
sizes = ["bytes", "KB", "MB", "GB", "TB"]
now = int()
while value_in_bytes > 1024:
va... | 5,352,409 |
def lambda_handler(event, context):
"""Main Function"""
page_iterator = PAGINATOR.paginate(**OPERATION_PARAMETERS)
for page in page_iterator:
functions = page['Functions']
for function in functions:
funct = {
"Name": function['FunctionName'],
"Ver... | 5,352,410 |
def _find_first_print(body):
""" This function finds the first print of something """
for (i, inst) in enumerate(body):
if isinstance(inst, ir.Print):
return i
return -1 | 5,352,411 |
def main():
"""
Handles parameters for the file to run
:return:
"""
input_path = sys.argv[1]
output_path = sys.argv[2]
support_thresold = int(sys.argv[3])
broadcast = 1
if len(sys.argv) > 4:
broadcast = int(sys.argv[4])
pcy = PCYFrequentItems(is_debug=True)
if broad... | 5,352,412 |
def clear_screen():
"""
Clears Python Interpreter Terminal Window Screen
"""
try:
command = 'cls' if os.name in ('nt', 'dos') else 'clear'
os.system(command)
except:
pass | 5,352,413 |
def list_mix(set_key, encoding, in_set = ""):
""" Returns: Seeded Random Shuffle of Input Set by Input Key. """
if in_set == "": char_set = list(encoding["set"])
else: char_set = in_set
seed(set_key)
return sample(char_set, len(char_set)) | 5,352,414 |
def leslie(f, s):
"""Create a Leslie matrix.
Given the length n array of fecundity coefficients ``f`` and the length n-1
array of survival coefficients ``s``, return the associated Leslie matrix.
Args:
f (cupy.ndarray): The "fecundity" coefficients.
s (cupy.ndarray): The "survival" coe... | 5,352,415 |
def __convert_node(node, default_value='', default_flags=vsflags()):
"""Converts a XML node to a JSON equivalent."""
name = __get_attribute(node, 'Name')
logging.debug('Found %s named %s', node.tagName, name)
converted = {}
converted['name'] = name
switch = __get_attribute(node, 'Switch')
... | 5,352,416 |
def generate(generations, population, nn_param_choices, dataset, dataset_TB_folder_name):
"""Generate a network with the genetic algorithm.
Args:
generations (int): Number of times to evole the population
population (int): Number of networks in each generation
nn_param_choices (dict): P... | 5,352,417 |
def document(input_file, output_path=None, recursive=False, prefix=None):
"""
Handler for documenting CMake files or all files in a directory. Performs
preprocessing before handing off to document_single_file over all detected
files. Also generates index.rst files for all directories.
:param input_... | 5,352,418 |
def clean():
"""
cleans shopyo.db __pycache__ and migrations/
Parameters
----------
Returns
-------
None
...
"""
if os.path.exists("shopyo.db"):
os.remove("shopyo.db")
print("shopyo.db successfully deleted")
else:
print("shopyo.db doesn't exist... | 5,352,419 |
def clone(output, replace=None, *args, **kwargs):
"""
Use as theano.clone().
TODO: Something useful with non-symbolic output ?
"""
if not core.is_theano_object(output):
raise ValueError("`shim.graph.clone()` is undefined for non-symbolic outputs")
return core.gettheano().clone(output, re... | 5,352,420 |
def get_clustermgtd_heartbeat(clustermgtd_heartbeat_file_path):
"""Get clustermgtd's last heartbeat."""
# Use subprocess based method to read shared file to prevent hanging when NFS is down
# Do not copy to local. Different users need to access the file, but file should be writable by root only
# Only u... | 5,352,421 |
def logout():
"""
Logs out user by deleting token cookie and redirecting to login page
"""
APP.logger.info('Logging out.')
resp = make_response(redirect(url_for('login_page',
_external=True,
_scheme=APP.config['SCHEM... | 5,352,422 |
async def test_templates_with_valid_values(opp, calls):
"""Test templates with valid values."""
with assert_setup_component(1, "vacuum"):
assert await setup.async_setup_component(
opp,
"vacuum",
{
"vacuum": {
"platform": "template",... | 5,352,423 |
def fileDescribe(*args, **kwargs):
"""
.. deprecated:: 0.42.0
Use :func:`file_describe()` instead.
"""
print("dxpy.fileDescribe is deprecated; please use file_describe instead.", file=sys.stderr)
return file_describe(*args, **kwargs) | 5,352,424 |
def ATR(df, n, high_column='High', low_column='Low', close_column='Close',
join=None, dropna=False, dtype=None):
"""
Average True Range
"""
high_series = df[high_column]
low_series = df[low_column]
close_prev_series = df[close_column].shift(1)
tr = np.max((
(high_series.value... | 5,352,425 |
def setup_logging(outdir):
"""
Setup logging system.
Log is written to 'mergeFastqs.log'.
Args:
outdir: Output directory
"""
logger = logging.getLogger("mergeFQs")
logger.setLevel(logging.DEBUG)
if not os.path.exists(outdir):
os.makedirs(outdir)
log_file = os.pat... | 5,352,426 |
def pytest_addoption(parser):
""" Load in config path. """
group = parser.getgroup(
"Aries Protocol Test Suite Configuration",
"Aries Protocol Test Suite Configuration",
after="general"
)
group.addoption(
"--sc",
"--suite-config",
dest='suite_config',
... | 5,352,427 |
def lookup(symbol):
"""Look up quote for symbol."""
# Contact API
try:
api_key = os.environ.get("API_KEY")
url = f"https://cloud-sse.iexapis.com/stable/stock/{urllib.parse.quote_plus(symbol)}/quote?token={api_key}"
response = requests.get(url)
response.raise_for_stat... | 5,352,428 |
def get_full_history(sender, dialog_id):
"""Download the full history for the selected dialog"""
page = 0
limit = 100
history = []
print('Downloading messages...')
while True:
sleep(REQUEST_DELAY)
offset = page * limit
try:
history[0:0] = sender.history(dia... | 5,352,429 |
def test_mul_same_number():
"""Test a case where we multiply
"""
result = num2 * num2
assert result.val == 4
assert result.jacobian(num2) == 4 | 5,352,430 |
def predict_transposition_cost(shape, perm, coefs=None):
"""
Given a shape and a permutation, predicts the cost of the
transposition.
:param shape: shape
:param perm: permutation
:param coefs: trained coefficients or None to get
the default ones
:return: dictionary of features
"... | 5,352,431 |
def checkBuildAMR(parfile,cellfile,**kwargs):
"""
Purpose
-------
Check that BuildAMRfromParticles.f90 builds the cells around the particles
created by mkClouds.f90 in the right places.
Only cloud cells are plotted. If you want to include the field cells, in
BuildAMRfromParticles.f90's subr... | 5,352,432 |
def dist(df):
"""
Calculate Euclidean distance on a dataframe.
Input columns are arranged as x0, x1, y0, y1.
"""
return np.sqrt((df.iloc[:,0] - df.iloc[:,2])**2 + (df.iloc[:,1] - df.iloc[:,3])**2) | 5,352,433 |
def B_Calc(T, n=2):
"""
Calculate B (Constant in the mass transfer term).
:param T: cell operation temperature [K]
:type T : float
:param n: number of moles of electrons transferred in the balanced equation occurring in the fuel cell
:type n: int
:return: B as float
"""
try:
... | 5,352,434 |
def get_page_likes(response):
"""Scan a page and create a dictionary of the image filenames
and displayed like count for each image. Return the
dictionary."""
# find all flowtow divs
flowtows = response.html.find_all('div', class_='flowtow')
result = dict()
for div in flowtows:
# ge... | 5,352,435 |
def firm(K, eta, alpha, delta):
"""Calculate return, wage and aggregate production.
r = eta * K^(alpha-1) * L^(1-alpha) + (1-delta)
w = eta * K^(alpha) * L^(-alpha)
Y = eta * K^(alpha) * L^(1-alpha) + (1-delta) * K
Args:
K: aggregate capital,
eta: TFP value,
alpha: out... | 5,352,436 |
def test_function_of_add_user_command_with_data_well(session):
"""
GIVEN the add_user function
WHEN when the function is called
THEN check for the user creation
"""
from app.commands import add_user
username = get_unique_username()
password = '123'
add_user(username, password)
... | 5,352,437 |
def get_col(arr, col_name):
""" returns the column from a multi-dimensional array """
return map(lambda x : x[col_name], arr) | 5,352,438 |
def get_articles(id):
"""function that process the articles and a list of articles objects
"""
get_articles_url = articles_url.format(id, api_key)
with urllib.request.urlopen(get_articles_url) as url:
news_article_results = json.loads(url.read())
news_article_object = None
... | 5,352,439 |
def check_slot_exist(start_time,end_time):
"""
Description:
check_slot_exists is responsible for checking that a slot exists
before a volunteer can create it.
Parameters:
Takes two parameters of type datetime:
start_time:datetime
end_time:datetime
return... | 5,352,440 |
def format_relative_date(date):
"""Takes a datetime object and returns the date formatted as a string e.g. "3 minutes ago", like the real site.
This is based roughly on George Edison's code from StackApps:
http://stackapps.com/questions/1009/how-to-format-time-since-xxx-e-g-4-minutes-ago-similar-to-stack-exchange-si... | 5,352,441 |
def task_install_book():
"""install the jupyter book and sphinx dependencies"""
if not jb:
yield dict(
name="install book deps",
actions=['pip install --rdocs/requirements.txt'],
targets=[config_changed(jb)]
) | 5,352,442 |
def Jacobian_rkhs_gaussian(x, vf_dict, vectorize=False):
"""analytical Jacobian for RKHS vector field functions with Gaussian kernel.
Arguments
---------
x: :class:`~numpy.ndarray`
Coordinates where the Jacobian is evaluated.
vf_dict: dict
A dictionary contai... | 5,352,443 |
def predict_images(detection_graph: tf.Graph, image_path: str, output_path: str, output_csv_path: str,
threshold: float = 0.3, save_csv: bool = True) -> Tuple[np.ndarray]:
"""Predict detection on image
Args:
detection_graph (tf.Graph): Graph of model to detect
image_path (str... | 5,352,444 |
def load_pickle(file):
"""Gets the file from the cPickle file."""
f = open(file, 'r')
d = cPickle.load(f)
f.close()
logger = get_logger()
logger.info("file %s loaded" % file)
return d | 5,352,445 |
def test_register_op_with_extending_steps_works():
"""
Calling the custom pipeline operation with an argument should yield the same
arguments passed back as a result
:return:
"""
test_pipe = Pipeline(STEPS, **PIPELINE_DEF_KWARGS)
def custom_op(doc, context=None, settings=None, **kwargs):
... | 5,352,446 |
def get_dates_for_last_30_days(
end_date: date,
) -> Tuple[Tuple[date, date], Tuple[date, date]]:
"""Returns dates for running RCA on the last 30 days.
The first tuple contains t-61, t-31.
The second tuple contains t-30, t.
"""
rca_start_date = end_date - timedelta(days=30)
base_end_date = ... | 5,352,447 |
def get_3rd_friday():
"""获取当前月的第三个星期五"""
first_day_in_month = datetime.now().replace(day=1) # 本月第一天
# 获取当前月的所有星期5的日
fridays = [i for i in range(1, 28) if (first_day_in_month + timedelta(days=i - 1)).isoweekday() == 5]
if len(fridays) < 3:
raise Exception(f'获取当前月异常:{fridays}')
# 第三个星期五... | 5,352,448 |
def retrieve_article_pdf_from_ads(bibcode, eprint_or_pub="PUB"):
"""
Get the PDF file for a given bibcode
"""
endpoint = f"{eprint_or_pub.upper()}_PDF"
safe_bibcode = quote(bibcode)
pdf_filename = f"{safe_bibcode}_{eprint_or_pub.lower()}.pdf"
url = f"{LINK_GATEWAY_BASE_URL}/{safe_bibcode}/{e... | 5,352,449 |
def get_account_info():
"""account information"""
method = 'GET'
path = '/open/api/v2/account/info'
url = '{}{}'.format(ROOT_URL, path)
params = _sign(method, path)
response = requests.request(method, url, params=params)
return response.json() | 5,352,450 |
def str_product(string):
""" Calculate the product of all digits in a string """
product = 1
for i in string:
product *= int(i)
return product | 5,352,451 |
def convolution_filter_grad_backward(inputs, base_axis=1, pad=None, stride=None,
dilation=None, group=1, channel_last=False):
"""
Args:
inputs (list of nn.Variable): Incomming grads/inputs to/of the forward function.
kwargs (dict of arguments): Dictionary of the ... | 5,352,452 |
def do_after_terminate(source, after_terminate):
"""Invokes an action after an on_complete() or on_error() event.
This can be helpful for debugging, logging, and other side effects
when completion or an error terminates an operation
on_terminate -- Action to invoke after on_complete or throw is call... | 5,352,453 |
def _get_dload_scale(dload,
xyz_scale: float,
velocity_scale: float,
accel_scale: float,
force_scale: float) -> None:
"""
LOAD asssumes force
"""
if dload.Type == 'LOAD':
scale = force_scale
elif dload.Type =... | 5,352,454 |
def job_complete(job):
"""
Should be called whenever a job is completed.
This will update the Git server status and make
any additional jobs ready.
"""
job_complete_pr_status(job)
create_issue_on_fail(job)
start_canceled_on_fail(job)
ParseOutput.set_job_info(job)
ProcessCommands... | 5,352,455 |
def direct(sp_script_str, run_dir, nsamp, njobs,
tgt_geo, bath_geo, thy_info, charge, mult,
smin=3.779, smax=11.339, spin_method=1, ranseeds=None):
""" Write input and run output.
:param sp_script_str: submission script for single-point calculation
:type sp_script_str: str
... | 5,352,456 |
def test_force_grid_wrap() -> None:
"""Ensures removing imports works as expected."""
test_input = "from bar import lib2\nfrom foo import lib6, lib7\n"
test_output = isort.code(
code=test_input, force_grid_wrap=2, multi_line_output=WrapModes.VERTICAL_HANGING_INDENT
)
assert (
test_ou... | 5,352,457 |
def corpus_loader(folder: str):
"""
A corpus loader function which takes in a path to a
folder.
"""
# iterate through all file
for file in os.listdir(folder):
file_path = f"{folder}/{file}"
yield read_text_file(file_path) | 5,352,458 |
def naive_scheduler(task_qs, max_workers, old_worker_map, to_die_list, logger):
""" Return two items (as one tuple) dict kill_list :: KILL [(worker_type, num_kill), ...]
dict create_list :: CREATE [(worker_type, num_create), ...]
In this scheduler model, there is min... | 5,352,459 |
def run(ceph_cluster, **kwargs) -> int:
"""
Method that executes the external test suite.
Args:
ceph_cluster The storage cluster participating in the test.
kwargs The supported keys are
config contains the test configuration
Returns:
0 - Suc... | 5,352,460 |
def search_item(search_term, next=False, page=0, board=0):
"""function to search and return comments"""
if next == False:
page = requests.get("https://www.nairaland.com/search?q=" + urllib.parse.quote_plus(str(search_term)) + "&board="+str(board))
else:
page = requests.get("https://www.nair... | 5,352,461 |
def is_valid_action(state, x, y, direction):
"""
Checks if moving the piece at given x, y coordinates in the given direction is valid, given the current state.
:param state: the current state
:param x: the x coordinate of the piece
:param y: the y coordinate of the piece
:param direction: the d... | 5,352,462 |
def range_(minimum, maximum):
"""
A validator that raises a :exc:`ValueError` if the initializer is called
with a value that does not belong in the [minimum, maximum] range. The
check is performed using ``minimum <= value and value <= maximum``
"""
return _RangeValidator(minimum, maximum) | 5,352,463 |
def sigmoid_prime(z):
"""Helper function for backpropagation"""
return sigmoid(z) * (1 - sigmoid(z)) | 5,352,464 |
def register_widget_util(ui_name, some_type, gen_widgets, apply_with_params):
"""
ui_name: the name of this utility in the UI
some_type: this utility will appear in the sidebar whenever your view function
returns a value of type ``some_type``
gen_widgets(val): a function that takes the report valu... | 5,352,465 |
def _CreateSamplePostsubmitReport(manifest=None,
builder='linux-code-coverage',
modifier_id=0):
"""Returns a sample PostsubmitReport for testing purpose.
Note: only use this method if the exact values don't matter.
"""
manifest = manifest or _... | 5,352,466 |
def create_doc_term_matrix():
"""
Load document-term matrix from disk into memory
"""
df = None
if os.path.isfile(DOCTERM_PICKLE):
print('Saved dataframe found! Loading saved document-term matrix...')
df = pd.read_pickle(DOCTERM_PICKLE)
else:
print('Could not find saved document-term matrix, loading from ... | 5,352,467 |
def _fetch_measurement_stats_arrays(
ssc_s: typing.List[_NIScopeSSC],
scalar_measurements: typing.List[niscope.ScalarMeasurement],
):
"""
private function for fetching statics for selected functions.
Obtains a waveform measurement and returns the measurement value. This
method may return multipl... | 5,352,468 |
def test_load_model():
"""
GIVEN: The model defined inside classifier.py (L21)
WHEN: Checking that the correct model is being passed in, by looking on the model.get_config()['handle'].
THEN: The full path to the model.
"""
model = c.load_model()
assert 'https://tfhub.dev/google/aiy/vision/cl... | 5,352,469 |
def test_cyren_feed_relationship_with_search_response(mocker, indicator):
"""
Given: File hash indicator.
When: Running cyren_feed_relationship command.
Then: Verify expected results returns
"""
from CyrenThreatInDepthRenderRelated import cyren_feed_relationship
args = dict(indicator=indica... | 5,352,470 |
def on_close_commit_buffer(commit_msg_filepath):
"""Actually trigger the commit.
on_close_commit_buffer(str) -> None
"""
r = _get_repo_for_tempfile(commit_msg_filepath)
try:
with open(commit_msg_filepath, 'r') as f:
success, msg = r.commit(f)
print(msg)
except Fi... | 5,352,471 |
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
"""Grow a stack of block devices.
This function is called recursively, with the childrens being the
first ones to resize.
@type disk: L{objects.Disk}
@param disk: the disk to be grown
@type amount: integer
@param amount: the amount (in meb... | 5,352,472 |
def nativeMouseY(self):
"""
TOWRITE
:rtype: qreal
"""
scene = self.activeScene() # QGraphicsScene*
if scene:
qDebug("mouseY: %.50f" % -scene.property("SCENE_MOUSE_POINT").y()) # .toPointF().y())
if scene:
return -scene.property("SCENE_MOUSE_POINT").y() # .toPointF().y()
... | 5,352,473 |
def generate_repository_dependencies_folder_label_from_key( repository_name, repository_owner, changeset_revision, key ):
"""Return a repository dependency label based on the repository dependency key."""
if key_is_current_repositorys_key( repository_name, repository_owner, changeset_revision, key ):
la... | 5,352,474 |
def weighted_characteristic_path_length(matrix):
"""Calculate the characteristic path length for weighted graphs."""
n_nodes = len(matrix)
min_distances = weighted_shortest_path(matrix)
sum_vector = np.empty(n_nodes)
for i in range(n_nodes):
# calculate the inner sum
sum_vector[i] = (1/(n_nodes-1)) *... | 5,352,475 |
def doctor(cli):
"""Basic QMK environment checks.
This is currently very simple, it just checks that all the expected binaries are on your system.
TODO(unclaimed):
* [ ] Compile a trivial program with each compiler
"""
cli.log.info('QMK Doctor is checking your environment.')
ok = True
... | 5,352,476 |
async def process_name(message: types.Message, state: FSMContext):
"""
Process user name
"""
async with state.proxy() as data:
data['name'] = message.text
await RegisterForm.next()
await message.reply("How old are you?") | 5,352,477 |
def preproc(config):
"""Preprocess the CNN on Illumina reads using the supplied configuration."""
# Set the number of cores to use
max_cores = config['Devices'].getint('N_CPUs')
# Set input and output paths
neg_path = config['InputPaths']['Fasta_Class_0']
pos_path = config['InputPaths']['Fasta_... | 5,352,478 |
def execute_timeout(cnx, command, **kwargs):
"""Perform Sqlite3 command to be interrupted if running too long.
If the given command is a string, it is executed as SQL.
If the command is a callable, call it with the cnx and any given
keyword arguments.
Raises SystemError if interrupted by timeout.
... | 5,352,479 |
def destroy():
"""Destroy this Heroku application. Wipe it from existance.
.. note::
This really will completely destroy your application. Think twice.
"""
local('heroku apps:destroy') | 5,352,480 |
def mean_IoU(threshold=0.5, center_crop=0, get_batch_mean=True):
"""
- y_true is a 3D array. Each channel represents the ground truth BINARY channel
- y_pred is a 3D array. Each channel represents the predicted BINARY channel
"""
def _f(y_true, y_pred):
y_true = fix_input(y_true)
y_... | 5,352,481 |
def unsatZone_withAgri_Ep(self, k):
"""
- Potential evaporation is calculated with formula in 'JarvisCoefficients', but without
using the Jarvis stress functions
- Potential evaporation is decreased by energy used for interception evaporation
- Formula for evaporation linear until LP, from t... | 5,352,482 |
def ConvertCSVStringToList(csv_string):
"""Helper to convert a csv string to a list."""
reader = csv.reader([csv_string])
return list(reader)[0] | 5,352,483 |
def add_data_to_taskw(data: dict, module: str, quest: str):
"""
Insert data to TaskWarrior DB.
"""
twarrior = TaskWarrior()
if quest is not None:
project_data = module + ":" + quest
timestamp = convert_to_unix_tstamp(data['end'], False)
else:
project_data = module
... | 5,352,484 |
def get_section_range_pairs(orig_section, new_pdf):
"""Return MatchingSection for a section."""
other_section = new_pdf.find_corresponding_section(orig_section)
if not other_section:
print("Skipping section {} - no match in the other doc!".format(
orig_section.title))
return None... | 5,352,485 |
def atomic_transaction(conn: sqlite3.Connection,
sql: str, *args: Any) -> sqlite3.Cursor:
"""Perform an **atomic** transaction.
The transaction is committed if there are no exceptions else the
transaction is rolled back.
Args:
conn: database connection
sql: format... | 5,352,486 |
def convert_to_tensor(narray, device):
"""Convert numpy to tensor."""
return tf.convert_to_tensor(narray, tf.float32) | 5,352,487 |
def get_config_origin(c):
"""Return appropriate configuration origin
Parameters
----------
c: Configuration
configuration to be examined
Returns
-------
origin: str
origin of configuration (e.g. "Local", "Random", etc.)
"""
if not c.origin:
origin = "Unknown... | 5,352,488 |
def get_instance_ip() -> str:
"""
For a given identifier for a deployment (env var of IDENTIFIER), find the cluster
that was deployed, find the tasks within the cluster (there should only be one),
find the network interfaces on that task, and return the public IP of the instance
:returns: str The pu... | 5,352,489 |
def is_hign_level_admin():
"""超级管理员"""
return is_admin() and request.user.level == 1 | 5,352,490 |
def object_metadata(save_path):
"""Retrieves information about the objects in a checkpoint.
Example usage:
```python
object_graph = tf.contrib.checkpoint.object_metadata(
tf.train.latest_checkpoint(checkpoint_directory))
ckpt_variable_names = set()
for node in object_graph.nodes:
for attribute i... | 5,352,491 |
async def login(_request: Request, _user: User) -> response.HTTPResponse:
"""
Login redirect
"""
return redirect(app.url_for("pages.portfolios")) | 5,352,492 |
def test_estimate_gas_fails_if_startgas_is_higher_than_blockgaslimit(deploy_client):
""" Gas estimation fails if the transaction execution requires more gas
then the block's gas limit.
"""
contract_proxy, _ = deploy_rpc_test_contract(deploy_client, "RpcWithStorageTest")
latest_block_hash = deploy_c... | 5,352,493 |
def delete_source(source_uuid: SourceId, database: Database):
"""Delete a source."""
data_model = latest_datamodel(database)
reports = latest_reports(database)
data = SourceData(data_model, reports, source_uuid)
delta_description = (
f"{{user}} deleted the source '{data.source_name}' from me... | 5,352,494 |
def find_object_with_matching_attr(iterable, attr_name, value):
"""
Finds the first item in an iterable that has an attribute with the given name and value. Returns
None otherwise.
Returns:
Matching item or None
"""
for item in iterable:
try:
if getattr(item, attr_na... | 5,352,495 |
def send_message(token, message: str) -> str:
"""
A function that notifies LINENotify of the character string given as an argument
:param message:
A string to be notified
:param token:
LineNotify Access Token
:return response:
server response (thats like 200 etc...)
"""
... | 5,352,496 |
def hdf5pack(hdf5_file,
active_areas=None,
address=None,
attenuation=None,
beam_center_x=None,
beam_center_y=None,
ccd_image_saturation=None,
data=None,
distance=None,
pixel_size=None,
pulse... | 5,352,497 |
def _fix(node):
"""Fix the naive construction of the adjont.
See `fixes.py` for details.
This function also returns the result of reaching definitions analysis so
that `split` mode can use this to carry over the state from primal to
adjoint.
Args:
node: A module with the primal and adjoint function d... | 5,352,498 |
def change_lane(vid, lane):
"""
Let a vehicle change lane without respecting any safety distance
:param vid: vehicle id
:param lane: lane index
"""
traci.vehicle.setLaneChangeMode(vid, DEFAULT_LC)
traci.vehicle.changeLane(vid, lane, 10000.0) | 5,352,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.