content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_fipallpoints(fixture_fiptools):
"""Test display of all user points."""
mypoints, allpoints = fixture_fiptools
message = '<@bob> has a score of 2\n<@fred> has a score of 1\n'
assert allpoints == message | 5,330,300 |
def crop_range_image(range_images, new_width, shift=None, scope=None):
"""Crops range image by shrinking the width.
Requires: new_width is smaller than the existing width.
Args:
range_images: [B, H, W, ...]
new_width: an integer.
shift: a list of integer of same size as batch that shifts the crop wi... | 5,330,301 |
def compare_chap_country_recs(
current_rec, s_title, db_rec, chapter, report_gen):
""" Find numeric differences at the country chapter level """
country = current_rec.cat
current_dict = current_rec._asdict()
db_dict = db_rec.__dict__
if report_gen.compare_and_print_ctry_chapter(
... | 5,330,302 |
def install():
""" Perform a lazy install of golang source
"""
# if plugin_path exists, this was already done
if 'plugin_path' in ctx.instance.runtime_properties:
return
# verify go available
res = subprocess.call(["go", "version"])
if res != 0:
raise NonRecoverableError("go... | 5,330,303 |
def install_aur_packages():
"""
Installs packages from the AUR system
"""
aur_packages = get_packages("aur_packages")
if is_null_or_empty(aur_packages):
print(f"No packages found.")
return
print("Installing packages from AUR")
for package in aur_packages:
print(f"I... | 5,330,304 |
def assert_modules_same(ir1: ModuleIR, ir2: ModuleIR) -> None:
"""Assert that two module IRs are the same (*).
* Or rather, as much as we care about preserving across
serialization. We drop the actual IR bodies of functions but try
to preserve everything else.
"""
assert ir1.fullname == ir2.fu... | 5,330,305 |
def getInfos(item):
"""Prints infos for item (IP or URL)
Args:
item (string): IP or URL for witch to get infos
"""
try:
ip_address(item)
getIPInfos(item)
except ValueError:
getDomainInfos(item) | 5,330,306 |
def randomString(length):
"""Generates a random string of LENGTH length."""
chars = string.letters + string.digits
s = ""
for i in random.sample(chars, length):
s += i
return s | 5,330,307 |
def rlistdir(path):
"""Resursive directory listing. Yield all files below given path,
ignoring those which names begin with a dot.
"""
if os.path.basename(path).startswith('.'):
return
if os.path.isdir(path):
for entry in os.listdir(path):
for subpath in rlistdir(os.path... | 5,330,308 |
def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
username = user.username
chat_id = user.id
if(default_LANG == ENGLISH_LANG):
user.bot.send_message(chat_id=chat_id,
text=fr'Hi {user.m... | 5,330,309 |
def kazoo_client_cache_enable(enable):
"""
You may disable or enable the connection cache using this function.
The connection cache reuses a connection object when the same connection parameters
are encountered that have been used previously. Because of the design of parts of this program
func... | 5,330,310 |
def DrawMACCloseButton(colour, backColour=None):
"""
Draws the wxMAC tab close button using wx.GraphicsContext.
:param `colour`: the colour to use to draw the circle.
"""
bmp = wx.EmptyBitmapRGBA(16, 16)
dc = wx.MemoryDC()
dc.SelectObject(bmp)
gc = wx.GraphicsContext.Create(dc)
... | 5,330,311 |
def main():
"""
This program computes Hailstone sequences and count the steps it takes
"""
print('This program computes Hailstone sequences.')
print('\n')
number = int(input('Enter a number: '))
# to count steps
steps = 0
if number == 1:
print('It took 0 steps to reach 1.')
... | 5,330,312 |
def dispatch(args, validator):
"""
'dispath' set in the 'validator' object the level of validation
chosen by the user. By default, the validator
makes topology level validation.
"""
print("Printing all the arguments: {}\n".format(args))
if args.vnfd:
print("VNFD validati... | 5,330,313 |
def create_app():
"""Create and configure and instance of the Flask application"""
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
DB.init_app(app)
@app.route('/')
def home():
return ren... | 5,330,314 |
def write_chart_json(j2_file_name, item):
"""Write a chart JSON file.
Args:
j2_file_name: the name of the Jinja template file
item: a (benchmark_id, chart_dict) pair
Returns:
returns the (filepath, json_data) pair
"""
file_name = fcompose(
lambda x: r"{0}_{1}".format(x, j... | 5,330,315 |
def main(config_file: str = ConfigOption, version: bool = VersionOption):
"""
This is the entry point of your command line application. The values of the CLI params that
are passed to this application will show up als parameters to this function.
This docstring is where you describe what your command l... | 5,330,316 |
def get_motif_class(motif: str) -> str:
"""Return the class of the given motif."""
for mcls in gen_motif_classes(len(motif), len(motif) + 1):
for m in motif_set(mcls):
if m == motif:
return mcls
else:
raise ValueError(
"Unable to find the class of the ... | 5,330,317 |
def resnet_v1(inputs,
blocks,
num_classes=None,
is_training=True,
global_pool=True,
output_stride=None,
include_root_block=True,
spatial_squeeze=True,
store_non_strided_activations=False,
reuse=... | 5,330,318 |
def findConstell(cc):
"""
input is one character (from rinex satellite line)
output is integer added to the satellite number
0 for GPS, 100 for Glonass, 200 for Galileo, 300 for everything else?
author: kristine larson, GFZ, April 2017
"""
if (cc == 'G' or cc == ' '):
out = 0
eli... | 5,330,319 |
def Controller(idx):
"""(read-only) Full name of the i-th controller attached to this element. Ex: str = Controller(2). See NumControls to determine valid index range"""
return get_string(lib.CktElement_Get_Controller(idx)) | 5,330,320 |
def smooth_2d_map(bin_map, n_bins=5, sigma=2, apply_median_filt=True, **kwargs):
"""
:param bin_map: map to be smooth.
array in which each cell corresponds to the value at that xy position
:param n_bins: number of smoothing bins
:param sigma: std for the gaussian smoothing
:return: sm_... | 5,330,321 |
def _select_socket(lower_port, upper_port):
"""Create and return a socket whose port is available and adheres to the given port range, if applicable."""
sock = socket(AF_INET, SOCK_STREAM)
found_port = False
retries = 0
while not found_port:
try:
sock.bind(('0.0.0.0', _get_candid... | 5,330,322 |
def _stabilization(sr, nmax, err_fn, err_xi):
"""
A function that computes the stabilisation matrices needed for the
stabilisation chart. The computation is focused on comparison of
eigenfrequencies and damping ratios in the present step
(N-th model order) with the previous step ((N-1)-th model ord... | 5,330,323 |
def detect_vacant_spaces(frame_blur):
"""
Detect cars and vacant spaces in parking.
:param frame_blur: frame_blur
:return: None
"""
parking_dict = {} # Store the status of each parking space
# Detecting vacant spaces
for ind, park in enumerate(parking_data):
points = np.array(... | 5,330,324 |
def _factory(cls_name, parent_cls, search_nested_subclasses=False):
"""Return subclass from parent
Args:
cls_name (basestring)
parent_cls (cls)
search_nested_subclasses (bool)
Return:
cls
"""
member_cls = None
subcls_name = _filter_out_underscore(cls_name.lower())
members = (_all_subclasses(p... | 5,330,325 |
def fast_exp10f(x):
"""
See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fast_exp10f.html
:param x: Argument.
:type x: float32
:rtype: float32
""" | 5,330,326 |
def tabuleiro_actualiza_pontuacao(t,v):
"""list x int -> list
Esta funcao recebe um elemento tabuleiro do tipo lista e um elemento v do tipo inteiro e modifica o tabuleiro, acrescentando ao valor da pontuacao v pontos"""
if isinstance(v,int) and v%4==0 and v>=0:
t[4]=tabuleiro_pontuacao(t)+v
... | 5,330,327 |
def pybullet_options_from_shape(shape, path='', force_concave=False):
"""Pybullet shape"""
options = {}
collision = isinstance(shape, Collision)
if collision:
options['collisionFramePosition'] = shape.pose[:3]
options['collisionFrameOrientation'] = rot_quat(shape.pose[3:])
else:
... | 5,330,328 |
def _on_connect(client, userdata, flags, rc):
"""Connect to MQTT broker and subscribe to topics"""
print(
"[STATUS] Connected to: {} (rc:{})".format(
client._client_id.decode("ascii"), str(rc)
)
)
# subscribing in on_connect() means that if we lose the connection and
# r... | 5,330,329 |
def test(course, all, environment):
"""
Test that COURSE builds without error.
"""
courses = get_courses(course, all)
envs = []
for i, course in enumerate(courses):
clean = 1 - environment # Clean if we're not doing env.
click.secho(f"Testing {course} ({i+1}/{len(courses)}). Ct... | 5,330,330 |
def test_registration_config(client, jwt, type, json_data_file):
"""Assert that the setup for all registration report types is as expected."""
# setup
text_data = None
with open(json_data_file, 'r') as data_file:
text_data = data_file.read()
data_file.close()
# print(text_data)
j... | 5,330,331 |
def showcase_code(pyfile,class_name = False, method_name = False, end_string = False):
"""shows content of py file"""
with open(pyfile) as f:
code = f.read()
if class_name:
#1. find beginning (class + <name>)
index = code.find(f'class {class_name}')
code = code[index:]
... | 5,330,332 |
def get_hyperparams(data, ind):
"""
Gets the hyperparameters for hyperparameter settings index ind
data : dict
The Python data dictionary generated from running main.py
ind : int
Gets the returns of the agent trained with this hyperparameter
settings index
Returns
-----... | 5,330,333 |
def _check_df_params_require_iter(
func_params: Dict[str, ParamAttrs],
src_df: pd.DataFrame,
func_kwargs: Dict[str, Any],
**kwargs,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""Return params that require iteration and those that don't."""
list_params: Dict[str, Any] = {}
df_iter_params: Di... | 5,330,334 |
def train_linear_classifier(loss_func, W, X, y, learning_rate=1e-3,
reg=1e-5, num_iters=100, batch_size=200,
verbose=False):
"""
Train this linear classifier using stochastic gradient descent.
Inputs:
- loss_func: loss function to use when training. It sh... | 5,330,335 |
def plot_confusion_matrix(cm, classes, std, filename=None,
normalize=False, cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
# std = std * 100
if normalize:
cm = cm.astyp... | 5,330,336 |
def sleepSome ():
"""
Sleeps a small amount of time to make it probable that some work in another
thread has been done.
"""
time.sleep (0.1) | 5,330,337 |
def ruleset_from_auto(source):
""" Automatically load a ruleset from any format
Automatically uncompresses files in either gzip or bzip2 format based
on the file extension if source is a filepath.
source: A file path or file handle
return: A ruleset or an exception
NOTE: ... | 5,330,338 |
def GetEvol(x, **kwargs):
"""
Run a VPLanet simulation for this initial condition vector, x
"""
# Get the current vector
dMass, dSatXUVFrac, dSatXUVTime, dStopTime, dXUVBeta = x
dSatXUVFrac = 10 ** dSatXUVFrac # Unlog
dStopTime *= 1.e9 # Convert from Gyr -> yr
# Get the prior probabili... | 5,330,339 |
def _inverse_permutation(p):
"""inverse permutation p"""
n = p.size
s = np.zeros(n, dtype=np.int32)
i = np.arange(n, dtype=np.int32)
np.put(s, p, i) # s[p] = i
return s | 5,330,340 |
def blend0(d=0.0, u=1.0, s=1.0):
"""
blending function trapezoid
d = delta x = xabs - xdr
u = uncertainty radius of xabs estimate error
s = tuning scale factor
returns blend
"""
d = float(abs(d))
u = float(abs(u))
s = float(abs(s))
v = d - u #offset by radius
... | 5,330,341 |
def median(a, dim=None):
"""
Calculate median along a given dimension.
Parameters
----------
a: af.Array
The input array.
dim: optional: int. default: None.
The dimension for which to obtain the median from input data.
Returns
-------
output: af.Array
Array... | 5,330,342 |
def all_permutations(index=0):
"""
Every permutation on n elements for positive n, returns tuples in lexicographic order
Args:
index -- 0 or 1, least element
OEIS A030298
"""
if index not in (0,1):
raise Exception("index must be 0 or 1")
for n in naturals(... | 5,330,343 |
async def is_photo(obj: Union[Message, CallbackQuery]) -> bool:
"""
Checks if message content is photo
:return: True if so
"""
obj = await _to_message(obj)
return obj.content_type == 'photo' | 5,330,344 |
def main():
"""
This function makes a breakout game.
The user has NUM_LIVES to play the game until the
bricks are all hit or the live is 0.
"""
graphics = BreakoutGraphics()
vx = graphics.get_dx() # the horizontal velocity
vy = graphics.get_dy() # the vertical velocity
global NUM_L... | 5,330,345 |
def check_win(mat):
"""
Returns either:
False: Game not over.
True: Game won, 2048 is found in mat
"""
if 2048 in mat: # If won, teriminal state is needed for RL agent
return True # Terminal state
else:
return False | 5,330,346 |
def mtl_to_json(mtl_text):
""" Convert Landsat MTL file to dictionary of metadata values """
mtl = {}
for line in mtl_text.split('\n'):
meta = line.replace('\"', "").strip().split('=')
if len(meta) > 1:
key = meta[0].strip()
item = meta[1].strip()
if key !... | 5,330,347 |
def endian_swap(word):
"""Given any string, swap bits and return the result.
:rtype: str
"""
return "".join([word[i:i+2] for i in [6, 4, 2, 0]]) | 5,330,348 |
def get_grundsteuer(request_id: str):
"""
Route for retrieving job status of a grundsteuer tax declaration validation from the queue.
:param request_id: the id of the job.
"""
try:
raise NotImplementedError()
except NotImplementedError:
logging.getLogger().info("Could not retriev... | 5,330,349 |
def str_to_col_grid_lists(s):
"""
Convert a string to selected columns and selected grid ranges.
Parameters:
s: (str) a string representing one solution.
For instance, *3**9 means 2 out of 5 dimensions are selected; the second and the last columns are selected,
and their co... | 5,330,350 |
def get_installation_indices_by_installation_id(
db_session: Session, installation_id: Union[str, uuid.UUID]
) -> List[SlackIndexConfiguration]:
"""
Gets all the indices set up in an installation given on the ID of that installation.
"""
bot_installation = (
db_session.query(SlackOAuthEvent)... | 5,330,351 |
def UInt32(self, connection, nullable=False):
"""Verify support for UInt32 data type."""
check_datatype(connection, "UInt32", [0, 4294967295], expected={
"all": "[(0, ), (4294967295, )]",
0: "[(0, )]",
4294967295: "[(4294967295, )]"
}, nullable=nullable) | 5,330,352 |
def convert_hdf(proj_dir, dir_list, hdf_filepath_list, hdf_filename_list):
"""Converts downloaded HDF file into geotiff file format."""
global src_xres
global src_yres
geotiff_list = []
"""Converts MODIS HDF files to a geotiff format."""
print "Converting MODIS HDF files to geotiff format..."
... | 5,330,353 |
def _django_db_setup(request,
_django_test_environment,
_django_cursor_wrapper):
"""Session-wide database setup, internal to pytest-django"""
skip_if_no_django()
from .compat import setup_databases, teardown_databases
# xdist
if hasattr(request.config, 'sl... | 5,330,354 |
def _join_type_and_checksum(type_list, checksum_list):
"""
Join checksum and their correlated type together to the following format:
"checksums": [{"type":"md5", "checksum":"abcdefg}, {"type":"sha256", "checksum":"abcd12345"}]
"""
checksums = [
{
"type": c_type,
"chec... | 5,330,355 |
def _local_groupby(df_rows, axis=0):
"""Apply a groupby on this partition for the blocks sent to it.
Args:
df_rows ([pd.DataFrame]): A list of dataframes for this partition. Goes
through the Ray object store.
Returns:
A DataFrameGroupBy object from the resulting groupby.
""... | 5,330,356 |
def colors_terrain() -> dict:
"""
Age of Empires II terrain colors for minimap.
Credit for a list of Age of Empires II terrain and player colors goes to:
https://github.com/goto-bus-stop/recanalyst.
This function has great potential for contributions from designers
and other specialists.
... | 5,330,357 |
def handle_kv_string(val):
"""This method is used as type field in --filter argument in ``buildtest buildspec find``.
This method returns a dict of key,value pair where input is in format
key1=val1,key2=val2,key3=val3
Args:
val (str): Input string in ``key1=value1,key2=value2`` format that is pr... | 5,330,358 |
def _load_dataset(dataset_config, *args, num_batches=None, **kwargs):
"""
Loads a dataset from configuration file
If num_batches is None, this function will return a generator that iterates
over the entire dataset.
"""
dataset_module = import_module(dataset_config["module"])
dataset_fn = ge... | 5,330,359 |
def file_consolidate(filename):
""" Consolidates duplicates and sorts by frequency for speedy lookup. """
# TODO: Really big files should not be loaded fully into memory to sort them.
# TODO: Make it more robust, actually checking for errors, etc.
sorting_hat = []
in_file = codecs.open(filename, 'r... | 5,330,360 |
def mock_checks_health(mocker: MockFixture):
"""Fixture for mocking checks.health."""
return mocker.patch("website_checker.checks.health") | 5,330,361 |
def decode_jwt(
jwt_string: str
) -> Dict[Any, Any]:
""" Decodes the given JWT string without performing any verification.
Args:
jwt_string (str): A string of the JWT to decode.
Returns:
dict: A dictionary of the body of the JWT.
"""
return jwt.decode( # type: ignore
j... | 5,330,362 |
def test_create_hubspot3_client():
"""attempts to create a hubspot3 client"""
with pytest.raises(HubspotNoConfig):
hubspot = Hubspot3()
with pytest.raises(HubspotBadConfig):
hubspot = Hubspot3(api_key=TEST_KEY, access_token=TEST_KEY)
hubspot = Hubspot3(api_key=TEST_KEY)
assert hubsp... | 5,330,363 |
def _resolve_references(navigation, version, language):
"""
Iterates through an object (could be a dict, list, str, int, float, unicode, etc.)
and if it finds a dict with `$ref`, resolves the reference by loading it from
the respective JSON file.
"""
if isinstance(navigation, list):
# na... | 5,330,364 |
def phq(data: pd.DataFrame, columns: Optional[Union[Sequence[str], pd.Index]] = None) -> pd.DataFrame:
"""Compute the **Patient Health Questionnaire (Depression) โ 9 items (PHQ-9)**.
The PHQ-9 is a measure for depression.
.. note::
This implementation assumes a score range of [1, 4].
Use :... | 5,330,365 |
def check_unread():
"""
reply to any valid summons in replies / messages / mentions
"""
for message in r.get_unread():
try:
if message.subreddit in restricted_subreddits:
r.send_message(message.author, "episodebot could not reply",
"epis... | 5,330,366 |
def test_for_verbose_exceptions(data_input, models_from_data):
"""
Executes simulate() with verbose enabled to ensure that there are
no exceptions while in verbose mode.
"""
# Redirect the verbose out to null.
stdout = sys.stdout
with open(os.devnull, 'w') as f:
sys.stdout = f
... | 5,330,367 |
def mbc_choose_any_program(table_path):
"""
randomly select one item of MBCRadioProgramTable
:param table_path:
:return:
"""
table = playlist.MBCRadioProgramTable(table_path=table_path)
programs = list(filter(lambda x: x.playlist_slug, table.programs))
random_id = randint(0, len(programs... | 5,330,368 |
def test_init_config_by_name():
"""Tests Config initialization, passing config set name.
"""
config_collection = os.environ.get('CONFIG_COLLECTION')
config_obj = Config(TEST_PROPS_NAME)
assert config_obj
assert config_obj._collection
assert config_obj._collection.name == config_collection
... | 5,330,369 |
def logout_view(request):
"""Logout a user."""
logout(request)
return redirect('users:login') | 5,330,370 |
def get_file_without_path(file_name, with_extension=False):
"""
get the name of a file without its path
"""
base = os.path.basename(file_name)
if not with_extension:
base = os.path.splitext(base)[0]
return base | 5,330,371 |
def _cast(vtype, value):
"""
Cast a table type into a python native type
:param vtype: table type
:type vtype: string
:param value: value to cast
:type value: string
"""
if not vtype:
return None
if isinstance(value, str):
return_value = value.strip()
... | 5,330,372 |
def before(*args, **kw):
"""Advice before business logic"""
print "Entering" | 5,330,373 |
def L2Norm(inputs, axis=0, num_axes=-1, eps=1e-5, mode='SUM', **kwargs):
"""L2 Normalization, introduced by `[Liu et.al, 2015] <https://arxiv.org/abs/1506.04579>`_.
Parameters
----------
inputs : Tensor
The input tensor.
axis : int
The start axis of stats region.
num_axes : int
... | 5,330,374 |
def test_destroy_select_module(cd_tmp_path, cp_config, monkeypatch):
"""Test destroy select from two modules."""
cp_config("min_required_multi", cd_tmp_path)
mock_destroy = MagicMock()
monkeypatch.setattr(MODULE + ".Runway.destroy", mock_destroy)
runner = CliRunner()
# 2nd deployment, out of ran... | 5,330,375 |
def check_output_directory(output_dir):
""" Check that the output directory exists, creating it if it doesn't. """
if not os.path.exists(output_dir):
logger.info("Creating directory %s." % (output_dir))
try:
os.makedirs(output_dir, mode=0o770)
except Exception as err:
... | 5,330,376 |
def has_option(obj, keywords: Union[str, Sequence[str]]) -> bool:
"""
Return a boolean indicating whether the given callable `obj` has the `keywords` in its signature.
"""
if not callable(obj):
return False
sig = inspect.signature(obj)
return all(key in sig.parameters for key in ensure_t... | 5,330,377 |
def create_element_rand(element_id):
"""
This function simply returns a 32 bit hash of the element id.
The result value should be used a random priority.
:param element_id: The element unique identifier
:return: an random integer
"""
import mmh3
import struct
if isinstance(element_i... | 5,330,378 |
def export_raw_canvas_to_images(sql_connection: sqlite3.Connection,
output_directory: str):
"""Export the base64 encoded canvases to image files.
Args:
sql_connection: The connection to the in-memory database.
output_directory: The directory where to store the ca... | 5,330,379 |
def removeKnobChanged(call, args=(), kwargs={}, nodeClass='*', node=None):
"""Remove a previously-added callback with the same arguments."""
pass | 5,330,380 |
def test_dataset_rm(tmpdir, runner, project, client, subdirectory):
"""Test removal of a dataset."""
# try to delete non existing dataset
result = runner.invoke(cli, ['dataset', 'rm'])
assert 2 == result.exit_code
result = runner.invoke(cli, ['dataset', 'rm', 'does-not-exist'])
assert 2 == resu... | 5,330,381 |
def add_sp500_subparser(subparsers):
"""
Add subparser for S&P 500 Stocks
"""
sp500 = subparsers.add_parser("sp500", help="Analyze the S&P 500")
sp500.set_defaults(pages=get_sp500) | 5,330,382 |
def _ul_add_action(actions, opt, res_type, stderr):
"""Create new and append it to the actions list"""
r = _UL_RES[opt]
if r[0] is None:
_ul_unsupported_opt(opt, stderr)
return False
# we always assume the 'show' action to be requested and eventually change it later
actions.append(
... | 5,330,383 |
def Win32Write(self, packet):
"""See base class."""
if len(packet) != self.GetOutReportDataLength():
raise OSError('Packet length must match report data length.')
out = bytes(bytearray(packet)) # Prepend the zero-byte (report ID)
num_written = windows.wintypes.DWORD()
ret = (
... | 5,330,384 |
def _pack(cmd_id: int, payload: List[Any], privkey: datatypes.PrivateKey) -> bytes:
"""Create and sign a UDP message to be sent to a remote node.
See https://github.com/ethereum/devp2p/blob/master/rlpx.md#node-discovery for information on
how UDP packets are structured.
"""
cmd_id = to_bytes(cmd_id... | 5,330,385 |
def clip_boxes(boxes, shape):
"""
:param boxes: (...)x4, float
:param shape: h, w
"""
orig_shape = boxes.shape
boxes = boxes.reshape([-1, 4])
h, w = shape
boxes[:, [0, 1]] = np.maximum(boxes[:, [0, 1]], 0)
boxes[:, 2] = np.minimum(boxes[:, 2], w)
boxes[:, 3] = np.minimum(boxes[:... | 5,330,386 |
def loss_fn(
models, backdoored_x, target_label, l2_factor=settings.BACKDOOR_L2_FACTOR,
):
"""loss function of backdoor model
loss_student = softmax_with_logits(teacher(backdoor(X)), target)
+ softmax_with_logits(student(backdoor(X)), target)
+ L2_norm(mask_matrix)
Args:
models(Python dict): teacher... | 5,330,387 |
def create_otp(slug, related_objects=None, data=None, key_generator=None, expiration=None, deactivate_old=False):
"""
Create new one time password. One time password must be identified with slug.
Args:
slug: string for OTP identification.
related_objects: model instances related with OTP.
... | 5,330,388 |
def get_pod_from_dn(dn):
"""
This parses the pod from a dn designator. They look like this:
topology/pod-1/node-101/sys/phys-[eth1/6]/CDeqptMacsectxpkts5min
"""
pod = POD_REGEX.search(dn)
if pod:
return pod.group(1)
else:
return None | 5,330,389 |
def extend_table(rows, table):
"""
appends the results of the array to the existing table by an objectid
"""
try:
dtypes = np.dtype(
[
('_ID', np.int),
('DOM_DATE', '|S48'),
('DOM_DATE_CNT', np.int32),
('DOM_DATE_PER', n... | 5,330,390 |
def p_compound_statement_3(p):
"""compound_statement : ASSEMBLY_DIRECTIVE STRING_LITERAL"""
p[0] = {"code": [["ASSEMBLY_DIRECTIVE", p[2]]]} | 5,330,391 |
def drawblock(arr, num_class=10, fixed=False, flip=False, split=False):
"""
draw images in block
:param arr: array of images. format='NHWC'. sequence=[cls1,cls2,cls3,...,clsN,cls1,cls2,...clsN]
:param num_class: number of class. default as number of images across height. Use flip=True to set number of w... | 5,330,392 |
def error_handling(error_to_raise: Union[PyViewsError, Type[PyViewsError]],
add_error_info: Callable[[PyViewsError], None] = None):
"""handles error and raises PyViewsError with custom error info"""
add_error_info = add_error_info if add_error_info is not None else _do_nothing
try:
... | 5,330,393 |
def mypy() -> None:
"""Check type annotations."""
_output(['mypy', '.', '--exclude', 'environment/vendor/']) | 5,330,394 |
def with_key(output_key_matcher):
"""Check does it have a key."""
return output_key_matcher | 5,330,395 |
def generatePersistenceManager(inputArgument, namespace = None):
"""Generates a persistence manager base on an input argument.
A persistence manager is a utility object that aids in storing persistent data that must be saved after the interpreter shuts
down. This function will interpret the input argum... | 5,330,396 |
def get_app():
"""
Creates a Sanic application whose routes are documented using the `api` module.
The routes and their documentation must be kept in sync with the application created
by `get_benchmark_app()`, so that application can serve as a benchmark in test cases.
"""
app = Sanic("test_api... | 5,330,397 |
def predict(request):
"""View to predict output for selected prediction model
Args:
request (json): prediction model input (and parameters)
Returns:
json: prediction output
"""
projects = [{"name":"Erschlieรung Ob den Hรคusern Stadt Tengen", "id":101227},
{"name"... | 5,330,398 |
def is_dict(etype) -> bool:
""" Determine whether etype is a Dict """
return type(etype) is GenericMeta and etype.__extra__ is dict | 5,330,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.