content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def remove_app(app_name, app_path):
"""Remove an application."""
# usage: mbl-app-manager remove [-h] app_name app_path
print("Remove {} from {}".format(app_name, app_path))
command = [MBL_APP_MANAGER, "-v", "remove", app_name, app_path]
print("Executing command: {}".format(command))
return subp... | 5,333,700 |
def lcp_iscsi_vnic_add(handle, name, parent_dn, addr="derived",
admin_host_port="ANY",
admin_vcon="any", stats_policy_name="global-default",
admin_cdn_name=None, cdn_source="vnic-name",
switch_id="A", pin_to_group_name=None, vni... | 5,333,701 |
def fixture_ecomax_with_data(ecomax: EcoMAX) -> EcoMAX:
"""Return ecoMAX instance with test data."""
ecomax.product = ProductInfo(model="test_model")
ecomax.set_data(_test_data)
ecomax.set_parameters(_test_parameters)
return ecomax | 5,333,702 |
def _get_cached_setup(setup_id):
"""Load a run from the cache."""
cache_dir = config.get_cache_directory()
setup_cache_dir = os.path.join(cache_dir, "setups", str(setup_id))
try:
setup_file = os.path.join(setup_cache_dir, "description.xml")
with io.open(setup_file, encoding='utf8') as fh... | 5,333,703 |
async def request_get_stub(url: str, stub_for: str, status_code: int = 200):
"""Returns an object with stub response.
Args:
url (str): A request URL.
stub_for (str): Type of stub required.
Returns:
StubResponse: A StubResponse object.
"""
return StubResponse(stub_for=stub_f... | 5,333,704 |
def single_gpu_test(model, data_loader, rescale=True, show=False, out_dir=None):
"""Test with single GPU.
Args:
model (nn.Module): Model to be tested.
data_loader (nn.Dataloader): Pytorch data loader.
show (bool): Whether show results during infernece. Default: False.
out_dir (s... | 5,333,705 |
def get_dump_time(f):
"""
Writes the time and date of the system dump
"""
f.write('Date of environment dump: \n')
f.write(str(datetime.datetime.now())+'\n') | 5,333,706 |
def readAllCarts():
"""
This function responds to a request for /api/people
with the complete lists of people
:return: json string of list of people
"""
# Create the list of people from our data
return[CART[key] for key in sorted(CART.keys())] | 5,333,707 |
def build_encapsulated_packet(select_test_interface, ptfadapter, tor, tunnel_traffic_monitor):
"""Build the encapsulated packet sent from T1 to ToR."""
_, server_ipv4 = select_test_interface
config_facts = tor.get_running_config_facts()
try:
peer_ipv4_address = [_["address_ipv4"] for _ in config... | 5,333,708 |
def test_ternary_auto_po2():
"""Test ternary auto_po2 scale quantizer."""
np.random.seed(42)
N = 1000000
m_list = [1.0, 0.1, 0.01, 0.001]
for m in m_list:
x = np.random.uniform(-m, m, (N, 10)).astype(K.floatx())
x = K.constant(x)
quantizer_ref = ternary(alpha="auto")
quantizer = ternary(alp... | 5,333,709 |
def index():
"""
Renders the index page.
"""
return render_template("index.html") | 5,333,710 |
def get_send_idp_location():
"""Queries GPS NMEA strings from the modem and submits to a send/processing routine."""
global log
global modem
global tracking_interval
MAX_ATTEMPTS = 3
loc = Location()
log.debug("Requesting location to send")
retrieved = False
sentences = []
atte... | 5,333,711 |
def condense_colors(svg):
"""Condense colors by using hexadecimal abbreviations where possible.
Consider using an abstract, general approach instead of hard-coding.
"""
svg = re.sub('#000000', '#000', svg)
svg = re.sub('#ff0000', '#f00', svg)
svg = re.sub('#00ff00', '#0f0', svg)
svg = re.sub... | 5,333,712 |
def install_pytest_confirmation():
"""Ask if pytest should be installed"""
return f'{fg(2)} Do you want to install pytest? {attr(0)}' | 5,333,713 |
def dense_nopack(cfg, data, weight, bias=None, out_dtype=None):
"""Compute dense without packing"""
debug = True
if debug:
print("bias", bias)
print("data_dtype", data.dtype)
print("weight_dtype", weight.dtype)
print("out_dtype", out_dtype)
if out_dtype is None:
... | 5,333,714 |
def rgb(r=0, g=0, b=0, mode='RGB'):
"""
Convert **r**, **g**, **b** values to a `string`.
:param r: red part
:param g: green part
:param b: blue part
:param string mode: ``'RGB | %'``
:rtype: string
========= =============================================================
mode ... | 5,333,715 |
def plot_dist_weights_pseudomonas(
LV_id, LV_matrix, shared_genes, num_genes, gene_id_mapping, out_filename
):
"""
This function creates a distribution of weights for selected
`LV_id`. This allows us to explore the contribution of genes
to this LV.
Here we are looking at only those HW genes ide... | 5,333,716 |
def load_csv_translations(fname, pfx=''):
"""
Load translations from a tab-delimited file. Add prefix
to the keys. Return a dictionary.
"""
translations = {}
with open(fname, 'r', encoding='utf-8-sig') as fIn:
for line in fIn:
line = line.strip('\r\n ')
i... | 5,333,717 |
def compute_bleu_rouge(pred_dict, ref_dict, bleu_order=4):
"""
Compute bleu and rouge scores.
"""
assert set(pred_dict.keys()) == set(ref_dict.keys()), \
"missing keys: {}".format(set(ref_dict.keys()) - set(pred_dict.keys()))
scores = {}
bleu_scores, _ = Bleu(bleu_order).compute_score(re... | 5,333,718 |
def create_simulated_data(mf_simulator, data_dir, n_sample=1.):
"""
Create FITS-files with simulated data.
:param mf_simulator:
:param data_dir:
:param n_sample:
"""
# Mapping from frequencies to FITS file names
fnames_dict = dict()
os.chdir(data_dir)
for freq in mf_simulator.fre... | 5,333,719 |
def check_upload_details(study_id=None, patient_id=None):
""" Get patient data upload details """
participant_set = Participant.objects.filter(patient_id=patient_id)
if not participant_set.exists() or str(participant_set.values_list('study', flat=True).get()) != study_id:
Response('Error: failed... | 5,333,720 |
def write(project_id, content):
"""Write project info"""
open(f'{files_path}/{project_id}.json', 'w').write(json.dumps(content)) | 5,333,721 |
def test_run_external_command_success(tmp_path):
"""
Output can be captured from a successful process.
"""
script = tmp_path / 'script.ps1'
script.write_text(_cmd_success)
p = run_external_command(('powershell', '-executionpolicy', 'Bypass', '-File', str(script)))
assert p.returncode == 0
... | 5,333,722 |
def crc32c_rev(name):
"""Compute the reversed CRC32C of the given function name"""
value = 0
for char in name:
value ^= ord(char)
for _ in range(8):
carry = value & 1
value = value >> 1
if carry:
value ^= CRC32_REV_POLYNOM
return value | 5,333,723 |
def sils_cut(T,f,c,d,h):
"""solve_sils -- solve the lot sizing problem with cutting planes
- start with a relaxed model
- add cuts until there are no fractional setup variables
Parameters:
- T: number of periods
- P: set of products
- f[t]: set-up costs (on period t)
... | 5,333,724 |
def progressive_fixed_point(func, start, init_disc, final_disc, ratio=2):
"""Progressive fixed point calculation"""
while init_disc <= final_disc * ratio:
start = fixedpoint.fixed_point(func, start, disc=init_disc)
init_disc *= ratio
return start | 5,333,725 |
async def create_new_game(redis: Redis = Depends(redis.wrapper.get)):
"""Create a new game with an unique ID."""
game = get_new_game()
handle_score(game)
game_dict = game_to_dict(game)
game_id = token_urlsafe(32)
await redis.set(game_id, json.dumps(game_dict))
return GameState(gameId=game_id... | 5,333,726 |
def _write_reaction_lines(reactions, species_delimiter, reaction_delimiter,
include_TS, stoich_format, act_method_name,
ads_act_method, act_unit, float_format,
column_delimiter, sden_operation,
**kwargs):
"""Writ... | 5,333,727 |
def test_apijson_get():
"""
>>> application = make_simple_application(project_dir='.')
>>> handler = application.handler()
>>> #bad json
>>> data ='''{
... ,,,
... }'''
>>> r = handler.post('/apijson/get', data=data, pre_call=pre_call_as("admin"), middlewares=[])
>>> d = json_loads(... | 5,333,728 |
def post_input_to_user_feedback(context, is_valid, endpoint, token):
"""Send feedback to user feedback endpoint."""
use_token = parse_token_clause(token)
api_url = urljoin(context.coreapi_url, endpoint)
data = generate_data_for_user_feedback(is_valid)
if use_token:
response = requests.post(a... | 5,333,729 |
def refines_constraints(storage, constraints):
"""
Determines whether with the storage as basis for the substitution map there is a substitution that can be performed
on the constraints, therefore refining them.
:param storage: The storage basis for the substitution map
:param constraints: The const... | 5,333,730 |
def dot_fp(x, y):
"""Dot products for consistent scalars, vectors, and matrices.
Possible combinations for x, y:
scal, scal
scal, vec
scal, mat
vec, scal
mat, scal
vec, vec (same length)
mat, vec (n_column of mat == length of vec)
Warning: No broadca... | 5,333,731 |
def add_one(num: int) -> int:
"""Increment arg by one."""
return num + 1 | 5,333,732 |
def normalize(data, train_split):
""" Get the standard score of the data.
:param data: data set
:param train_split: number of training samples
:return: normalized data, mean, std
"""
mean = data[:train_split].mean(axis=0)
std = data[:train_split].std(axis=0)
return (data - mean) / std,... | 5,333,733 |
def test_log_file():
"""
test the log content written in log file
"""
_rm_env_config()
file_path = '/tmp/log/mindspore_test'
os.environ['GLOG_v'] = '2'
os.environ['GLOG_logtostderr'] = '0'
os.environ['GLOG_log_dir'] = file_path
if os.path.exists(file_path):
shutil.rmtree(file... | 5,333,734 |
def test_process_one_book_and_return(csv_one_book_plus_empty_line, json_empty, results_path):
""" Process and generate data for one book. """
# GIVEN a CVS file with just one book, AN EMPTY LINE at the end, and emtpy complement file.
source_file = csv_one_book_plus_empty_line
complement_file = json_empty
... | 5,333,735 |
def lemma(name_synsets):
"""
This function return lemma object given the name.
.. note::
Support only English language (*eng*).
:param str name_synsets: name of the synset
:return: lemma object with the given name
:rtype: :class:`Lemma`
:Example:
... | 5,333,736 |
def export_cookies(domain, cookies, savelist=None, sp_domain=None):
"""
Export cookies used for remembered device/other non-session use
as list of Cookie objects. Only looks in jar matching host name.
Args:
domain (str) - Domain to select cookies from
cookies (requests.cookies.Requests... | 5,333,737 |
def test_subscribe(class_2_test):
"""
Test subscribe method : original test was written by by Zhen Wang
Source : https://github.com/nehz/pubsub/blob/master/tests.py
"""
# Get an instance of PubSub class
communicator = class_2_test()
channel = "test"
# The Listener subscribes to the ch... | 5,333,738 |
def adaptive_crossover(parents: Tuple[AbstractSolution, AbstractSolution],
variables_number: int,
crossover_pattern: int) -> ChildrenValuesTyping:
"""
Adaptive crossover function.
Crossover is performed according to a pattern that determines which gene (decisio... | 5,333,739 |
def get_type_dict(kb_path, dstc2=False):
"""
Specifically, we augment the vocabulary with some special words, one for each of the KB entity types
For each type, the corresponding type word is added to the candidate representation if a word is found that appears
1) as a KB entity of that type,
""... | 5,333,740 |
def check_students(students):
""" Make sure we have requisite fields for each student. """
for s in students:
if 'github_repo' not in s:
print(' missing github_repo for %s' % str(s))
for k, v in s.items():
s[k] = v.strip() if v else None | 5,333,741 |
def validate_export(error_writer,project, sm):
"""
Save error report, project properties, composites, and donors
:param sm: scenario model
"""
errorList = sm.validate()
name = os.path.basename(project)
graph_rules.processProjectProperties(sm)
sm.save()
for err in errorList:
e... | 5,333,742 |
def parse_time(duration: str, minimum: int = None, maximum: int = None, error_on_exceeded: bool = True) -> int:
"""Function that parses time in a NhNmNs format. Supports weeks, days, hours, minutes and seconds, positive and
negative amounts and max values. Minimum and maximum values can be set (in seconds), and... | 5,333,743 |
def injectRawKeyboardInput(isPress, code, isExtended):
"""Inject raw input from a system keyboard that is not handled natively by Windows.
For example, this might be used for input from a QWERTY keyboard on a braille display.
NVDA will treat the key as if it had been pressed on a normal system keyboard.
If it i... | 5,333,744 |
def correl_align(s_orig, align_phases=False,tol=1e-4,indirect_dim='indirect',
fig_title='correlation alignment',signal_pathway = {'ph1':0,'ph2':1},
shift_bounds=False, avg_dim = None, max_shift = 100., sigma=20.,direct='t2',fl=None):
"""
Align transients collected with chunked phase cycling dim... | 5,333,745 |
def get_fragment_mz_dict(pep, fragments, mod=None):
"""
:param pep:
:param fragments:
:param mod:
:return:
"""
mz_dict = dict()
for each_fragment in fragments:
frag_type, frag_num, frag_charge = rapid_kit.split_fragment_name(each_fragment)
mz_dict[each_fragment] = calc_fr... | 5,333,746 |
def remove_filters_from_files(
catfile,
physgrid=None,
obsgrid=None,
outbase=None,
physgrid_outfile=None,
rm_filters=None,
beast_filt=None,
):
"""
Remove filters from catalog, physics grid, and/or obsmodel grid. This has
two primary use cases:
1. When making simulated obser... | 5,333,747 |
def merge_dicts(iphonecontrollers, ipadcontrollers):
"""Add ipad controllers to the iphone controllers dict, but never overwrite a custom controller with None!"""
all_controllers = iphonecontrollers.copy()
for identifier, customclass in ipadcontrollers.items():
if all_controllers.get(identifier) is ... | 5,333,748 |
def SaveResampled(FileName):
"""Save Resampled results in csv
Input:
- FileName: Name of output File
Save the resampled source as csv
Save all time steps
"""
resampled = FindSource('Resampled')
# save data
SaveData(FileName, proxy=resampled, WriteTimeSteps=1,Precision=8,UseScien... | 5,333,749 |
def p_while(p):
"""
while : WHILE ciclo_uno OP expresion CP ciclo_dos bloque ciclo_tres
"""
p[0] = [p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]] | 5,333,750 |
def test_pre_tag_newlines():
"""http://code.pediapress.com/wiki/ticket/79"""
_check_text_in_pretag("\ntext1\ntext2\n\ntext3") | 5,333,751 |
def perimRect(length,width):
"""
Compute perimiter of rectangle
>>> perimRect(2,3)
10
>>> perimRect(4, 2.5)
13.0
>>> perimRect(3, 3)
12
>>>
"""
return 2*(length+width) | 5,333,752 |
def rename_events_in_subjects(subjects, events):
"""
Goes through all subject events and renames the datetime to the event name in the corresponding
index of the events list. Uses zip so if subject information runs out before the events
get used up it's fine.
However we need to make sure we dont' g... | 5,333,753 |
def main():
"""Run the app."""
app.run(host='0.0.0.0', port=8000, debug=True) | 5,333,754 |
def h_search(endpoint, query, sort, order, per_page, page):
"""
- Executes search.search and returns a dictionary
of results
`return {headers,status_code,items}`
"""
current_search_params = {
"query": query,
"sort": sort,
"order": order,
"per_page": per_page,
... | 5,333,755 |
def async_wrapper(fn):
"""
Wraps an async function or generator with a function which runs that generator on the thread's
event loop. The wrapped function requires an 'xloil_thread_context' argument which provides a
callback object to return a result. xlOil will pass this object automatically to functi... | 5,333,756 |
def add_deprecated_species_alias(registry, ftype, alias_species, species, suffix):
"""
Add a deprecated species alias field.
"""
unit_system = registry.ds.unit_system
if suffix == "fraction":
my_units = ""
else:
my_units = unit_system[suffix]
def _dep_field(field, data):
... | 5,333,757 |
def docker_client():
"""
Return the current docker client in a manner that works with both the
docker-py and docker modules.
"""
try:
client = docker.from_env(version='auto', timeout=3600)
except TypeError:
# On older versions of docker-py (such as 1.9), version isn't a
#... | 5,333,758 |
def fatal(msg, *args, **kwargs):
"""Logs thE level FATAL logging, it logs only FATAL.
Args:
msg: the message to log
"""
_logger.fatal(_log_prefix() + msg, *args, **kwargs) | 5,333,759 |
def bulk_generate_metadata(html_page: str,
description: dict=None,
enable_two_ravens_profiler=False
) -> typing.List[typing.List[dict]]:
"""
:param html_page:
:param description:
:param es_index:
:return:
"""
s... | 5,333,760 |
def add_cals():
"""
Add nutrients from products.
"""
if 'username' in session:
user_obj = users_db.get(escape(session['username']))
calc = Calculator(user_obj.weight, user_obj.height,
user_obj.age, user_obj.gender, user_obj.activity)
food = request.form.... | 5,333,761 |
def parse(q):
"""http://en.wikipedia.org/wiki/Shunting-yard_algorithm"""
def _merge(output, scache, pos):
if scache:
s = " ".join(scache)
output.append((s, TOKEN_VALUE, pos - len(s)))
del scache[:]
try:
tokens = lex(q)
except Exception as e:
... | 5,333,762 |
def CheckChangeOnUpload(input_api, output_api):
"""Presubmit checks for the change on upload.
The following are the presubmit checks:
* Check change has one and only one EOL.
"""
results = []
results.extend(_CommonChecks(input_api, output_api))
# Run on upload, not commit, since the presubmit bot apparen... | 5,333,763 |
def compute_compression_rate(file: str, zip_archive) -> float:
"""Compute the compression rate of two files.
More info: https://en.m.wikipedia.org/wiki/Data_compression_ratio
:param file: the uncompressed file.
:param zip_archive the same file but compressed.
:returns the compre... | 5,333,764 |
def set_idc_func_ex(name, fp=None, args=(), flags=0):
"""
Extends the IDC language by exposing a new IDC function that is backed up by a Python function
This function also unregisters the IDC function if 'fp' was passed as None
@param name: IDC function name to expose
@param fp: Python callable tha... | 5,333,765 |
def get_hidden_plugins() -> Dict[str, str]:
"""
Get the dictionary of hidden plugins and versions.
:return: dict of hidden plugins and their versions
"""
hidden_plugins = get_cache('cache/hidden-plugins.json')
if hidden_plugins:
return hidden_plugins
else:
return {} | 5,333,766 |
def wait_for_re_doc(coll, key, timeout=180):
"""Fetch a doc with the RE API, waiting for it to become available with a 30s timeout."""
start_time = time.time()
while True:
print(f'Waiting for doc {coll}/{key}')
results = re_client.get_doc(coll, key)
if results['count'] > 0:
... | 5,333,767 |
def split_year_from_week(data: pd.DataFrame) -> pd.DataFrame:
"""
Because we have used the partition key as the NFL year, the year/week need to be put into the appropriate columns
"""
data[[Stats.YEAR, Stats.NFL_WEEK]] = data[Stats.YEAR].str.split("/", expand=True)
data[Stats.NFL_WEEK] = data[Stats.... | 5,333,768 |
def normalize_index(idx, shape):
"""Normalize slicing indexes
1. Replaces ellipses with many full slices
2. Adds full slices to end of index
3. Checks bounding conditions
4. Replace multidimensional numpy arrays with dask arrays
5. Replaces numpy arrays with lists
6. Posify's integers... | 5,333,769 |
def data2results(data, rr, nin=None, nout=None, ngoodrank=None, fullcalccurrent=None, fullcalc=None, selectionmaxn=None):
""" Convert analysis data to results structure """
print('do not use this function!!!!')
raise | 5,333,770 |
def relu(data):
"""Rectified linear unit.
.. math::
out = max(x, 0)
Parameters
----------
data : relay.Expr
The input data
Returns
-------
result : relay.Expr
The computed result.
"""
return _make.relu(data) | 5,333,771 |
def levsim(args):
"""Returns the Levenshtein similarity between two terms."""
term_i, term_j, j = args
return (MLEV_ALPHA * (1 - Levenshtein.distance(term_i, term_j) \
/ max(len(term_i), len(term_j)))**MLEV_BETA, term_j, j) | 5,333,772 |
def some_payloaded_data(length=1000000, size=32, var=0):
"""Generate random array with named tuples, containing random string as payload"""
for datum in some_simple_data(length):
yield DataWithPayload(datum, some_payload(size, var)) | 5,333,773 |
def retrieve_job_logs(job_id):
"""Retrieve job's logs.
:param job_id: UUID which identifies the job.
:returns: Job's logs.
"""
return JOB_DB[job_id].get('log') | 5,333,774 |
def parse_argv():
"""Parses arguments for use with the test launcher.
Arguments are:
1. Working directory.
2. Test runner, `pytest` or `nose`
3. debugSecret
4. debugPort
5. Debugger search path
6. Mixed-mode debugging (non-empty string to enable, empty string to disable)
7. Enable co... | 5,333,775 |
def play_collection(playlist_id, start_album_id, shuffle_albums: bool, device_id=None):
"""This function attempts to mimic the ability to play songs
within the context of a playlist.
Playback will start from the first track of `start_album_id`
If shuffle_albums is set to true then the list order will ... | 5,333,776 |
def _normalize_format(fmt):
"""Return normalized format string, is_compound format."""
if _is_string_or_bytes(fmt):
return _compound_format(sorted(
_factor_format(fmt.lower()))), ',' in fmt
else:
return _compound_format(sorted([_normalize_format(f)[0] for f in... | 5,333,777 |
def get_cevioai_version() -> str:
"""
CeVIO AIのバージョンを取得します。
Returns
-------
str
CeVIO AIのバージョン
"""
_check_cevioai_status()
return _service_control.host_version | 5,333,778 |
def get_all_revisions_available(link):
""" List all the revisions availabel for a particular link
"""
svn_username = current_user.svn_username
svn_password = current_user.svn_password
link = link.replace("dllohsr222","10.133.0.222")
args = ["svn", "log",
link,"--xml",
"--u... | 5,333,779 |
def get_explicit_kwargs_OD(f_params, bound_args, kwargs) -> OrderedDict:
"""For some call to a function f, args *arg and **kwargs,
:param f_params: inspect.signature(f).parameters
:param bound_args: inspect.signature(f).bind(*args, **kwargs)
:return: OrderedDict of the (kwd, kwargs[kwd])
... | 5,333,780 |
def generate_variable_formants_point_function(corpus_context, min_formants, max_formants):
"""Generates a function used to call Praat to measure formants and bandwidths with variable num_formants.
Parameters
----------
corpus_context : :class:`~polyglot.corpus.context.CorpusContext`
The CorpusC... | 5,333,781 |
def handle_player_dead_keys(key):
"""
The set of keys for a dead player.
Can only see the inventory and toggle fullscreen.
"""
key_char = chr(key.c) if key.vk == libtcod.KEY_CHAR else ""
if key_char == 'i':
return {'show_inventory': True}
if key.vk == libtcod.KEY_ENTER and key.la... | 5,333,782 |
def safe_std(values):
"""Remove zero std values for ones."""
return np.array([val if val != 0.0 else 1.0 for val in values]) | 5,333,783 |
def skinPercent(q=1,ib="float",nrm=1,prw="float",r=1,rtd=1,t="string",tmw="string",tv="[string, float]",v=1,zri=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/skinPercent.html
-----------------------------------------
skinPercent is undoable, queryable, and NOT editable.
This... | 5,333,784 |
def _munge_source_data(data_source=settings.NETDEVICES_SOURCE):
"""
Read the source data in the specified format, parse it, and return a
:param data_source:
Absolute path to source data file
"""
log.msg('LOADING FROM: ', data_source)
kwargs = parse_url(data_source)
path = kwargs.pop... | 5,333,785 |
def copy_global_to_local_blacklist(excluded_testcase=None):
"""Copies contents of global blacklist into local blacklist file, excluding
a particular testcase (if any)."""
lsan_suppressions_path = get_local_blacklist_file_path()
excluded_function_name = (
get_leak_function_for_blacklist(excluded_testcase... | 5,333,786 |
def create_app(settings_override=None):
"""
Create a flask application using the app factory pattern
:return: Flask app
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config.settings')
app.config.from_pyfile('settings.py', silent=True)
if setting... | 5,333,787 |
def convex_hull(ps: Polygon) -> Polygon:
"""Andrew's algorithm"""
def construct(limit, start, stop, step=1):
for i in range(start, stop, step):
while len(res) > limit and cross(res[-1] - res[-2], s_ps[i] - res[-1]) < 0:
res.pop()
res.append(s_ps[i])
assert l... | 5,333,788 |
def get_api_file_url(file_id):
"""Get BaseSpace API file URL."""
api_url = get_api_url()
return f'{api_url}/files/{file_id}' | 5,333,789 |
def Tr(*content, **attrs):
"""
Wrapper for tr tag
>>> Tr().render()
'<tr></tr>'
"""
return KWElement('tr', *content, **attrs) | 5,333,790 |
def _read_storm_locations_one_time(
top_tracking_dir_name, valid_time_unix_sec, desired_full_id_strings):
"""Reads storm locations at one time.
K = number of storm objects desired
:param top_tracking_dir_name: See documentation at top of file.
:param valid_time_unix_sec: Valid time.
:param... | 5,333,791 |
def ja_il(il, instr):
"""
Returns llil expression to goto target of instruction
:param il: llil function to generate expression with
:param instr: instruction to pull jump target from
:return: llil expression to goto target of instr
"""
label = valid_label(il, instr.ja_target)
return il.... | 5,333,792 |
def create_plot_durations_v_nrows(source, x_axis_type='log', x_range=(1, 10**5),
y_axis_type='log', y_range=(0.001, 10**3)):
"""
Create a Bokeh plot (Figure) of do_query_dur and stream_to_file_dur versus num_rows.
num_rows is the number of result rows from the query.
P... | 5,333,793 |
def listen_and_transcribe(length=0, silence_len=0.5):
"""
Listen with the given parameters, but simulaneously stream the audio to the
Aurora API, transcribe, and return a Text object. This reduces latency if
you already know you want to convert the speech to text.
:param length the length of time (seconds) ... | 5,333,794 |
def load_test_dataframes(feature_folder, **kwargs):
"""
Convenience function for loading unlabeled test dataframes. Does not add a 'Preictal' column.
:param feature_folder: The folder to load the feature data from.
:param kwargs: keyword arguments to use for loading the features.
:return: A DataFra... | 5,333,795 |
def _match_grid(grid):
"""
given a grid, create the other side to obey:
one p1 black must be a p2 green, tan, and black; and vice versa
"""
l = [""] * 25
color_dict = {
"b": [i for i in range(25) if grid[i] == "b"],
"t": [i for i in range(25) if grid[i] == "t"],... | 5,333,796 |
def extract_frames(subject_action):
"""
This function is to save video frames and save their paths along with
2D/3D keypoints and bounding box coordinates in a .npz file.
Can be used for PEBRT.
"""
tabs = {}
for s in subject_action.keys():
for action in subject_action[s]:
... | 5,333,797 |
def decorate(subplot=None, **params):
"""Decorate graph using parameters
Args:
subplot (matplotlib.axes._subplots.AxesSubplot)
**params: <deco_param_descr>
"""
subplot = plt.gca() if subplot is None else subplot
params, font_params = splitparams_(params)
if params.xlabel:
... | 5,333,798 |
def add_vary_callback_if_cookie(*varies):
"""Add vary: cookie header to all session responses.
Prevent downstream web serves to accidentally cache session set-cookie reponses,
potentially resulting to session leakage.
"""
def inner(request, response):
vary = set(response.vary if response.va... | 5,333,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.