content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def write_manifest(blame_state, path_sha_loc, report_dir, name_description, title):
"""Write a README file in `report_dir`
"""
total_files, total_commits, total_loc = get_totals(path_sha_loc)
totals = 'Totals: %d files, %d commits, %d LoC' % (total_files, total_commits, total_loc)
repo_summary = b... | 53,400 |
def setup_routes():
"""Setup dispatcher routes (i.e. URL paths)"""
root = CherryTarball()
d = cherrypy.dispatch.RoutesDispatcher()
d.connect('main', '/', controller=root)
# This enumerates the tarball and connects each file within to a URL in the dispatcher
tar = tarfile.open(tarball_path)
f... | 53,401 |
def check_voicehat_is_first_card():
"""Check that the voiceHAT is the first card on the system."""
cards = get_sound_cards()
return 0 in cards and VOICEHAT_ID in cards[0] | 53,402 |
def add_sylls_to_textgrid(voice, sc_utt):
""" Reconstruct syllable tier by getting segments based on word
alignments and re-running voice's syllabification algorithm on
(potentially) new pronunciations...
"""
#get phoneset map and invert to map back to native representations
#in ord... | 53,403 |
def removeVM(vm):
"""Removes virtual machine. NOTE: This operation is undo-able.
@param vm: Virtual machine's name."""
return defer.maybeDeferred( _getController().removeVM, vm) | 53,404 |
def probablePosition(board):
"""
|x-pos_x|<3, |y-pos_y|<3
:param
board: the current board state
:return:
position: all position may be considered
"""
probable_list = []
for (pos_x, pos_y) in itertools.product(range(pp.width), range(pp.height)):
if not board[pos_x][pos... | 53,405 |
def get_user_group_perms(
user_or_group: UserOrGroup, obj: models.Model
) -> Tuple[PermissionList, List[Tuple[int, str, PermissionList]]]:
"""Get permissions for the user/group on the given model.
This method is only used in Resolwe views and expects permissions to be
prefetched by the view. To avoid a... | 53,406 |
def test_subgraph_metanode_subset():
"""
Test get_subgraph with a specified subset of metanodes.
"""
graph = get_disease_gene_example_hetnet()
metanodes = [
'Disease',
'Tissue',
]
metanodes = [graph.metagraph.get_node(mn) for mn in metanodes]
subgraph = graph.get_subgraph... | 53,407 |
def update_button(first_color, second_color, _button_state):
"""Updates button, and changes color depending on if the mouse is hovering over button.
Returns if the mouse is hovering over button or not"""
_mouse_hover = False
# noinspection PyChainedComparisons
if mouse[0] > 4 and mouse[0] < 381 and ... | 53,408 |
def get_configmap_fields_from_yaml(file) -> {}:
"""
Parse yaml file and return a dict of ConfigMap data fields.
:param file: an absolute path to a file
:return: {}
"""
with open(file) as f:
dep = yaml.load(f)
return dep['data'] | 53,409 |
def addfella():
"""
This endpoint is for adding fellas to the application.
Loadbalancer decids to go for which instances and based on that fella is added to it.
"""
instance_id = os.getenv("CF_INSTANCE_INDEX")
print 'Instance Id ****************%s'%instance_id
fella_count = int(db.hg... | 53,410 |
def test_generate(analysis, wordform):
"""
Simple test of generating wordforms.
"""
assert wordform in list(strict_generator().lookup(analysis)) | 53,411 |
def join_race_and_gender(c_id_string, artist_df):
"""
takes in a string of c_id(s), ex: "8210" or "8210, 5670"
returns a total count of male, female, white, black, asian, aian, mix, hispanic
"""
male = 0
female = 0
white = 0
black = 0
asian = 0
aian = 0
mix = 0
hispanic =... | 53,412 |
def get_average(pixel, date, dataset):
"""
Return an N month average in the given dataset.
"""
N = 24
vals = []
bad_cnt = 0
# generate lists of month numbers and values
for i in range(N):
try:
vals.append(dataset[date][pixel])
except KeyError:
bad... | 53,413 |
def flake8(obj):
"""
Run flake8.
"""
try:
subprocess.check_call([sys.executable, '-m', 'flake8'])
print("flake8 OK")
except subprocess.CalledProcessError as e:
if e.returncode == 1:
print("\nThere were flake8 errors!") | 53,414 |
def to_mb(s):
"""Simple function to convert `disk_quota` or `memory` attribute string
values into MB integer values.
"""
if s is None:
return s
if s.endswith('M'):
return int(re.sub('M$', '', s))
elif s.endswith('G'):
return int(re.sub('G$', '', s)) * 1000
return 512 | 53,415 |
def subselect_toggled(flag):
""" Respond to the change of allsubselect flag.
"""
global sweep_all
sweep_all = flag | 53,416 |
def get_pattern(plate: str) -> Union[str, NoReturn]:
"""
Given a string that represents a plate, tries to return
its pattern. If the plate is not valid, raises a
PlateNotValidException
"""
if not valid_plate(plate):
raise PlateNotValidException(plate)
pattern = re.sub("[A-Z]", "C", p... | 53,417 |
def list_alerts_by_ip():
"""
List alerts by the source IP or destination IP
"""
args = demisto.args()
time_frame = args.get('time_frame')
start_time = args.get('start_time')
end_time = args.get('end_time')
src_ip = args.get('src_ip')
dest_ip = args.get('dest_ip')
headers = ['Time... | 53,418 |
def example() -> None:
"""Examples group""" | 53,419 |
def Select(combinations, loads, max_number_of_workers):
"""This method selects the optimal combination of appointments.
This method uses Mixed Integer Programming to select the optimal mix of
appointments.
"""
solver = pywraplp.Solver('Select',
pywraplp.Solver.CBC_MIXED_INTEGER_PRO... | 53,420 |
def ensure_module(module_name):
""" ensure module is installed """
try:
__import__(module_name)
except ImportError:
python = sys.executable
print(red("Could not find {module_name}."
" Installing it for you now:".format(**locals())))
local('sudo {python} -m p... | 53,421 |
def main():
"""
Main function
Read the url and show the image.
"""
day, month, year = get_args()
print("The requested date is %i.%i.%i." % (day, month, year))
check_date(year, month, day)
url = get_img_by_date(day, month, year)
print(url)
file_location = urlopen(url)
image_f... | 53,422 |
def test_process_children(cbcsdk_mock, get_summary_response, guid, expected_num_children):
"""Testing Process.children property."""
api = cbcsdk_mock.api
process = api.select(Process, guid)
cbcsdk_mock.mock_request("GET", "/api/investigate/v1/orgs/test/processes/summary", get_summary_response)
# if ... | 53,423 |
def execute_sql_query_table(table_name: str, sql_query: str, dbname: str = "dvf", path_to_secret_yml: str = "../secrets.yml") -> None:
"""
Function to execute a specific sql query on a table
"""
conn = open_connection(dbname=dbname, secrets=path_to_secret_yml)
cur = conn.cursor()
if table_name... | 53,424 |
def voter_stop_opposing_save_doc_view(request):
"""
Show documentation about voterStopSupportingSave
"""
url_root = WE_VOTE_SERVER_ROOT_URL
template_values = voter_stop_opposing_save_doc.voter_stop_opposing_save_doc_template_values(url_root)
template_values['voter_api_device_id'] = get_voter_api... | 53,425 |
def first_date_in_time_dimensions() -> datetime.date:
"""The first date that should appear in time dimensions"""
return datetime.date.today() - datetime.timedelta(days=365) | 53,426 |
def length_left(lumber):
"""
Convenience function for calculating the length left in a piece of lumber
:param lumber: a piece of Lumber
:return: length remaining
"""
return lumber.length_left() | 53,427 |
def create_spawn_point_prefab(team):
"""Return a team-specific spawn-point prefab."""
prefab = {
"name": "spawn_point",
"components": [
{
"component": "StateManager",
"kwargs": {
"initialState": "playerSpawnPoint",
"stateConfigs":... | 53,428 |
def merge_bpe(input_fname: str, output_fname: str):
"""
Merge byte-pair encoded sub-words.
:param input_fname: Path of byte-pair encoded input file, plain text or
gzipped.
:param output_fname: Path of tokenized output file, plain text.
"""
with utils.smart_open(input_fna... | 53,429 |
def del_from_dict(dct: dict, key: tuple[str, ...]) -> None:
"""Delete value from dict using a multi-part key"""
data = dct
*parts, last_part = key
for part in parts:
if part not in data:
data[part] = {}
new_data = data[part]
data = new_data
if last_part in data:... | 53,430 |
def FindOrBuildDpa(dpas, options, grants):
"""Find or build DPA for simulation purpose.
If several DPA, select the one with most grants around (but DPA simulation
options always override the logic).
"""
if options.dpa:
dpa_kml_file = options.dpa_kml or None
dpa = dpa_mgr.BuildDpa(options.dpa, None, p... | 53,431 |
def register(request):
"""
A view that renders the register page for new users. This can only
be access by users that are not currently signed in.
**Context**
``form``
Registration form for new users
**Templates:**
`base/register.html`
... | 53,432 |
def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= mask
fin_loss=tf.reduce_mean(loss)
var... | 53,433 |
def find_matching_paren_pair(s):
"""
Find the first matching pair of parentheses and return their positions
"""
paren_level = -1
open_pos = 0
for i in range(0, len(s)):
if s[i] == "(":
paren_level += 1
if paren_level == 0:
open_pos = i
elif... | 53,434 |
def copy_mol(mol: Chem.rdchem.Mol) -> Chem.rdchem.Mol:
"""Copy a molecule and return a new one.
Args:
mol: a molecule to copy.
"""
return copy.deepcopy(mol) | 53,435 |
def convert_sync_bn(config, model):
"""
Convert the BatchNorm layers in the model to the SyncBatchNorm layers.
For SyncBatchNorm, we support two sources: Apex and PyTorch. The optimized
SyncBN kernels provided by apex run faster.
Args:
config (AttrDict): configuration file
model: P... | 53,436 |
def _(dbmodel, backend):
"""
get_backend_entity for DummyModel DbNode.
DummyModel instances are created when QueryBuilder queries the Django backend.
"""
djnode_instance = djmodels.DbNode(
id=dbmodel.id,
node_type=dbmodel.node_type,
process_type=dbmodel.process_type,
... | 53,437 |
def update_job(function):
"""Decorator to update Task with result."""
@wraps(function)
def wrapper(task_id, *args, **kwargs):
task = Task.objects.get(id=task_id)
task.status = Task.STATUS[1][0]
task.save()
try:
result = function(*args, **kwargs)
task.... | 53,438 |
def log(string, f=None):
"""Log to terminal and to file."""
print(string)
if f is not None:
f.write(string + "\n") | 53,439 |
def settings2str(settings):
"""Create a string out of settings, which can be inserted in the beginning of a bash script."""
raise NotImplementedError | 53,440 |
def filterdiff(diff_file, old_file):
""" Filters registry dump diff file and marks affected keys/values.
Prints to stdout.
Arguments:
1. Registry dump diff file.
2. Old registry dump file (read-only, for references).
"""
with open(diff_file) as f:
for line in mark_diff(f.read().splitlines(), old_file):
pri... | 53,441 |
def checkLogin():
"""
Check if user is logged in
"""
if current_user.is_authenticated:
return {"authenticated": True, "user": current_user.username}
else:
return {"authenticated": False} | 53,442 |
def _load_checkpoint(
checkpoint: Checkpoint, trainer_name: str
) -> Tuple[Any, Optional[Preprocessor]]:
"""Load a Ray Train Checkpoint.
This is a private API.
Args:
checkpoint: The checkpoint to load the weights and
preprocessor from.
trainer_name: Trainer class name to us... | 53,443 |
def aoa_music_1D(steering_vec, rx_chirps, num_sources):
"""Implmentation of 1D MUltiple SIgnal Classification (MUSIC) algorithm on ULA (Uniformed Linear Array).
Current implementation assumes covariance matrix is not rank deficient and ULA spacing is half of the wavelength.
.. math::
P_{} (\\t... | 53,444 |
def add_importance_scores_plot(df, fig, gs, i,
color_dict=False,
y_label="score",
y_label_size=9):
"""
Make nucleotide importance scores plot.
Normalized profile scores range from -1 .. 1.
"""
ax = fig.add_... | 53,445 |
def IsMerge(op):
"""Return true if `op` is a Merge."""
return op.type == "Merge" or op.type == "RefMerge" | 53,446 |
def parse_args():
"""
Parse input arguments
"""
parser = argparse.ArgumentParser(description='Generate txt result file')
parser.add_argument('--dir', dest='base_dir',
help='result base dir',
default='/home/hezheqi/data/frame/result', type=str)
parser.add_argument(... | 53,447 |
def book_info(td):
"""given a BeautifulSoup <td> Tag representing a book,
extract the book's details and return a dict"""
title = td.find("div", "thumbheader").a.text
by_author = td.find('div', 'AuthorName').text
authors = [x.strip() for x in re.sub("^By ", "", by_author).split(",")]
isbn_link ... | 53,448 |
def fetch_imdb_results(slack_signing_key: AnyStr, arguments: List):
"""
This method searches IMDb and returns the links to post on
channel #ideas
:param slack_signing_key:
:param arguments:
:return:
"""
slack_client = get_slack_client(slack_signing_key)
command = "+".join(arguments)... | 53,449 |
def configs(ctx):
"""Validates configuration files in configs and docs."""
ctx.run("yamllint -c .yamllint {docs}".format(docs=DOCS_PATH))
ctx.run("python {}/test_configs.py".format(SCRIPTS_PATH), pty=True) | 53,450 |
def remove_non_txt_files(folder):
"""Delete all non-text files within a folder.
Args:
folder: A folder as a "Path" object.
"""
for file in folder.iterdir():
if not file.name.endswith(".txt"):
file.unlink() | 53,451 |
def find_groups(groups=None, name=None, gid=None, member=None):
"""
Return groups that match the specified values.
Returns an empty list if no groups match.
'member' can be an array and is allowed to be a subset of the 'members' array
associated with a group, i.e. if member == ['a', 'b'] and a giv... | 53,452 |
def btran_helper(eta_list, a):
"""
Helper function for the Btran method.
:param eta_list: Eta vectors list.
:param a: Vector a.
:return: The resulting vector.
"""
if len(eta_list) == 1:
return a.dot(np.linalg.inv(eta_list[0]))
z = btran_helper(eta_list[1:], a)
return z.dot(np... | 53,453 |
def permutation_spearman(xvals, yvals, trials=1e5, normalize=True, doparallel=True):
"""
given a list of xvals and yvals, returns a p-value that is
the fraction of the trials that return a larger (in magnitude)
Spearmann r coefficient than the actual x-y pairs. smaller
p-value means more correlati... | 53,454 |
def test_delete_row_wp():
"""One row deleted in WP, no changes in master"""
config_file = os.path.join(this_dir, "config-farm-basic.yml")
tmp_dir_1 = _make_initial_farm_work_packages(config_file)
tmp_dir_2 = _prepare_next_run_work_packages(tmp_dir_1)
# modify a WP dataset - delete a tree (master fi... | 53,455 |
def to_binary(n):
"""Convert integer n to binary form."""
if n == 0:
return zero
elif n == 1:
return one
elif n % 2 == 0:
return bit0(to_binary(n // 2))
else:
return bit1(to_binary(n // 2)) | 53,456 |
def get_short_interest_days_to_cover(sort_field: str) -> pd.DataFrame:
"""Get short interest and days to cover. [Source: Stockgrid]
Parameters
----------
sort_field : str
Field for which to sort by, where 'float': Float Short %%,
'dtc': Days to Cover, 'si': Short Interest
Returns
... | 53,457 |
def with_setup_factory(setup_funcs=(), teardown_funcs=(),
post_initialize=()):
"""Create different kinds of `@with_setup` decorators
to properly initialize and teardown things necessary to run test functions
`setup_funcs` - a list of functions that do things before a test
`teardo... | 53,458 |
def set_site_title(new_name: str, mode: int=0)->None:
"""设置 获取后台标题名称 注释见set_site_header"""
alias_paths = get_all_py_path_by_alias(env.getAdminAlias())
if 2 == mode:
for _ in alias_paths:
content = retools.PATT_TITLE_NAME.sub('', read_file(_))
write_file(_, content)
if 1 =... | 53,459 |
def grab_stat_entries(stat_file_name,name):
""" stat_file_name: .stat.h5 file name, name: ex. gofr """
stat_file = h5py.File(stat_file_name)
data = []
# find entry and extract data
for estimator in stat_file.keys():
if estimator != name:
continue
# end if
ent... | 53,460 |
def parse_chunksize(size):
"""Parse chunksize argument"""
match = re.fullmatch(r"(\d+)([KMGT]B)?", size)
if match is None:
raise argparse.ArgumentTypeError(
"invalid size value: '{}'".format(size)
)
num, suffix = match.groups("")
return int(num) * (
{
... | 53,461 |
def exception_handler(exc, context):
"""
自定义异常处理
"""
# 调用drf框架原生的异常处理方法
response = drf_exception_handler(exc, context)
if response is None:
view = context['view']
if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
# 数据库异常
logger.error('[%s]... | 53,462 |
def can_view_email(user, obj=None):
"""
View staff emails or your own.
"""
return obj.is_staff or obj == user | 53,463 |
def calculateMatchValueWithRanges(incompleteObject, knownObject):
"""Calculate an integer match value, scoring +1 for each match"""
matchvalue = 0
for catkey, catval in incompleteObject.items():
if (catkey == 'cats' or catkey=='trees'):
if catval > knownObject[catkey]:
ma... | 53,464 |
def relativistic_waveshift(dv, units='km/s'):
"""
Relativistic offset in wavelength
default is dv in km/s
:param dv: float or numpy array, the dv values
:param units: string or astropy units, the units of dv
:return:
"""
# get c in correct units
# noinspection PyUnresolvedReferences
... | 53,465 |
def test_aliases(test_seqrepo_access):
"""Test that aliases method works correctly"""
expected = (["ga4gh:SQ.ijXOSP3XSsuLWZhXQ7_TJ5JXu4RJO6VT"], None)
resp = test_seqrepo_access.aliases("NM_152263.3")
assert len(resp[0]) > 0
assert resp[1] is None
assert expected[0][0] in resp[0]
resp = tes... | 53,466 |
def divisors(integer):
"""
Create a function named divisors/Divisors that takes an integer n > 1 and returns an array with all of the integer's
divisors(except for 1 and the number itself), from smallest to largest. If the number is prime return the string
'(integer) is prime' (null in C#) (use Either S... | 53,467 |
def firewall(visible, hidden):
"""
NOT IMPLEMENTED YET
turn visible into ON
turn hidden into OFF
FIRST PARAM shall be state to set firewall to
SECOND PARAM shall be the challenge to generate a firewall rule for
"""
rules = os.popen('gcloud compute firewall-rules --format=json li... | 53,468 |
def hex_to_binary_str(pdq_hex):
"""
Convert a hexadecimal string to a binary string. Requires input string to be length BITS_IN_PDQ / 4.
"""
assert len(pdq_hex) == BITS_IN_PDQ / 4
# padding to 4 bindigits each hexdigit
result = "".join(bin(int(c, 16))[2:].zfill(4) for c in pdq_hex)
assert le... | 53,469 |
def hinge_loss(psample, qsample):
"""Point-wise hinge loss."""
loss = tf.nn.relu(1.0 - psample) + tf.nn.relu(1.0 + qsample)
return loss | 53,470 |
def test_get_structure_sequence_alignment(package, resource, sequence, expected_alignment):
"""Compare results to expected sequence alignment."""
with resources.path(package, resource) as path:
structure = read_molecules(str(path))[0]
structure = remove_non_protein(structure, remove_water=Tr... | 53,471 |
def l_spin(pdgid):
"""
Returns the orbital angular momentum L as 2L+1.
Notes
-----
- This is valid for mesons only. None is returned otherwise.
- Mesons with PDGIDs of the kind 9XXXXXX (N=9) are not experimentally well-known particles
and None is returned too.
"""
value = L(pdgid)... | 53,472 |
def test_all_ages_positive():
"""Only demographic medians are ages"""
median_cols = [c for c in local_loader.aggregated.columns if c[-5:] == "median"]
assert (local_loader.aggregated[median_cols].min() > 0).all() | 53,473 |
def with_metaclass(meta: type, *bases) -> type:
"""Create a base class with a metaclass."""
# This requires a bit of explanation: the basic idea is to make a dummy
# metaclass for one level of class instantiation that replaces itself with
# the actual metaclass.
class metaclass(meta): # type: ... | 53,474 |
def create_dir(
dir_name: str,
incremental: bool,
abort_if_exists: bool = False,
ask_to_delete: bool = False,
) -> None:
"""
Create a directory `dir_name` if it doesn't exist.
:param incremental: if False then the directory is deleted and
re-created, otherwise it skips
:param ab... | 53,475 |
def mod(a: protocols.SupportsMod[A, B], b: A) -> B:
"""
Return `a % b`, for _a_ and _b_.
Example:
>>> mod(2)(3)
2
Args:
a: left element of % expression
b: right element of % expression
Return:
a modulo b
"""
return a % b | 53,476 |
def _append_backward_ops_(block,
ops,
target_block,
no_grad_dict,
grad_to_var,
callbacks=None,
input_grad_names_set=None):
"""
Create all grad ops, and inse... | 53,477 |
def header_pass(block):
"""
Check each block for potential header, if found, split (or extract) the given block into a header.
Parameters
----------
block : Block
A block to split or extract
Returns
-------
list
A list of blocks and/or header
"""
# TODO: Add lo... | 53,478 |
def ParseNetworks(value, project, version):
"""Build a list of PolicyNetworks or ResponsePolicyNetworks from command line args."""
if not value:
return []
registry = api_util.GetRegistry(version)
networks = [
registry.Parse(
network_name,
collection='compute.networks',
pa... | 53,479 |
def do_something_bar():
"""
bar!
---
responses:
200:
description: Success
"""
return do_something() | 53,480 |
def login():
"""用户登录接口
eg:
{
"username": "liuli",
"password": "liuli"
}
Token Demo:
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTYyNzc1MDQ1OCwianRpIjoiNzJjZjZkYzYtZDE5NS00NGRhLTg2NWUtNmNhZmY3MTdkMjMwIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6MTU3Njc5NTY4OTAsIm5iZiI6MT... | 53,481 |
def fraction_to_word(aText, fractions):
"""Spell out fractions written with a '/'. """
import re
aText = re.sub(r"1/2", fractions[0], aText)
aText = re.sub(r"1/3", fractions[1], aText)
aText = re.sub(r"2/3", fractions[2], aText)
aText = re.sub(r"1/4", fractions[3], aText)
aText = re.sub(r"3/... | 53,482 |
def test_gym_message_instantiation():
"""Test instantiation of the gym message."""
assert GymMessage(
performative=GymMessage.Performative.ACT, action="any_action", step_id=1
)
assert GymMessage(
performative=GymMessage.Performative.PERCEPT,
observation="any_observation",
... | 53,483 |
def create_message_context_properties(message_type, message_id, source, identifier, is_cloud_event_format) -> dict:
"""Create message context properties dict from input param values."""
return {
'type': message_type,
'message_id': message_id,
'source': source,
'identifier': ident... | 53,484 |
def run_continuously(interval=1):
"""Continuously run, while executing pending jobs at each elapsed
time interval.
@return cease_continuous_run: threading.Event which can be set to
cease continuous run.
Please note that it is *intended behavior that run_continuously()
doe... | 53,485 |
def HelpIndexCards(s):
"""
Given an HTML page, yield groups (id, desc, block of text)
"""
tag_lexer = html.TagLexer(s)
pos = 0
it = html.ValidTokens(s)
while True:
try:
tok_id, end_pos = next(it)
except StopIteration:
break
if tok_id == html.StartTag:
tag_lexer.Reset(pos, e... | 53,486 |
def teardown_module(module):
"""Reset refs; specifically the default waveset."""
refs.setref() | 53,487 |
def test_no_commits_after_tag(initial_repository, project_config):
"""If there is a tag but no commits after it, fail."""
with pytest.raises(ValueError):
run(project_config, initial_repository, False) | 53,488 |
def remove_holes(mask):
"""
This method removes holes inside the the binary mask by assigning '1' to all regions
that are not reachable from the mask corners
:param mask: mask to process
:return: mask with connected components without holes
"""
height, width = mask.shape
pos... | 53,489 |
def get_search_space(max_len, channel_range, search_space=[], now=0):
"""
Recursive.
Get all configuration combinations
:param max_len: max of the depth of model
:param channel_range: list, the range of channel
:param search_space: search space
:param now: depth of model
:return:
""... | 53,490 |
def create_gtf_file(input_file, output_file):
"""Create pseudo gtf file for all probes sequences
`input_file`: A manifest csv file that contain probe information
`output_file`: A pseudo gtf file that serve for annotation
"""
print colored("Stage 3: Creating custom gtf file from manifest file ...", "... | 53,491 |
def use_resultdb():
"""Checks the luci context to determine if resultdb is configured."""
ctx_filename = os.environ.get("LUCI_CONTEXT")
if ctx_filename:
try:
with open(ctx_filename) as ctx_file:
ctx = json.load(ctx_file)
rdb = ctx.get('resultdb', {})
return rdb.get('hostname') an... | 53,492 |
def remove_observations(acyclic_graph):
"""
Remove all observations from a symplectic acyclic_graph.
"""
result = acyclic_graph.copy()
RemoveObservations().optimize_acyclic_graph(result)
return result | 53,493 |
def contours_by_Imax(data, minI_factor=8., cl_factor=1.2, num_contours=10):
"""Calculate the contours for the plot base on the maximum intensity."""
maxI = data.max()
minI = maxI / minI_factor
return [minI * cl_factor ** x for x in range(num_contours)] | 53,494 |
def test_merge_outer_multipolygon_way_2():
"""Merged outer way of multipolygon was inserted"""
data = t.cache_query(ways=[16001, 16002], deps=True)
assert data['ways']['16001']['relations'].keys() == ['16001']
assert data['ways']['16002'] == None
data = t.cache_query(relations=[16001], full=True)
... | 53,495 |
def test_default_func_nested_str():
"""
packb() default function nested str
"""
ref = Custom()
def default(obj):
return str(obj)
assert ormsgpack.packb({"a": ref}, default=default) == msgpack.packb(
{"a": str(ref)}
) | 53,496 |
def getActivityRelations(URI):
"""Returns a list of activity flows that are *input of* and *output of* the specified activity.
.. :quickref: Flows list query; Get list of flows related to a specified activity.
**Example request**:
.. sourcecode:: http
GET /v1/activities/get_rel... | 53,497 |
def test_upload_list_accessible_for_agency_coordinators(
client, huron_mdnr_sc, data_uploads
):
"""A user with the role of agency stocking coordinator should be able
to access the list of upload events, but it should only include
upload events that are associated with their lake(s) and agency.
"""
... | 53,498 |
def make_wsgi_app(root_factory, includeme, registry=None, **settings):
"""Create and return a WSGI application."""
configurator_cls = pyramid_config.Configurator
# Initialise a ``Configurator`` and apply the package configuration.
if registry:
config = configurator_cls(registry=registry)
... | 53,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.