content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def get_serial_model(session_obj):
"""Get device serial number and model"""
global session
session = session_obj
serial = None
model = None
show_inventory = send_command('show inventory')
for i in show_inventory.splitlines():
if i.rfind('Chassis') != -1:
model = i.sp... | e8fe8f4fb7ec45b1107f70e18d9e01886f6b020f | 65,400 |
import os
def create_env(visible=False, scene=''):
"""
Creates an instance of the game environment
"""
path = '/usr/local/lib/python3.7/dist-packages/vizdoom/scenarios/'
scene = 'defend_the_center' if not scene else scene
doom = vz.DoomGame()
doom.load_config(os.path.join(path, f'{sce... | ce10f18442d03a6191c0051a5126c150da6096be | 65,401 |
def find_nearest(known_array, test_array):
"""Find closest value in `known_array` for each element in `test_array`.
Parameters
----------
known_array : numpy array
consisting of scalar values only; shape: (m, 1)
test_array : numpy array
consisting of scalar values only; shape: (n, 1)... | 49a6351250c5ef61818cfb385de645a27bcf736e | 65,402 |
import array
def ReadNormalTag(tag):
"""
Read the raw data stored in Normal Tag.
:param tag: The Normal Tag to read the data from.
:type tag: c4d.NormalTag
:return: A list with all the raw data.
:rtype: list[int]
"""
# Retrieves the read buffer array
buffer = tag.GetLowlevelDataAd... | 211faf4cd2bceacdc7a13e93addbb82f851ffd0c | 65,403 |
def power_out_time(value):
"""
0 - 32767 seconds
"""
return "Seconds:{}".format(value) | 1f1efb91a9163ad0f6fb920985edb84809c38c5a | 65,404 |
def _album_is_reviewed(album, user_key):
"""Check if an album has been reviewed.
Args:
album: An Album entity
user_key: A stringified user key, or None.
Returns:
If user_key is None, returns True if and only if the album has
any reviews at all.
If user_key is not None, retu... | fd3b495ccdbc7a61398bc63a28fd5ab8378152f0 | 65,405 |
def cubehandler(f):
"""
Wrap a function from metpy.calc submodule to pass iris cubes as arguments
and get cubes as output.
Copies coordinates from the first cube among the arguments.
Only copies `dim_coords` and `aux_coords`.
May not work with some units.
"""
@wraps(f)
def wrapper(... | 71fafc8049a40145d143de26025f133ab243de2d | 65,406 |
def read_argv(argv):
"""Reads the config and source file from argvs"""
try:
config_file = argv[0]
source_file = argv[1]
return config_file, source_file
except:
Corrector.exit(
"Invalid arguments when running corrector. e.g python corrector.py settingsPath sourcePa... | 0eed23937e2c0506dccdd19a40a83274719661c6 | 65,407 |
import argparse
def create_arg_parser() -> argparse.ArgumentParser:
"""Create the argument parser for the CLI."""
parser_main = argparse.ArgumentParser(
description=(
"Manage subreddit threads, wiki pages, widgets, menus and more"
),
argument_default=argparse.SUPPRESS,
... | 671d45e39dc27eb52af90f9c07e5bf622808ec80 | 65,408 |
def position_encoding_init(n_position, d_pos_vec):
"""
Generate the initial values for the sinusoid position encoding table.
"""
position_enc = np.array([[
pos / np.power(10000, 2 * (j // 2) / d_pos_vec)
for j in range(d_pos_vec)
] if pos != 0 else np.zeros(d_pos_vec) for pos in rang... | ae6abd373c4841b15771464a8c9bc073d3865e1d | 65,409 |
def _require_auth(fnc):
"""Authentication decorator."""
@wraps(fnc)
@_assure_identity
def _wrapped(*args, **kwargs):
if not identity.authenticated:
msg = "Authentication required before calling '%s'." % fnc.__name__
raise exc.NotAuthenticated(msg)
return fnc(*args... | 17e3dd050aed75a9d5b1e0005de9f7d07bdf690c | 65,410 |
def get_random_word(alphabet: str, length: int):
"""Generate a random word on alphabet with given length"""
random_word = ''
for i in range(length):
random_word += alphabet[randint(0, len(alphabet) - 1)]
return random_word | ec51b52f6643a0a975a60f986761dfe7efeb45e2 | 65,411 |
import sqlite3
def load_history_db(history_db):
""" Load simulation history from provided db.
In case no db is given, returns an empty history
:param history_db:
:return:
"""
history = {}
if history_db is not None:
conn = sqlite3.connect(history_db)
cursor = conn.cursor()
... | 06055c6c48f8757513808e44d85f802ab0acd456 | 65,412 |
import functools
def compute_network_criticality(
parameters,
module_objective_fn,
init_loop_variables_mapping,
final_loop_variables_mapping,
):
"""Compute the criticality of a network parameterized by `parameters`."""
def _module_criticality_by_ref(layer_ref):
return compute_module_criticali... | f0098368708ffe0814848cf07c111179c3a574bf | 65,413 |
import shutil
def async_get_engine(hass, config):
"""Set up macOS speech component."""
if shutil.which("say", path="/usr/bin") is None:
_LOGGER.error("'/usr/bin/say' not found")
return False
if shutil.which("reattach-to-user-namespace", path="/usr/local/bin") is None:
_LOGGER.error... | 97487b4eca354ed7b962a6ab90c6448c1da17af4 | 65,414 |
def validate_data(first_name, age,investment_amount,risk_level, intent_request):
"""
Validates the data provided by the user.
"""
# Validate that the user is over 0 and less than 65
if first_name is None:
# first_Name validation
# age=parse_int(age)
return build_validatio... | d14a366499d52accc3b2d8059b3ee93add2f275c | 65,415 |
import os
from typing import Dict
def _get_conda_env_path(conda_info: Dict, env_name: str, worker=None) -> str:
"""Get path for a python executable of a conda env"""
if env_name == "base":
return os.path.join(conda_info["envs"][0], "bin")
else:
envs_path = conda_info["envs"][1:]
i... | 53bf41227290d58c6e57ed7ffe500adafc3af71c | 65,416 |
def get_targets(data, n_groups):
"""
In order to obtain our final set of labels for the data,
this function transforms the data first using PCA,
then Agglomerative Hierarchical Clustering. It returns
the target labels as a pandas dataframe.
Parameters:
data: The dataset in question.
n_g... | a7c9a326cc08e649ca52dc322c5b8677a5bcbdd3 | 65,417 |
def string_to_datetime(timestamp_string):
"""Convert string timestamp to datetime instance."""
try:
return dt.datetime.strptime(timestamp_string, "%Y-%m-%dT%H:%M:%S.%fZ")
except ValueError:
return dt.datetime.strptime(timestamp_string, "%Y-%m-%dT%H:%M:%SZ") | 32716adeea77ada8c07f144422c7b2075f5afa1b | 65,418 |
import os
from datetime import datetime
def news_upload():
"""News Upload endpoint.
Gets the latest news from NewsAPI and respective metadata, cleans the documents
and runs them through the indexing pipeline to be stored in the database.
"""
try:
NEWSAPIKEY = os.environ.get("NEWSAPIKEY")
... | 4b4fd38bb644ba8d1e01b39802d3d10740ebb17b | 65,419 |
from typing import Any
def _filter_keep(value: Any, keep_always: bool) -> bool:
"""Determine whether we should keep a value in serialized output."""
if keep_always:
return True
return value is not MISSING | 373ba5179e315dc76cb8b19d3ef7f3d51e8b9e00 | 65,420 |
def GetScopedName(scope, type_defn):
"""Gets the prefix string to reference a type from a given scope.
This function returns a concatenation of C++ scope operators such as, in the
context of the given scope, when prefixing the name of the given type, it
will reference exactly that type.
For example, given:
... | ec8259de1be11563d8ddf67abe071941b6195aa3 | 65,421 |
def SNR(info, magnitude=24.5, exptime=565.0, exposures=3, galaxy=True, background=True, diginoise=False):
"""
Calculates the signal-to-noise ratio for an object of a given magnitude in a given exposure time and a
number of exposures.
:param info: instrumental information such as zeropoint and backgroun... | 5001fc83307b52b93bcb98e5337beeb76132e86c | 65,422 |
def ipusage(request):
"""Lists all assets."""
inventory = netspot.NetSPOT(collection=netspot_settings.COLL_IP)
search_result = inventory.search('', key='ip', sort=[("date", 1), ("time", 1)], limit=20)
return render(
request,
'ipusage.htm',
context={'filter': '', 'ips': search_result,},
) | 3ad2a424a9e43036be40c2bbb215e68bdeef5559 | 65,423 |
def max_employment(countries, employment):
"""
Fill in this function to return the name of the country
with the highest employment in the given employment
data, and the employment in that country.
"""
i = np.argmax(employment)
max_value = employment[i]
max_country = countries[i]
ret... | e023ecd2819f7300046a53999473723c5bb5bebc | 65,424 |
def merge_tracks(args, tracks, feat_tracks=None):
"""Check frame conflict & merge tracks"""
# Check frame conflict and fix it
if feat_tracks is None: feat_tracks = tracks
dets = np.concatenate([t.dump() for t in tracks], axis=0)
if not debug_frame(dets):
conflict_idx = check_conflict(tracks)... | 1d11b6d04ca8e2c1fb70c18b7e14a37437575920 | 65,425 |
from typing import Type
def inherit(*args,errors=(NotImplementedError)):
"""A decorator which automatically wraps the underlying function and instead calls a parent class
The body of the wrapped function is entirely ignored.
Annotations of the parent class will be applied to the wrapped function **unless*... | 72ebad546c00dcd27391f68bd1c9ef5ff49083aa | 65,426 |
import os
def connect_to_db() -> psycopg2.extensions.connection:
"""Connect to the database."""
conn = psycopg2.connect(
f"host=127.0.0.1 sslmode=disable dbname=stats user=stats password={os.getenv('DB_PASSWORD')}")
return conn | fccdf326652393d5393fbf0cd7a4a51f3bc96548 | 65,427 |
def delete_todo(request):
"""
todo delete 的路由函数
"""
# 得到当前编辑的 todo的 id
todo_id = int(request.query.get('id', -1))
t = Todo.find_by(id=todo_id)
uid = current_user(request)
u = User.find_by(id=uid)
# 验证用户id是否相同
if t.user_id != u.id:
return redirect('/login')
if t is n... | 502cc0b83e034a834aacb8bb1416875c0cc8c581 | 65,428 |
def dB_to_amplitude(SNR):
"""Returns the amplitude ratio, converted from decibels.
Arguments
---------
SNR : float
The ratio in decibels to convert.
Example
-------
>>> round(dB_to_amplitude(SNR=10), 3)
3.162
>>> dB_to_amplitude(SNR=0)
1.0
"""
return 10 ** (SNR ... | 92fa3cb5d40e8f0ac68a447e3eef976ec9853139 | 65,429 |
def upload_location(instance, filename, **kwargs):
"""Upload location for profile image"""
return f"accounts/{instance.username}/{filename}" | c662bbb095f8180aa330a2566c9d9aaf372712b0 | 65,430 |
def v9_tail(iterable, n):
"""Return the last n items of given iterable.
This solution uses deque, a double-ended queue class, from the
collections module...
We're setting the maximum size of our deque to n. When you append to a
deque which has reached it's maximum length, it will efficiently remov... | 89358971690adcb4f32005ee09b2f3ca4a63277e | 65,431 |
import operator
def add(n_in: int = 2) -> Foldl:
"""Creates an addition combinator.
>>> from redex import combinator as cb
>>> add = cb.add()
>>> add(4, 2) == 6
True
Args:
n_in: a number of inputs.
Returns:
a combinator.
"""
return foldl(func=operator.add, n_in=n... | f7b7e1e66654e30da14dc112abed3e95884e5020 | 65,432 |
import base64
def base64url_to_hex(data):
"""
Converts a base64url encoded string to a hex encoded string
Args:
data (str): The base64url encoded string
"""
data = data.replace("-", "+").replace("_", "/")
missing_padding = len(data) % 4
if missing_padding:
data += "=" * (... | db56f4c9e1335b9a4a8f0e0a794c7468122666dc | 65,433 |
def read_release_version():
"""Read version information from VERSION file"""
try:
with open(VERSION_FILE, "r") as infile:
version = str(infile.read().strip())
if len(version) == 0:
version = None
return version
except IOError:
return None | 1de778f67235b31c3a349b8016fe29e2f3c113f8 | 65,434 |
def read_rpg_header(file_name):
"""Reads header from RPG binary file.
Supports Level 0/1 and version 2/3/4.
Args:
file_name (str): name of the file.
Returns:
tuple: 2-element tuple containing the header (as dict) and file position.
"""
def read(*fields):
block = np.fr... | c2b97981e96555c3cc02d5e6ad071cd1d35b81cd | 65,435 |
def quantize(dt, *, resolution=timedelta(minutes=15)):
"""Get the period from a fixed-size grid which contains the given time"""
# The grid is zeroed at midnight, so resolution must fit into a day without leaving a remainder.
assert not Period.DAY % resolution
from_midnight = timedelta(hours=dt.hour, mi... | 4ff8388594bd884c81102fbf34a85122386247f5 | 65,436 |
def validate_redirection_target(path):
"""Checks if login can safely redirect to a path.
For example, if instead of a path a full url is used (with a
domain part), the redirect could leak a login token in the Referer
header (not an obvious problem since token is intended to be one
time, but better ... | 4401d9f723bdaccb27256f405b0de31dec855a35 | 65,437 |
import sqlite3
def create_connection(db_file) -> sqlite3.Connection:
"""
This method connects to the database and returns the connection
"""
connection = None
try:
connection = sqlite3.connect(db_file)
except Error as e:
print(e)
return connection | 2d00bdc2f86fd04b0d77f542ec177232a49e97aa | 65,438 |
import os
def clean_dir(dir_to_clean, remove_ext):
"""
dir_to_clean (list, str): directories to clean
remove_ext (list,str): extensions to delete
----------------
return: None
"""
file_size_del = 0
files_count = 0
for direc in dir_to_clean:
for file in os.listdir(direc):
... | df53c204ec066224c9c11c9ff749bfa39fbcec43 | 65,439 |
def estimate_noise(X, method='mp', UDV=None, **kwargs):
"""
Estimates the noise level for a low rank PCA model.
Parameters
----------
X: array-like, (n_samples, n_features)
The data matrix.
method: str
Which method to use. Must be one of TODO: document
'mp':
'c... | 73009230709799d7f16c3f3aafd5523404c66398 | 65,440 |
def kldiv2(s, t):
""" Kullback-Leibler divergence with base 2 """
return kldiv(s, t, log="2") | 4822f19600c3ce91b5e91fd30dc6ca690e3697ea | 65,441 |
def get_meta(number):
"""
Retrieve the level 3 classname and official RGB value for each clc class.
Parameters
----------
number: int
CLC_CODE of the class
Examples
--------
>>> get_meta(111)
Returns
-------
Official RGB colors as (r,g,b)
Level 3 name of t... | 2cebc9dd50bad28de5c122a51ca19f5ef97f6414 | 65,442 |
def submat(X,ii,jj):
""" Pick a block submatrix from block matrix X by rows ii and cols jj """
return {(ix,jx): X.get((i,j), None)
for (ix,i),(jx,j) in product(enumerate(ii),
enumerate(jj))} | 33fafb2b4e2daeedd51cd4fb8aa5e6d705e8bf36 | 65,443 |
import csv
def corpus_maker(f_name):
"""
Takes a csv file and creates a set of decklists in list of lists,
DataFrame, and tomotopy Corpus objects.
Parameters:
f_name: .csv file
Term-document matrix: columns are card names, rows are decks,
and each cell is the co... | 6dd5d0c4a1f3a66e72421eea2c69418fa9c94248 | 65,444 |
def summed_area_table(img):
"""
Use summed_area_table_fast() instead. Leaving this for reference.
"""
# Convert to numpy array if necessary
if not isinstance(img, np.ndarray): img = np.array(img)
table = np.zeros(img.shape)
# Raster scan
#---- Do top and left edges
table[0, 0] = im... | a7e29e667f031dd5b2256fd13dcbbd2e9a92eb4c | 65,445 |
def find_omp(verbose=False):
"""
Find omp in environment.
Parameters
----------
verbose : bool
to print paths to include and library directories
Returns
-------
tuple(list(str), list(str))
path to include directory, path to library directory
"""
omp_include, omp... | e627ca182ce824342be2423ea72a28d6920a0c56 | 65,446 |
def safe_filename(infilename):
"""
Take a filename and remove special characters like the asterisk and slash which mess things up. Warning: if you
pass a directory path to this function, it will remove the slashes. Do not do that.
:param infilename: filename to be processed.
:type infilename: strin... | 0e46972696f8d7b10bc6bc61efcdd2dfbca9e909 | 65,447 |
import collections
from typing import Mapping
def namedtuple(typename, field_names, default_values=()):
"""
Overwriting namedtuple class to use default arguments for variables not passed in at creation of object
Can manually set default value for a variable; otherwise None will become default value
""... | b0fba5ba73037e7bdb5db05d10a8b96f953fc829 | 65,448 |
import warnings
import json
def _validate(nodes_fname, meta_fname, streamlines_fname):
"""
Run checks to ensure requirements and warns of inconsistencies.
Parameters
----------
nodes_fname : str
Full path to nodes table CSV file
meta_fname : str
Full path to metadata CSV fil... | c6ef766be628088e1bef90c0ac81ebcc444cc304 | 65,449 |
def _truncate_log(log_txt):
"""
Truncate the ``log_txt`` in case it exeeds the max. log size.
:param log_txt:
A ``str``.
"""
max_log_bytes = config.getint('job_runner_worker', 'max_log_bytes')
if len(log_txt) > max_log_bytes:
top_length = int(max_log_bytes * 0.2)
botto... | a3be928a29c32a73b10ca45cb14da768b28d9bda | 65,450 |
import os
def _get_rh_available_repoids(context, indata):
"""
RH repositories are provided either by RHSM or are stored in the expected repo file provided by
RHUI special packages (every cloud provider has itw own rpm).
"""
arch = api.current_actor().configuration.architecture
rh_repoids = _... | a57bea8e0178aa207b1f4ed743c61c4db39a093c | 65,451 |
def length_along_path(pp, index):
""" Get the lenth measured along the path up to the given index.
"""
index = min(index, len(pp) - 1) # beware of the end
diff_squared = (pp[:index] - pp[1:index+1]) ** 2
distances = diff_squared.sum(1)
return (distances ** 0.5).sum()
# == sum(pp[j].distance... | a7eea4b411860c51fb5f64a690a9d4832c8b98a9 | 65,452 |
def generate_background(options):
"""
Fonction permettant d'ajouter un background
:return: etree.Element
"""
width = options.width
height = options.height
background_group = etree.Element('g')
etree.SubElement(background_group, 'title').text = 'background'
background = etree.SubEle... | 72c9db05d72b5dcd64bfad907e5b74e5c25c0a04 | 65,453 |
import re
def get_generators(cmakePath=findexe("cmake"), as_list=False):
"""get available CMake generators
Parameter:
as_list str: True to return a list of dict of all generators. Each entry
consists of 'name', 'desc', and 'default'
Returns: str if as_list==False else dic... | f2603dc1a366822b4e1040b7e10db614332c8ad7 | 65,454 |
import calendar
def _get_month_info(localtime):
"""获取月相关的信息"""
now_day = localtime.tm_mday
now_year = localtime.tm_year
now_month = localtime.tm_mon
now_month_max_day = calendar.monthrange(now_year, now_month)[1]
left_day = now_month_max_day - now_day
month_percent, progress_bar = _get_pro... | d7d619528d36c75d56d5c36360876bd328e36a24 | 65,455 |
def init(cfg: GenomeConfig):
"""Random initialized weight value, calculated via a normal distribution."""
return clip(gauss(cfg.weight_init_mean, cfg.weight_init_stdev),
a_min=cfg.weight_min_value,
a_max=cfg.weight_max_value) | f18314d905822bf3e30204c4168c8952edefaa1d | 65,456 |
def tokenize_and_tag(filepath):
"""Load the book's text, tokenize and tag in memory."""
with open(filepath+'.txt', 'r') as f:
book = f.read()
return pos_tag(word_tokenize(book)) | 5f543c98cc9d59c91d82921d2dd6c1e81daf10c2 | 65,457 |
import json
def output():
"""Prints out the first 10 rows in the database"""
my_query = get_database_data("SELECT * FROM Data LIMIT %s", (10,))
json_output = json.dumps(my_query, default=str)
return json_output | 6e35b5fca72171680bec5da87a38a0fd59a4c9e4 | 65,458 |
def get_user_env_var() -> str:
"""returns the environment variable "USER", if it doesn't exists, return a default value"""
user_var = ps.get_env_var( 'USER' )
if user_var == None:
user_var = 'USER'
return user_var | 165df68af82708d3d7d15c1a5eecdf863ce0c854 | 65,459 |
def RFile():
"""Return a raman data file for testing."""
return 'examples/testdata/1/0001.txt' | cb9bf96aa3dab11f27322b4587f3e36f89a59f31 | 65,460 |
def zzX_mul(f, g):
"""Multiply polynomials in Z[X]. """
if poly_univariate_p(f):
return zzx_mul(f, g)
if f == g:
return zzX_sqr(f)
if zzX_zero_p(f):
return f
if zzX_zero_p(g):
return g
df = zzX_degree(f)
dg = zzX_degree(g)
h, l = [], poly_level(f)-1
... | a7288d2ee59415acf46a5fea30913bd23e45f33b | 65,461 |
def compute_performance_easy(trials):
"""
Compute performance on easy trials (stimulus >= 50 %) from trials object
:param trials: trials object that must contain contrastLeft, contrastRight and feedbackType
keys
:type trials: dict
returns: float containing performance on easy contrast trials
... | 6859f79f5fae635fc08261f7906dbc05e9140aa6 | 65,462 |
import os
def prepare_eval_data(config):
""" Prepare the data for evaluating the model. """
coco = COCO(config.eval_caption_file, config.max_eval_ann_num)
image_ids = []
image_files = []
if not config.max_eval_ann_num:
print('No config.max_eval_ann_num')
image_ids = list(coco.imgs.... | 96a3aaad20901771f0079986529ae0f0e428ac1f | 65,463 |
import json
def _list(key):
"""
Internal implementation for list_* functions
:param key: string for required entity (zone, zonegroup, realm, user)
:type key: str
:return: List of specified entities found
:rtype: list
"""
cmd = [
RGW_ADMIN, '--id={}'.format(_key_name()),
... | 7faa52833515180bdc7161e75d8c96e7fc7e9ccb | 65,464 |
import math
def check_transcript_eir_tc_state(tr_id, exid2cov_dic, trid2exc_dic,
filter_ei_ratio=1.0,
min_ei_cov=20,
min_ei_cov_sum=False,
exid2isrn_dic=False,
... | 3e20da95ec5e463fb68fb8619d0063701b453217 | 65,465 |
def find_node(_node_number, geometry):
"""
Check if node number exist in the f2u model
"""
_node = []
for _number in _node_number:
try:
_test = geometry._mesh.nodes[_number]
_node.append(_number)
except KeyError:
continue
return _node | 17e5a3c21529298e19ee424539a83ccea1b8acf6 | 65,466 |
def computeII(imData):
"""
#---------------------------------------------------------------------------#
#--- computeII ---#
#---------------------------------------------------------------------------#
Description:
Computes Integral Image
I... | b2c326aaa4b3021c4859b312ab006c3f7869567e | 65,467 |
def confidence_score(classifier, X: np.ndarray) -> np.ndarray:
"""Measure the confidence score of a model for a set of samples.
Args:
classifier: The classifier for which the labels are to be queried.
X: The pool of samples to query from.
Returns:
The confidence score for each samp... | 4af8ff0df27392e9f809a5a4fdc9c8c8e7f64900 | 65,468 |
import random
def roll_die():
"""Returns a random int between 1 and 6"""
return random.choice([1,2,3,4,5,6]) | 664add4a7345268e68d0c6941aa42d71be581606 | 65,469 |
def report(uid):
""" Render object report for verify """
database = DataProvider()
# get checklist and show it in edit mode
item = first_or_default(database.checklists, lambda x: x.uid == uid)
item.visit_by(session['user_name'])
database.update_checklist(item)
questions = database.checklist
... | 02ac3a002f3134f99ba3643a7e3edc5f14345e74 | 65,470 |
import random
def dirichlet_partition(samples, num_clients, alpha):
"""O(n)"""
ret = {i: [] for i in range(num_clients)}
random.shuffle(samples)
# TODO: what does it mean
prop = np.random.dirichlet(np.repeat(alpha, num_clients))
prop = list(accumulate(prop))
i = 0
for idx in range(0, l... | 390294cab0ac78fb831605d14b801d55f49367d8 | 65,471 |
def convert_to_HSV(image):
"""convert RGB(BGR in opencv numpy) to HSV color space"""
hsv_image = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)
return hsv_image | 62be9e73ef76d426d4572d71ad5925a236cb549c | 65,472 |
def size(input, name=None, out_type=dtypes.int32):
# pylint: disable=redefined-builtin
"""Returns the size of a tensor.
Returns a 0-D `Tensor` representing the number of elements in `input`
of type `out_type`. Defaults to tf.int32.
For example:
```python
t = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3,... | 6e8ece9fb4ca73f114642ece0a249a05882177ba | 65,473 |
def find_part(part_id):
"""
This function is defined as an abstraction barrier,
in case we want to use a different storage object for
BoM, such as perhaps a read/write database.
:part_id: the ID of the part specified
:return: part object specified by part_id, else None if DNE
"""
return... | de9f6332d8a7926a0f5b96983b8d2cdf2b3acefe | 65,474 |
import random
def Transform(depth_image: np.array, ir_image: np.array, boxes: np.array, labels: np.array, train: bool):
"""
Apply transformation.
:param depth_image: np.array(uint16), Depth image
:param ir_image: np.array(uint16), IR image
:param boxes: np.array(np.float), a list of N boxes of th... | 98d24bb44c979e3cd344de67bacf0052284240a5 | 65,475 |
import os
import logging
import sys
def get_logger(config, name=None):
"""
获取Logger对象
Args:
config(ConfigParser): config
name: specified name
Returns:
Logger: logger
"""
log_dir = './libcity/log'
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log... | 601b4dcf9e938b350ce2b955fd5d67969849c6c2 | 65,476 |
def FormatScoreTimes(score_times):
"""Provide a color-coded formatting of the output of ScoreLogFile."""
ok = '\033[94m'
warn = '\033[93m'
fail = '\033[91m'
result = []
for name, score_time in score_times.iteritems():
if score_time < 0.2:
color = ok
elif score_time < 2.0:
color = warn
... | 67c7456974d907f8f87eb9cde409083693a08118 | 65,477 |
def isWithin(rect1, rect2):
"""Checks whether rectangle 1 is within rectangle 2
Parameters:
rect1: list of coordinates [minx, maxy, maxx, miny]
rect2: list of coordinates [minx, maxy, maxx, miny]
Returns:
True if rect1 within rect2 else False
"""
minx1, maxy1,maxx1, miny1 = r... | d7adca34b7cfb4294316090e18c164db0a34e818 | 65,478 |
import numpy
import itertools
import six
from operator import concat
def n_step_lstm(
n_layers, dropout_ratio, hx, cx, ws, bs, xs, train=True,
use_cudnn=True):
"""Stacked Long Short-Term Memory function for sequence inputs.
This function calculates stacked LSTM with sequences. This function g... | 419cca3181f910bc0c93d8e9bd46d9a3f818ea9b | 65,479 |
import argparse
def create_arg_parser():
""" Create an argument parser
"""
parser = argparse.ArgumentParser(help)
parser.add_argument('--meshfile', default='hgrid.gr3',
help='mesh file to analyze, default=hgrid.gr3, If the file is 2dm format, it will be converted into temp.gr3 ... | 96a67e3c54cab73776171c1c5ab0e605450dbcf1 | 65,480 |
def login_post():
"""Obdelaj izpolnjeno formo za prijavo"""
# Uporabniško ime, ki ga je uporabnik vpisal v formo
username = request.forms.username
# Izračunamo MD5 has gesla, ki ga bomo spravili
password = password_md5(request.forms.password)
# Preverimo, ali se je uporabnik pravilno prijavil
... | f2e43f4d25d2020ab959375f10acd9e060bcc9c3 | 65,481 |
import glob
import os
def find_model(folder, extension):
"""
This is assuming there is only one of each extension each folder, which should be kept this case all the time.
"""
extension = '*.' + extension
dir = glob(os.path.join(folder, extension))
return dir[0] | 10358c72e9ff7558d759ef304eb70a828f654b5f | 65,482 |
def doolittle(matrix_a):
""" Doolittle's Method for LU-factorization.
:param matrix_a: Input matrix (must be a square matrix)
:type matrix_a: list, tuple
:return: a tuple containing matrices (L,U)
:rtype: tuple
"""
# Initialize L and U matrices
matrix_u = [[0.0 for _ in range(len(matrix... | 03ba90c29dfb67ffe1edf939b49f3ab537931831 | 65,483 |
def is_form_submitted():
"""
Check if current method is PUT or POST
"""
return request and request.method in ("PUT", "POST") | de260ecbd0eb48ae5d49029e858a41e558a03009 | 65,484 |
import random
def randFunc():
"""
Rand # generating func
:return: int
"""
return random.randint(1,3) | f2b2501dcc1acede3d99d36b55587b6e97f8ae5a | 65,485 |
import os
def main(output_dir, scenarios_per_year):
"""
Process scenario data
Parameters
----------
output_dir : str
Directory where output files are to be stored (also contains outputs from previous steps)
scenarios_per_year : int
Number of operating scenarios per year
... | 4a9973fe4dc056bf66fe6344b67f84c15d9d1b9a | 65,486 |
import os
import random
def randombytes(n):
"""Return n random bytes."""
if os.path.exists('/dev/urandom'):
f = open('/dev/urandom')
s = f.read(n)
f.close()
return s
else:
L = [ chr(random.randrange(0, 256)) for i in range(n) ]
return ''.join(L) | cf399f4ce6712bb99ef736424dea6d7499720690 | 65,487 |
def hilbert(w):
"""
Take the Hilbert transform of some function to get the analytic signal
:type w: np.array
:param w: signal data, must be real
"""
return np.imag(analytic(w)) | 2f40fc448e3dd9a1d212567abdebaeb83de83896 | 65,488 |
def get_model_list():
"""Get the entire list of model names in model_zoo.
Returns
-------
list of str
Entire list of model names in model_zoo.
"""
return _models.keys() | 27aae6873272af4ba20b227f74669c79583cae37 | 65,489 |
def get_delay_queue_max_size():
"""Returns max allowed number of "waiting" messages in the delay queue.
:return: Positive integer number or None if infinite
:rtype: int
"""
if 'replica' not in settings.CQRS:
return None
return settings.CQRS['replica']['delay_queue_max_size'] | b056ac58b50ec33179e0a4d1b076ef3c068bdd74 | 65,490 |
import subprocess
def shell(cmd, cwd=None, closeFds=True):
"""
Executes a shell command
:param cmd: Command string
:param cwd: Current working directory (Default value = None)
:param closeFds: If True, all file descriptors except 0, 1 and 2 will
be closed before the child process is executed. Defaults ... | 9c7600bd32c2f3d15f02269754261ea3548ef1ba | 65,491 |
def getRequest(request):
"""
Get an openid request from the session, if any.
"""
return request.session.get('openid_request') | f6ebcb13e631365f53ae3a362eaf2dba614d7344 | 65,492 |
from typing import Tuple
def make_networks(
spec: specs.EnvironmentSpec,
hidden_layer_sizes: Tuple[int, ...] = (256, 256)) -> ValueDiceNetworks:
"""Creates networks used by the agent."""
num_dimensions = np.prod(spec.actions.shape, dtype=int)
def _actor_fn(obs):
network = hk.Sequential([
h... | fecba5196fb09f81c9cba1da82f238f69d32af09 | 65,493 |
def pad_to_longest(vals: AnyList) -> StringList:
"""Pad all strings to length of longest in list
Arguments:
strs {StringList} -- string list
Returns:
StringList -- list of strings
"""
strs = [str(x) for x in vals]
pad_len = max([len(x) for x in strs])
pad_str = ' ' * pad_le... | 07ea446153ba6d8d37cb7b3729171fad98effa36 | 65,494 |
def histogram_widget(value, title=None, description=None, footer=None, read_only=False,
buckets=20, weight=1):
"""Helper function for quickly creating a histogram widget.
Histogram widgets display the distribution of a numeric attribute, in buckets, to group
ranges of values in your da... | 823cc4948bacb073fa6b9e0e5eee89d5f0a0b3ca | 65,495 |
def generate_process_tag(slug):
"""Generate test tag for a given process."""
return '{}.{}'.format(TAG_PROCESS, slug) | 58cdac7b226ffd042faadd65f9e2700cc0d935e0 | 65,496 |
def artificialNeuralNetwork(obj, weights):
"""
obj is a list of values (like [0.5, 6.0, 0]. Keep away
from inf and nan and stuff).
weights is a vector where the first element is the number
of hidden layers. (Call it N)
Then there should follow N integers that show how many n... | 1324f78759dcd3f0296d1557b04adc5ff2266cbb | 65,497 |
def run(adj_list, node_mappings, games=50):
"""
Function: run
-------------
Runs the simulation on a graph with the given node mappings.
adj_list: A dictionary representation of the graph adjacencies.
node_mappings: A dictionary where the key is a name and the value is a array
list of seed... | d87c70eb2044d676350b431fa2d4e6e3b2e610d9 | 65,498 |
def filter_staged(position_name, position_annotations, timepoint_annotations):
"""Filter-function for filter_annotations() to return worms that have been
stage-annotated fully and are noted as "dead"."""
stages = [tp.get('stage') for tp in timepoint_annotations.values()]
# NB: all(stages) below is True ... | 14e7f12fa100da4ef9a26496f7f9fc83e2988d3d | 65,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.