content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_mremove_misspelled_component(ac_dc_network, caplog):
"""
GIVEN the AC DC exemplary pypsa network.
WHEN a misspelled component is removed with mremove
THEN the function should not change anything in the Line component
dataframe and an error should be logged.
"""
... | 400 |
def _f7(seq: Sequence) -> List:
"""order preserving de-duplicate sequence"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | 401 |
def mir_snp(fpath, mirna_fa, out_dir, transcript_fa, gtf,
flank=DEFAULT_FLANK, run_rnahybrid=True):
"""
fpath: variants file
mirna_fa: miRNA sequences, FASTA
out_dir: main output directory
transcript_fa: human genome exon region fasta,created by gffread
gtf: gtf
flank: flank sequ... | 402 |
def get_config(cfg):
"""
Sets the hypermeters for the optimizer and experiment using the config file
Args:
cfg: A YACS config object.
"""
config_params = {
"train_params": {
"adapt_lambda": cfg.SOLVER.AD_LAMBDA,
"adapt_lr": cfg.SOLVER.AD_LR,
"lamb... | 403 |
def get_nas_transforms():
""" Returns trajectory transformations for NAS. """
return [
PadActions(),
AsArray(),
RewardsAsValueTargets(),
TileValueTargets()
] | 404 |
def epoch_to_datetime(epoch):
"""
:param epoch: str of epoch time
:return: converted datetime type
"""
return datetime.datetime.fromtimestamp(float(epoch) / 1000) | 405 |
def qe_m4(px,mlmax,Talm=None,fTalm=None):
"""
px is a pixelization object, initialized like this:
px = pixelization(shape=shape,wcs=wcs) # for CAR
px = pixelization(nside=nside) # for healpix
output: curved sky multipole=4 estimator
"""
ells = np.arange(mlmax)
#prepare temperature map
... | 406 |
def recorded_run(self, run_id, tale_id):
"""Start a recorded run for a tale version"""
cli = docker.from_env(version='1.28')
run = self.girder_client.get('/run/{}'.format(run_id))
tale = self.girder_client.get('/tale/{}'.format(tale_id))
user = self.girder_client.get('/user/me')
def set_run_s... | 407 |
def seasonality_plot_df(m, ds):
"""Prepare dataframe for plotting seasonal components.
Parameters
----------
m: Prophet model.
ds: List of dates for column ds.
Returns
-------
A dataframe with seasonal components on ds.
"""
df_dict = {'ds': ds, 'cap': 1., 'floor': 0.}
for n... | 408 |
async def response(request: DiscoveryRequest, xds_type: DiscoveryTypes, host: str = 'none'):
"""
A Discovery **Request** typically looks something like:
.. code-block:: json
{
"version_info": "0",
"node": {
"cluster": "T1",
"build_version": "... | 409 |
def count_inner_bags(content, start_color):
"""Count inner bags"""
rules = process_content(content)
bags = rules[start_color]
count = len(bags)
while len(bags) != 0:
new_bags = []
for bag in bags:
count += len(rules[bag])
new_bags += rules[bag]
bags =... | 410 |
def build_generation_data(
egrid_facilities_to_include=None, generation_years=None
):
"""
Build a dataset of facility-level generation using EIA923. This
function will apply filters for positive generation, generation
efficiency within a given range, and a minimum percent of generation
fr... | 411 |
def get_nessus_scans():
"""Return a paginated list of Nessus scan reports.
**Example request**:
.. sourcecode:: http
GET /api/1.0/analysis/nessus?page=1 HTTP/1.1
Host: do.cert.europa.eu
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.0... | 412 |
def count_failures(runner):
"""Count number of failures in a doctest runner.
Code modeled after the summarize() method in doctest.
"""
try:
from doctest import TestResults
except:
from _doctest26 import TestResults
return [TestResults(f, t) for f, t in runner._name2ft.values() ... | 413 |
def fnv1_64(data, hval_init=FNV1_64_INIT):
"""
Returns the 64 bit FNV-1 hash value for the given data.
"""
return fnv(data, hval_init, FNV_64_PRIME, 2**64) | 414 |
def recongnize_image_file(args, image_file, output_dir):
"""
遍历图片文件
:param input_dir:
:return:
"""
temp_name = image_file.split('/')[-1].split('.')[0]
textract_json = None
label_file = os.path.join( output_dir, temp_name + '.txt')
#print("label_file ", label_file)
#print("outpu... | 415 |
def redirectLoggerStreamHandlers(oldStream, newStream):
"""Redirect the stream of a stream handler to a different stream
"""
for handler in list(logger.handlers): #Remove old handlers
if handler.stream == oldStream:
handler.close()
logger.removeHandler(handler)
for handle... | 416 |
def parse(file_path, out):
"""
parse the header file:
- recursively call includes if not parsed yet
- write the rest of the file to the output file
"""
print("parsing: " + file_path)
with open(file_path) as f:
for line in f:
include_match = re.search('#include[\s]*<[a-zA-... | 417 |
def parse_data_sp(source_root, parallel_roots, glob_str="**/*.wav", add_source=False):
"""
assert that parallel_root wil contain folders of following structure:
PARALLEL_ROOT/record_17/IPhone 12 Pro Max/JBL CLIP3/distance=60-loudness=15-recording_mode=default/RELATIVE_PATH_TO_WAV_FROM_SOURCE
"""
dat... | 418 |
def heat_diffusion(A, t, L, k, eps=0.0001):
"""
Computes the heat diffusion equation
Parameters
----------
A : Tensor or SparseTensor
the (N,N,) density matrix
t : float
the diffusion time
L : Tensor or SparseTensor
the (N,N,) Laplacian matrix
k : Tensor
... | 419 |
def help() :
"""print cache help"""
log.info(log.YELLOW +
"fips cache\n"
"fips cache [config]\n" + log.DEF +
" open the CMakeCache file with your default text editor") | 420 |
def unpack_ad_info(ad_info: dict, param_name: str) -> bytes:
"""Проверяет наличие ожидаемой структуры и возвращает значение."""
# Красиво не сработает, потому что применение условий должно быть последовательным
if (
isinstance(ad_info, dict)
and ad_info.get(param_name) # noqa: W503
... | 421 |
def _read_file(file, sheet_name=0):
"""
Helper function used to read the file and return a pandas dataframe.
Checks if file type is a .csv or excel. If not,
returns a ValueError.
Parameters
----------
file : str
the name of the file, including the filetype extension
sheet_name : ... | 422 |
def get_school_total_students(school_id, aug_school_info):
"""
Gets total number of students associated with a school.
Args:
district_id (str): NCES ID of target district (e.g. '0100005').
aug_school_info (pandas.DataFrame): Target augmented school information
(as formatted by... | 423 |
def loci_adjust(ds, *, group, thresh, interp):
"""LOCI: Adjust on one block.
Dataset variables:
hist_thresh : Hist's equivalent thresh from ref
sim : Data to adjust
"""
sth = u.broadcast(ds.hist_thresh, ds.sim, group=group, interp=interp)
factor = u.broadcast(ds.af, ds.sim, group=group,... | 424 |
def output_thread():
""" output thread function
for getting inference results from Movidius NCS
running graph specific post processing of inference result
queuing the results for main thread callbacks
"""
global gRunning
try:
while gRunning:
try:
inference_result, user_data = gGraph.Get... | 425 |
def _ClientThread(client_ip, client_user, client_pass, mvip, username, password, purge):
"""delete the volumes for a client, run as a thread"""
log = GetLogger()
SetThreadLogPrefix(client_ip)
log.info("Connecting to client")
client = SFClient(client_ip, client_user, client_pass)
account_name = ... | 426 |
def objective(args: Namespace, trial: optuna.trial._trial.Trial) -> float:
"""Objective function for optimization trials.
Args:
args (Namespace): Input arguments for each trial (see `config/args.json`) for argument names.
trial (optuna.trial._trial.Trial): Optuna optimization trial.
Returns:... | 427 |
def read_gdwarfs(file=_GDWARFALLFILE,logg=False,ug=False,ri=False,sn=True,
ebv=True,nocoords=False):
"""
NAME:
read_gdwarfs
PURPOSE:
read the spectroscopic G dwarf sample
INPUT:
logg= if True, cut on logg, if number, cut on logg > the number (>4.2)
ug= if Tru... | 428 |
def add_item(category_slug=None):
"""
Add a new Item Form.
:param category_slug: The category slug
"""
# Get the current category using the slug
current_category = Category.where('slug', category_slug).first()
return render_template(
'items/add.html',
categories=Category.a... | 429 |
def test_list_overlays_when_dir_missing(chdir_fixture): # NOQA
"""
This test simulates checking out a frozen dataset from Git that has no
overlays written to it, i.e. where the ``.dtool/overlays`` directory is
missing.
See also:
https://github.com/jic-dtool/dtoolcore/issues/3
"""
from... | 430 |
def track_type(time, lat, tmax=1):
"""
Determines ascending and descending tracks.
Defines unique tracks as segments with time breaks > tmax,
and tests whether lat increases or decreases w/time.
"""
# Generate track segment
tracks = np.zeros(lat.shape)
# S... | 431 |
def get_installed_procnames():
"""Get a list of procs currently on the file system."""
return set(get_procs()) | 432 |
def check(model_opt: onnx.ModelProto, model_ori: onnx.ModelProto, n_times: int = 5) -> None:
"""
Warning: Some models (e.g., MobileNet) may fail this check by a small magnitude.
Just ignore if it happens.
:param model_opt: The simplified ONNX model
:param model_ori: The original ONNX model
:para... | 433 |
def pam_bw_as_matrix(buff, border):
"""\
Returns the QR code as list of [0, 1] lists.
:param io.BytesIO buff: Buffer to read the matrix from.
:param int border: The QR code border
"""
res = []
data, size = _image_data(buff)
for i, offset in enumerate(range(0, len(data), size)):
... | 434 |
def delete_task(task_id: int):
"""Remove task with associated ID from the database."""
send_to_login = ensure_login()
if send_to_login:
return send_to_login
else:
old_task = Task.delete(task_id)
flash(f'You deleted "{old_task.title}"', "info")
return redirect(url_for("ta... | 435 |
def KDPReboot(cmd_args=None):
""" Restart the remote target
"""
if "kdp" != GetConnectionProtocol():
print "Target is not connected over kdp. Nothing to do here."
return False
print "Rebooting the remote machine."
lldb.debugger.HandleCommand('process plugin packet send --command 0x1... | 436 |
def get_version(): # noqa: E501
"""API version
The API version # noqa: E501
:rtype: str
"""
return '1.0.0' | 437 |
def bert_evaluate(model, eval_dataloader, device):
"""Evaluation of trained checkpoint."""
model.to(device)
model.eval()
predictions = []
true_labels = []
data_iterator = tqdm(eval_dataloader, desc="Iteration")
for step, batch in enumerate(data_iterator):
input_ids, input_mask, label... | 438 |
def test_sign_and_recover_message():
"""Test the signing and the recovery of a message."""
account = FetchAICrypto(FETCHAI_PRIVATE_KEY_PATH)
sign_bytes = account.sign_message(message=b"hello")
assert len(sign_bytes) > 0, "The len(signature) must not be 0"
recovered_addresses = FetchAIApi.recover_mes... | 439 |
def get_cached_scts(hex_ee_hash):
""" get_cached_scts returns previously fetched valid SCT from this certificate. The key to perform this search is
the hex-encoded hash of the end-entity certificate
:param hex_ee_hash: the hex-encoded hash of the end-entity certificate
:return: a dictionary of SCTs whe... | 440 |
def manual_init(board: Board, initial_cells: int):
"""
Click to add/remove cells.
Stop when you've added configured number.
"""
live_cells = 0
while live_cells < initial_cells:
print(f"Cells remaining to input {initial_cells - live_cells}")
grid = plt.imshow(board.binary_grid, cm... | 441 |
def set_gps_model(gps):
"""Updates current gps_model and publishes merged model."""
try:
g['gps_model'] = np.squeeze(
bridge.imgmsg_to_cv2(gps, desired_encoding='mono8'))
merge_and_publish()
except CvBridgeError:
rospy.loginfo("Error converting gps model to cv2")
... | 442 |
def bin_to_hex() -> None:
"""Convierte un binario a hexadecimal."""
n = str_input("> ")
result = hex(int(n, 2))[2:]
textbox(str(result)) | 443 |
def all_gather_multigpu(
output_tensor_lists, input_tensor_list, group=None, async_op=False
):
"""
Gathers tensors from the whole group in a list.
Each tensor in ``tensor_list`` should reside on a separate GPU
Only nccl backend is currently supported
tensors should only be GPU tensors
Comp... | 444 |
def test_rejects_invalid_year() -> None:
"""It rejects invalid years."""
x = pd.Series(
[
"nan",
"x",
"1.2",
]
)
error = parse_year(x)
pd.testing.assert_series_equal(x, pd.Series(error["values"])) | 445 |
def get_uuid_from_str(input_id: str) -> str:
"""
Returns an uuid3 string representation generated from an input string.
:param input_id:
:return: uuid3 string representation
"""
return str(uuid.uuid3(uuid.NAMESPACE_DNS, input_id)) | 446 |
def extend_request(request_id=None, workload_id=None, lifetime=30):
"""
extend an request's lifetime.
:param request_id: The id of the request.
:param workload_id: The workload_id of the request.
:param lifetime: The life time as umber of days.
"""
return requests.extend_request(request_id=... | 447 |
def from_bytes(buf: bytes) -> str:
"""Return MIME type from content in form of bytes-like type.
Example:
>>> import defity
>>> defity.from_bytes(b'some-binary-content')
'image/png'
"""
_guard_buf_arg(buf)
# We accept many input data types just for user's convenience. We still c... | 448 |
def pl__5__create_train_frame_sequences(ctvusts_by_tcp__lte_1, frame_sequences__by__tcpctvustsfs, train_tcpctvustsfs__gt__1):
"""
returns:
train_tcpctvustsfs__all
(
<TokenID>,
<CameraPerspective>,
<ASLConsultantID>,
<TargetVideo... | 449 |
def createList(value, n):
"""
@param value: value to initialize the list
@param n: list size to be created
@return: size n list initialized to value
"""
return [value for i in range (n)] | 450 |
def label_class_num(label):
"""
标签的种类
:param label:
:return:
"""
return label.shape[1] | 451 |
def heur(puzzle, item_total_calc, total_calc):
"""
Heuristic template that provides the current and target position for each number and the
total function.
Parameters:
puzzle - the puzzle
item_total_calc - takes 4 parameters: current row, target row, current col, target col.
Returns i... | 452 |
def make_argparse_help_safe(s):
"""Make strings safe for argparse's help.
Argparse supports %{} - templates. This is sometimes not needed.
Make user supplied strings safe for this.
"""
return s.replace('%', '%%').replace('%%%', '%%') | 453 |
def _file_content_hash(file_name, encoding, database=None, newline=None):
"""
Returns the file content as well as the hash of the content
Use the database to keep a persistent cache of the last content
hash. If the file modification date has not changed assume the
hash is the same and do not re-op... | 454 |
def leaderboard(avatars, usernames, levels):
"""
Draw the leaderboard. Return the path of the image.
The path points to a temporary file with extension png. The caller
is responsible for removing this temporary file.
avatars is 10 top users' avatar images. It should be a list of
BytesIO or ... | 455 |
def create_pysm_commands(
mapfile,
nside,
bandcenter_ghz,
bandwidth_ghz,
beam_arcmin,
coord,
mpi_launch,
mpi_procs,
mpi_nodes,
):
"""
Return lines of shell code to generate the precomputed input sky map.
"""
mpistr = "{}".format(mpi_launch)
if mpi_procs != "":
... | 456 |
def edits1(word):
""" All edits that are one edit away from `word`. """
letters = 'abcdefghijklmnopqrstuvwxyz'
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in... | 457 |
def test_umlaut_update_client_description():
"""
Tests umlaut on description string.
"""
pm = MockPymill('key')
clientid = "client_12345"
pm.update_client(client_id = clientid, email="foo@example.com", description='Ümläüt')
assert pm.api_called
assert pm.call_args['params'].get('descript... | 458 |
def process_text_cn(text: str):
"""中文文本处理"""
text = del_white_chars(text)
text = sub_punctuation(text)
return text | 459 |
def total_elastic_cross_section_browning1994_cm2(atomic_number, energy_keV):
"""
From browning1994
Valid in the range 100 eV to 30 keV for elements 1 to 92.
"""
Z = atomic_number
E = energy_keV
factor = 3.0e-18
power_z = math.pow(Z, 1.7)
power_e = math.pow(E, 0.5)
nominator = fac... | 460 |
def connector_setup():
"""
Fill the sandbox with fresh data by sending simple text-only messages.
"""
config = Config
now = datetime.datetime.now().timestamp()
if config.get_test_data()["last_update_timestamp"] + config.min_update_interval <= now:
data_filler: DataFiller = DataFiller(
... | 461 |
def includeme(config):
"""
Initialize the model for a Pyramid app.
Activate this setup using ``config.include('datameta.models')``.
"""
settings = config.get_settings()
settings['tm.manager_hook'] = 'pyramid_tm.explicit_manager'
# use pyramid_tm to hook the transaction lifecycle to the re... | 462 |
def plot_fancy(nodes, elems, phi=None, charge=None, u=None, charge_max=None,
show=False, save=None, num_intp=100, title=None, clabel=None,
animation_mode=True, latex=False):
""" Plots fancily. """
if animation_mode:
fig = Figure(colorbar=False, tight_layout=True, show=show,... | 463 |
def buildModelGPT(modelType='gpt2-medium'):
"""
This function builds the model of the function und returns it based on GPT
"""
## Create Model
# Load pre-trained model tokenizer (vocabulary)
tokenizer = GPT2Tokenizer.from_pretrained(modelType)
# Load pre-trained model (weights)
model = GPT2LMHeadMo... | 464 |
async def test_resume_all_workers_empty_json(aresponses):
"""Test resume_all_workers() method is handled correctly when given empty json."""
aresponses.add(
MATCH_HOST,
"/unmanic/api/v2/workers/worker/resume/all",
"POST",
aresponses.Response(
status=200,
h... | 465 |
def vid_to_list(filepath):
"""
Converts a video file to a list of 3d arrays of dim (h, w, c)
Input:
filepath: (str) full filepath of video
Output:
vid: (ndarray) list of 3d numpy arrays, of shape (height, width, color)
"""
cap = cv.VideoCapture(filepath)
list_of_frames = ... | 466 |
def match_aws_gcp(gcp_index_path, aws_index_paths):
"""Match AWS and GCP metadata datasets
Note this assumes that if the _folder_ exists, then all files exist in the
COGS bucket. I.e. it doesn't check that all files are correctly there.
"""
gcp_df = load_google_metadata(gcp_index_path)
for aws_... | 467 |
def from_pickle(fname=interpolator_path):
"""Loads grid inperpolator from pickle located at `fname`.
"""
with open(fname, "rb") as f:
grid = pickle.load(f)
return grid | 468 |
def click_instance_center(instance_name:str, ocr_result:list):
"""鼠标单击instance_name
Args:
instance_name (str): 实例名称
ocr_result (list): 识别结果列表
"""
if len(ocr_result) == 0:
return
ret_list = [ line[0] for line in ocr_result if instance_name in line[1][0] ]
if len(ret_list)... | 469 |
def test_drop_privs():
"""
test that privileges are dropped when jsonp is requested
so that we cannot get private data
"""
tiddler = Tiddler('private')
tiddler.bag = 'foo_private'
tiddler.text = 'some text'
store.put(tiddler)
user_cookie = get_auth('foo', 'foobar')
callback = 'c... | 470 |
def get_prob_and_custom_prob_per_crops(
logits_for_patches,
img_size_work_px_space,
n_pixels_in_crop,
descendent_specifier,
target_list,
rf,
DEVICE,
):
"""Determine the probability and the custom probability (i.e. the non-Deep-Learning "logit", cf. Appendix C.2) for crops according to th... | 471 |
def xywh_to_xyxy(boxes):
"""Convert [x y w h] box format to [x1 y1 x2 y2] format."""
if boxes is None or len(boxes) == 0:
return boxes
boxes = np.array(boxes)
return np.hstack((boxes[:, 0:2], boxes[:, 0:2] + boxes[:, 2:4] - 1)) | 472 |
def unionanlex():
"""Realiza la construcción del analizador léxico a través de la unión de diferentes AFNs
"""
lst = [] # Lista donde se guardarán los AFNs a unir
id = 0
while id != -1:
print("AFNs escogidos:\n", lst)
print("Escoja un ID de los AFNs disponibles (termine con -1):")
... | 473 |
def vscat(a,fig=None,ls=None,marker='o',nmin=2,mhmin=-3,density=False,out=None) :
""" Make histograms of VSCATTER for different bins of Teff H], given min NVISITS, and min [M/H]
"""
if fig == None : fig,ax=plots.multi(4,6,hspace=0.001,wspace=0.4,figsize=(12,8))
else : fig,ax=fig
tbins=[3000,3500,400... | 474 |
def install(ctx, platform, arch, java_version='8'):
"""
Download and extract the Java JDK.
"""
global java_home, java_dir
try:
url = azul_jdk[java_version][f'{platform}:{arch}']
except KeyError:
raise NotImplementedError(
f'Unsupported java version, platform or archi... | 475 |
def parse_unique_count_for_column(column_df, column):
"""
returns column specific distribution details.
sample output,
```
"<column_df>": {
"<>": 30
}
```
"""
return {column: get_unique_counts_of_column(column_df)} | 476 |
def transaction():
"""
Get database transaction object
:return: _TransactionContext object
usage:
with transaction():
# transactions operation
pass
>>> def update_profile(t_id, name, rollback):
... u = dict(id=t_id, name=name, email='%s@test.org' % name, password=name, ... | 477 |
def _BoundedIntRange(
description: str = "",
description_tooltip: str = None,
layout: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_layout.Layout]] = {},
max: int = 100,
min: int = 0,
style: Union[Dict[str, Any], Element[ipywidgets.widgets.widget_description.DescriptionStyle]] = {},
... | 478 |
def load_static_mnist(args, **kwargs):
"""
Dataloading function for static mnist. Outputs image data in vectorized form: each image is a vector of size 784
"""
args.dynamic_binarization = False
args.input_type = 'binary'
args.input_size = [1, 28, 28]
# start processing
def lines_to_np_... | 479 |
def get_benchmark_snapshot(benchmark_df,
threshold=_MIN_FRACTION_OF_ALIVE_TRIALS_AT_SNAPSHOT):
"""Finds the latest time where |threshold| fraction of the trials were still
running. In most cases, this is the end of the experiment. However, if less
than |threshold| fraction of the ... | 480 |
def configChromeDriver(webVisible : bool = True , filePathDownload : str = None, filePathWebDriver: str = None) -> WebDriver:
"""
Configure o seu Chrome Driver:
- webVisible ==> Por padrão True para ocultar o webDriver.
- filePathDownload ==> Por padrão será criado uma pasta Downloads na raiz do projeto... | 481 |
def create_trigger_function_with_trigger(server, db_name, schema_name,
func_name):
"""This function add the trigger function to schema"""
try:
connection = utils.get_db_connection(db_name,
server['username'],
... | 482 |
def get_results_seq_len(given_true_eig,
hidden_dim,
input_dim,
min_seq_len,
max_seq_len,
num_sampled_seq_len,
num_repeat,
input_mean,
... | 483 |
def test_basic_cli(tmp_path, scope_files):
"""Test that basic cli works."""
cmd = ["mokapot", scope_files[0], "--dest_dir", tmp_path]
subprocess.run(cmd, check=True)
assert Path(tmp_path, "mokapot.psms.txt").exists()
assert Path(tmp_path, "mokapot.peptides.txt").exists() | 484 |
def episode_to_timestep_batch(
episode: rlds.BatchedStep,
return_horizon: int = 0,
drop_return_horizon: bool = False,
flatten_observations: bool = False,
calculate_episode_return: bool = False) -> tf.data.Dataset:
"""Converts an episode into multi-timestep batches.
Args:
episode: Batched st... | 485 |
def test_async_without_ambi():
"""Equivalent example without ambisync"""
async def testmain():
async def foo():
await asyncio.sleep(1.3)
print('foo')
asyncio.create_task(foo())
test = NoAmbiAsync('noambi test')
await test.my_method('noambi arg')
asyn... | 486 |
def parse(authz_file, modules):
"""Parse a Subversion authorization file.
Return a dict of modules, each containing a dict of paths, each containing
a dict mapping users to permissions. Only modules contained in `modules`
are retained.
"""
parser = UnicodeConfigParser(ignorecase_option=False)
... | 487 |
def send_expiry_note(invite, request, user_name):
"""
Send a notification email to the issuer of an invitation when a user
attempts to accept an expired invitation.
:param invite: ProjectInvite object
:param request: HTTP request
:param user_name: User name of invited user
:return: Amount o... | 488 |
def main():
"""
Main function to run script.
"""
startTime = datetime.now()
logging.info("Running wcry_scanner")
cli_options = gather_cli_options()
rhosts_open_445 = run_masscan(cli_options['subnet'])
rhosts_ms17_vuln = run_nmap(rhosts_open_445)
results_to_file(rhosts_ms17_vuln, cli_... | 489 |
def level_is_between(level, min_level_value, max_level_value):
"""Returns True if level is between the specified min or max, inclusive."""
level_value = get_level_value(level)
if level_value is None:
# unknown level value
return False
return level_value >= min_level_value and level_value... | 490 |
def voronoiMatrix(sz=512,percent=0.1,num_classes=27):
"""
Create voronoi polygons.
Parameters
----------
sz : int
row and column size of the space in which the circle is placed
percent : float
Percent of the space to place down centers of the voronoi polygons.
Smaller percent makes the polygons larger
... | 491 |
def genVBOF2(virus_record, model, model_name=None):
"""New version of the genVBOF function by Hadrien.
Builds a Virus Biomass Objective Function (basically a virus biomass
production reaction, from aminoacids and nucleotides) from a genbank
file.
Params:
- virus_record: genbank record of a ... | 492 |
def parse_args(arguments: Sequence, options: List[str] = None) -> Dict:
"""
Parse input arguments.
Simple assessment that module AWS Glue is not available in pyshell jobs.
Parameters
----------
arguments
Sequence of options and values to be parsed. (sys.argv)
options
Option... | 493 |
def get_current_ms_time() -> int:
"""
:return: the current time in milliseconds
"""
return int(time.time() * 1000) | 494 |
def get_service_info(): # noqa: E501
"""Get information about Workflow Execution Service.
May include information related (but not limited to) the workflow descriptor formats, versions supported, the WES API versions supported, and information about general service availability. # noqa: E501
:rtype: Ser... | 495 |
def str_of_tuple(d, str_format):
"""Convert tuple to str.
It's just str_format.format(*d). Why even write such a function?
(1) To have a consistent interface for key conversions
(2) We want a KeyValidationError to occur here
Args:
d: tuple if params to str_format
str_format: Auto fie... | 496 |
def _intersect(bboxes1, bboxes2):
"""
bboxes: t x n x 4
"""
assert bboxes1.shape[0] == bboxes2.shape[0]
t = bboxes1.shape[0]
inters = np.zeros((bboxes1.shape[1], bboxes2.shape[1]), dtype=np.float32)
_min = np.empty((bboxes1.shape[1], bboxes2.shape[1]), dtype=np.float32)
_max = np.empty((... | 497 |
def test_r4_3_create_product(description, expected):
"""
Testing R4-3: The description of the product can be arbitrary characters,
with a minimum length of 20 characters and a maximum of 2000 characters.
"""
# Register a test user, if exists will just return false
register('Test0', 'test0@test... | 498 |
def convert_x_to_bbox(x,score=None):
"""
Takes a bounding box in the centre form [x,y,s,r] and returns it in the form
[x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right
"""
w = np.sqrt(np.abs(x[2] * x[3]))
if(w<=0):
w=1
h = x[2] / w
if(score==None):
return np.array([... | 499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.