content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def walk(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
"""Returns the Walk task."""
# physics = Physics.from_xml_string(*get_model_and_assets())
physics = SuperballContactSimulation("tt_ntrt_on_ground.xml")
task = PlanarSuperball(move_speed=_WALK_SPEED, random=random)
environment_kwar... | 5,347,400 |
def confound_isolating_sampling(y, z, random_seed=None, min_sample_size=None,
n_remove=None):
"""
Sampling method based on the 'Confound isolating cross-validation'
technique.
# TODO Reference to the paper
:param y: numpy.array, shape (n_samples), target
:param z... | 5,347,401 |
def encode_direct(list_a: list):
"""Problem 13: Run-length encoding of a list (direct solution).
Parameters
----------
list_a : list
The input list
Returns
-------
list of list
An length-encoded list
Raises
------
TypeError
If the given argument is not ... | 5,347,402 |
def main():
"""
This main function is used to run "Orteil Idle Game Maker Code Generator" tool.
:return: None
"""
print("Welcome to 'Orteil Idle Game Maker Code Generator' tool by GlobalCreativeCommunityFounder.")
print("This tool will quickly generate Orteil Idle Game Maker code to shor... | 5,347,403 |
def handler500(request):
"""
HTTP Error 500 Internal Server Error
"""
return HttpResponse('<h1>HTTP Error 500 Internal server error</h1>', {}) | 5,347,404 |
def increase_line_complexity(linestring, n_points):
"""
linestring (shapely.geometry.linestring.LineString):
n_points (int): target number of points
"""
# or to get the distances closest to the desired one:
# n = round(line.length / desired_distance_delta)
distances = np.linspace(0, linestr... | 5,347,405 |
def get_topic_prevelance(doc_topic_matrix, num_topics, total_num_docs):
"""Input: doc_topic_matrix, a numpy nd array where each row represents a doc, and each collumn is the assocication
of the doc with a topic. Num_topics and integer holding the number of topics. Total_num_docs is an int holding the
number of docs... | 5,347,406 |
async def drones_byDroneId_delete(request, droneId):
"""
Remove a drone from the fleet
It is handler for DELETE /drones/<droneId>
"""
return handlers.drones_byDroneId_deleteHandler(request, droneId) | 5,347,407 |
def generate_sql_integration_data(sql_test_backends):
"""Populate test data for SQL backends for integration testing."""
sql_schema_info = get_sqlalchemy_schema_info()
vertex_values, edge_values, uuid_to_class_name = get_integration_data()
# Represent all edges as foreign keys
uuid_to_foreign_key_v... | 5,347,408 |
def p4( command ):
"""
Run a perforce command line instance and marshal the
result as a list of dictionaries.
"""
commandline = 'p4 %s -G %s' % (P4_PORT_AND_USER, command)
logging.debug( '%s' % commandline )
stream = os.popen( commandline, 'rb' )
entries = []
try:
while 1:
entry = marshal.lo... | 5,347,409 |
def restart_apps_or_services(app_or_service_names=None):
"""Restart any containers associated with Dusty, or associated with
the provided app_or_service_names."""
if app_or_service_names:
log_to_client("Restarting the following apps or services: {}".format(', '.join(app_or_service_names)))
else:... | 5,347,410 |
def install_script_job(function):
""" Adds a script job for file read and scene opened
"""
kill_script_job(function.__name__)
cmds.scriptJob(event=["NewSceneOpened", function])
cmds.scriptJob(conditionTrue=["readingFile", function]) | 5,347,411 |
def measure_shear_metacal_plus_mof(res, *, s2n_cut, t_ratio_cut):
"""Measure the shear parameters for metacal+MOF.
NOTE: Returns None if nothing can be measured.
Parameters
----------
res : dict
The metacal results.
s2n_cut : float
The cut on `wmom_s2n`. Typically 10.
t_rat... | 5,347,412 |
def software_detail(request, context, task_id, vm_id):
""" render the detail of the user page: vm-stats, softwares, and runs """
softwares = model.get_software(task_id, vm_id)
runs = model.get_vm_runs_by_task(task_id, vm_id)
datasets = model.get_datasets_by_task(task_id)
# Construct a dictionary th... | 5,347,413 |
def test_quota_namespace_count():
"""
Lets make sure we can violate the number of names in a directory limitation
"""
cluster = mini_cluster.shared_cluster()
try:
fs = cluster.fs
fs.setuser(cluster.superuser)
if fs.exists('/tmp/foo2'):
fs.rmtree('/tmp/foo2')
fs.mkdir("/tmp/foo2", 0777)
... | 5,347,414 |
def compile_error_curves(dfs, window_size = 60):
"""
takes a list of timeseries dfs and
returns a DataFrame in which each column is
the monatonically decreasing version of % error
for one of the dfs in the list.
usefull for summarizing how a bunch of timeseries converge on
some value after ... | 5,347,415 |
def _get_cluster_medoids(idx_interval: np.ndarray, labels: np.ndarray,
pdist: np.ndarray, order_map: np.ndarray) \
-> np.ndarray:
"""
Get the indexes of the cluster medoids.
Parameters
----------
idx_interval : np.ndarray
Embedding indexes.
labels : np.n... | 5,347,416 |
def printHexArray(hex_list):
"""
打印十六进制数组的数组
hex_list: 一个十六进制数组的数组
"""
for item in hex_list:
print convertBytesToHexStr(item) | 5,347,417 |
def cli(package_name):
"""Shows all releases for a package and some info about it.
PACKAGE_NAME Name of the package to fetch info about.
"""
main.main(package_name=package_name) | 5,347,418 |
def perform_authorization_code_flow():
"""
Performs spotify's Authorization Code Flow to retrive an API token.
This uses the OAuth 2.0 protocol, which requires user input and consent.
Output
______
api_key: str
a user's api key with prompted permissions
refresh_token:... | 5,347,419 |
def fetch_papers(db_manager: DBManager,
base_url: str,
list_url: str,
conf_id: str,
conf_sub_id: str,
conf_name: str) -> None:
""" Fetches the data of all the papers found at list_url and add them to
the database, if the data i... | 5,347,420 |
def calculate_empirical_cdf(variable_values):
"""Calculate numerical cumulative distribution function.
Output tuple can be used to plot empirical cdf of input variable.
Parameters
----------
variable_values : numpy array
Values of a given variable.
Returns
-------
numpy array... | 5,347,421 |
def import_reference(filename):
"""
Imports object from reference node filename
:param filename: str
"""
return maya.cmds.file(filename, importReference=True) | 5,347,422 |
def product_mapping(name, setup, cleanup=True):
"""Obtain the kernel mapping.
:return: Kernel Mapping
:rtype: str
"""
kernel_list_file = (
setup.working_directory
+ os.sep
+ f"{setup.mission_acronym}_{setup.run_type}_"
f"{int(setup.release):02d}.ker... | 5,347,423 |
def test_connect():
"""
test disconnecing and then reconnecting
"""
cam = CCDCam("localhost", 7624)
v = cam.disconnect()
assert(v is not None)
v = cam.connect()
assert(v is not None)
t = cam.temperature
assert(t == 20.0)
cam.quit() | 5,347,424 |
def override_setting(name, default=None, help=u'', category=_CATEGORY):
""" Override a setting.
"""
_attach_callback(
name,
default=default,
help=help,
category=category,
override=True
) | 5,347,425 |
def generate_example(interactive, config, riotbase):
"""Generate the code of an example application."""
group = "application"
params = load_and_check_application_params(
group, interactive, config, riotbase, in_riot_dir="examples"
)
params["application"]["type"] = "example"
output_dir ... | 5,347,426 |
def PlotExpectedGains(guess1=20000, guess2=40000):
"""Plots expected gains as a function of bid.
guess1: player1's estimate of the price of showcase 1
guess2: player2's estimate of the price of showcase 2
"""
player1, player2 = MakePlayers()
MakePlots(player1, player2)
player1.MakeBeliefs(... | 5,347,427 |
def remove_persons_with_few_joints(all_keypoints, min_total_joints=10, min_leg_joints=2, include_head=False):
"""Remove bad skeletons before sending to the tracker"""
good_keypoints = []
for keypoints in all_keypoints:
# include head point or not
total_keypoints = keypoints[5:, 1:] if not i... | 5,347,428 |
def message_has_races(message):
"""
Checks to see if a message has a race kwarg.
"""
races = get_races_from_message(message)
return len(races) > 0 and races[0] != "" | 5,347,429 |
def _find_word(input):
"""
_find_word - function to find words in the input sentence
Inputs:
- input : string
Input sentence
Outputs:
- outputs : list
List of words
"""
# lower case
input = input.lower()
# split by whitespace
input = re.split(pattern = '[\s]+', string = input)
# find words in WORD... | 5,347,430 |
def logp1_r_squared_linreg(y_true, y_pred):
"""Compute custom logp1 r squared ((follows the scipy linear regression implementation of R2).
Parameters
----------
y_true
y_true.
y_pred
y_pred.
Returns
-------
r2
"""
y_pred, _ = tf.split(y_pred, num_or_size_splits=... | 5,347,431 |
def to_legacy_data_type(data_type: Union[JsonDict, dt.DataType]) -> JsonDict:
"""
Convert to simple datatypes ("String", "Long", etc) instead of JSON objects,
if possible.
The frontend expects the "type" field for enums and arrays to be lowercase.
"""
if not isinstance(data_type, dt.DataType):
... | 5,347,432 |
def command_list_all_users(context, args) -> None:
"""
List all users via portal/users
"""
client = __get_service_api_client(context, args)
response = client.navigate('portal', 'users').GET()
users = response.DATA.get('UserInfoList', [])
print(f'Found {len(users)} users')
for user in use... | 5,347,433 |
def cluster_build_trees(
identity, set_name, cluster_file=None, click_loguru=None
):
"""Calculate homology clusters, MSAs, trees."""
options = click_loguru.get_global_options()
user_options = click_loguru.get_user_global_options()
parallel = user_options["parallel"]
set_path = Path(set_name)
... | 5,347,434 |
def display_dictionary(dictionary, renormalize=False, reshaping=None,
groupings=None, label_inds=False, highlighting=None,
plot_title=""):
"""
Plot each of the dictionary elements side by side
Parameters
----------
dictionary : ndarray(float32, size=(s, n) OR (s,... | 5,347,435 |
def example(a,b):
""" que onda
""" | 5,347,436 |
def rbinary_search(arr, target, left=0, right=None):
"""Recursive implementation of binary search.
:param arr: input list
:param target: search item
:param left: left most item in the search sub-array
:param right: right most item in the search sub-array
:return: index of item if found `-1` oth... | 5,347,437 |
def get_redis_posts(author: str) -> (str, str):
"""Return user's first and other post IDs
Retrieve the user's first and other post IDs from Redis,
then return them as a tuple in the form (first, extra)
:param author: The username to get posts for
:return: Tuple of the first and other post IDs
... | 5,347,438 |
def template_localtime(value, use_tz=None):
"""
Checks if value is a datetime and converts it to local time if necessary.
If use_tz is provided and is not None, that will force the value to
be converted (or not), overriding the value of settings.USE_TZ.
This function is designed for use by the tem... | 5,347,439 |
def FilesBrowse(button_text='Browse', target=(ThisRow, -1), file_types=(("ALL Files", "*.*"),), disabled=False,
initial_folder=None, tooltip=None, size=(None, None), auto_size_button=None, button_color=None,
change_submits=False, enable_events=False,
font=None, pad=Non... | 5,347,440 |
def test_operation_to_channel_matrix(channel):
"""Verifies that cirq.channel_matrix correctly computes the channel matrix."""
actual = cirq.operation_to_channel_matrix(channel)
expected = compute_channel_matrix(channel)
assert np.all(actual == expected) | 5,347,441 |
def ensure_sudo() -> str:
"""ensures user is root and SUDO_USER is in os.environ,
:returns: the real username (see real_username())
"""
# if we aren't root, or don't have access to host environment variables...
username = real_username()
uid = os.getuid() # pylint: disable=no-member
if user... | 5,347,442 |
def exibir_tarefas():
""" exibe a lista de tarefas cadastradas, com algumas formatações básicas """
for tarefa in db.get_tarefas():
# check = \u2713 é o caracter unicode que representa o concluido
check = u'\u2713' if tarefa[2] == 1 else ""
"""
os parametros passados para... | 5,347,443 |
def f2p(phrase, max_word_size=15, cutoff=3):
"""Convert a Finglish phrase to the most probable Persian phrase.
"""
results = f2p_list(phrase, max_word_size, cutoff)
return ' '.join(i[0][0] for i in results) | 5,347,444 |
def updateProf(id):
""" update prof w/ id """
r = requests.get("http://www.ratemyprofessors.com/ShowRatings.jsp?tid="+str(id))
p = Professor.query.filter_by(id=id).first()
if p:
soup = BeautifulSoup(r.text, "html.parser")
# scrape the data from the page
ratings_title = ["helpful... | 5,347,445 |
def read_sj_out_tab(filename):
"""Read an SJ.out.tab file as produced by the RNA-STAR aligner into a
pandas Dataframe.
Parameters
----------
filename : str of filename or file handle
Filename of the SJ.out.tab file you want to read in
Returns
-------
sj : pandas.DataFrame
... | 5,347,446 |
def gc_subseq(seq, k=2000):
"""
Returns GC content of non − overlapping sub− sequences of size k.
The result is a list.
"""
res = []
for i in range(0, len(seq)-k+1, k):
subseq = seq[i:i+k]
gc = calculate_gc(subseq)
res.append(gc)
return gc | 5,347,447 |
def get_links_from_page(text: str=None) -> set:
"""
extract the links from the HTML
:param text: the search term
:return: a set of links
:rtype: set
"""
links = set()
link_pattern = re.compile('img.src=.+') # todo expand this to get href's
# link_pattern = re.compile(r'href=*')
... | 5,347,448 |
def pcursor():
"""Database cursor."""
dbconn = get_dbconn("portfolio")
return dbconn.cursor() | 5,347,449 |
def base_experiment_cmd(args, rest):
"""Execute experiment function"""
if not getattr(args, 'expfunc', None):
args.command.print_help()
else:
args.expfunc(args, rest) | 5,347,450 |
def get_args_from_command_line():
"""Parse the command line arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("--HITId", type=str)
parser.add_argument("--worker_id", type=str)
args = parser.parse_args()
return args | 5,347,451 |
def truncate(f, n):
"""
Floors float to n-digits after comma.
"""
return math.floor(f * 10 ** n) / 10 ** n | 5,347,452 |
async def hacs(hass: HomeAssistant):
"""Fixture to provide a HACS object."""
hacs_obj = HacsBase()
hacs_obj.hass = hass
hacs_obj.tasks = HacsTaskManager(hacs=hacs_obj, hass=hass)
hacs_obj.validation = ValidationManager(hacs=hacs_obj, hass=hass)
hacs_obj.session = async_get_clientsession(hass)
... | 5,347,453 |
def process_simple_summary_csv(out_f, in_f, rundate):
"""Scan file and compute sums for 2 columns"""
df = panda.read_csv(in_f)
FORMATTING_FILE = "ColumnFormatting.json"
with open(FORMATTING_FILE) as json_data:
column_details = json.load(json_data)
# this dictionary will contain information ... | 5,347,454 |
def test_export_post_command_bad_command():
"""Test --post-command with bad command"""
import os.path
from osxphotos.cli import cli
runner = CliRunner()
cwd = os.getcwd()
# pylint: disable=not-context-manager
with runner.isolated_filesystem():
result = runner.invoke(
cl... | 5,347,455 |
def test_with_zip_concat():
"""
Feature: SentencePieceTokenizer
Description: test SentencePieceTokenizer with zip and concat operations
Expectation: output is equal to the expected value
"""
data = ds.TextFileDataset(VOCAB_FILE, shuffle=False)
vocab = text.SentencePieceVocab.from_dataset(dat... | 5,347,456 |
def test_inspect_auto_flats(tmp_path, save_changes):
"""Test flat channel & segment detection."""
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
plt.close('all')
bids_root = setup_bids_test_dir(tmp_path)
bids_path = _bids_path.copy().update(root=bids_root)
chann... | 5,347,457 |
def rotY(theta):
""" returns Rotation matrix such that R*v -> v', v' is rotated about y axis through theta_d.
theta is in radians.
rotY = Ry'
"""
st = math.sin(theta)
ct = math.cos(theta)
return np.matrix([[ ct, 0., st ],
[ 0., 1., 0. ],
... | 5,347,458 |
def get_core_blockdata(core_index, spltcore_index, core_bases):
"""
Get Core Offset and Length
:param core_index: Index of the Core
:param splitcore_index: Index of last core before split
:param core_bases: Array with base offset and offset after split
:return: Array with core offset and core le... | 5,347,459 |
def make_bench_verify_token(alg):
""" Return function which will generate token for particular algorithm """
privk = priv_keys[alg].get('default', priv_key)
token = jwt.generate_jwt(payload, privk, alg, timedelta(days=1))
def f(_):
""" Verify token """
pubk = pub_keys[alg].get('default',... | 5,347,460 |
def test_dag_integrity(dag_path):
"""Import DAG files and check for a valid DAG instance."""
dag_name = path.basename(dag_path)
module = _import_file(dag_name, dag_path)
# Validate if there is at least 1 DAG object in the file
dag_objects = [
var for var in vars(module).values() if isinstan... | 5,347,461 |
def test_make_package(qipkg_action, qipy_action):
""" Test Make Package """
tmpdir = qipy_action.worktree.tmpdir
qipkg_action.add_test_project("a_cpp")
qipkg_action.add_test_project("b_py")
c_pkg_proj = qipkg_action.add_test_project("c_pkg")
# ipython 5 is the last version compatible with Python... | 5,347,462 |
def status():
""" Status of the API """
return jsonify({'status': 'OK'}) | 5,347,463 |
def calc_median(input_list):
"""sort the list and return median"""
new_list = sorted(input_list)
len_list = len(new_list)
if len_list%2 == 0:
return (new_list[len_list/2-1] + new_list[len_list/2] ) / 2
else:
return new_list[len_list/2] | 5,347,464 |
def _load_eigenvalue(h5_result, log):
"""Loads a RealEigenvalue"""
class_name = _cast(h5_result.get('class_name'))
table_name = '???'
title = ''
nmodes = _cast(h5_result.get('nmodes'))
if class_name == 'RealEigenvalues':
obj = RealEigenvalues(title, table_name, nmodes=nmodes)
elif cl... | 5,347,465 |
def _GenerateBaseResourcesAllowList(base_module_rtxt_path,
base_allowlist_rtxt_path):
"""Generate a allowlist of base master resource ids.
Args:
base_module_rtxt_path: Path to base module R.txt file.
base_allowlist_rtxt_path: Path to base allowlist R.txt file.
Returns:... | 5,347,466 |
def test_two_unrelated_w_a_wout_c(clean_db, unrelated_with_trials, capsys):
"""Test two unrelated experiments with --all."""
orion.core.cli.main(['status', '--all'])
captured = capsys.readouterr().out
expected = """\
test_double_exp
===============
id status
------------... | 5,347,467 |
def finite_min_max(array_like):
""" Obtain finite (non-NaN, non-Inf) minimum and maximum of an array.
Parameters
----------
array_like : array_like
A numeric array of some kind, possibly containing NaN or Inf values.
Returns
-------
tuple
Two-valued tuple containing the fin... | 5,347,468 |
def list_extend1(n):
"""
using a list to built it up, then convert to a numpy array
"""
l = []
num_to_extend = 100
data = range(num_to_extend)
for i in xrange(n/num_to_extend):
l.extend(data)
return np.array(l) | 5,347,469 |
def ccf(tdm, tsuid_list_or_dataset, lag_max=None, tsuids_out=False, cut_ts=False):
"""
This function calculates the maximum of the cross correlation function matrix between all ts
in tsuid_list_or_dataset in a serial mode.
The result is normalized (between -1 and 1)
Cross correlation is a correlati... | 5,347,470 |
def filter_zoau_installs(zoau_installs, build_info, minimum_zoau_version):
"""Sort and filter potential ZOAU installs based on build date
and version.
Args:
zoau_installs (list[dict]): A list of found ZOAU installation paths.
build_info (list[str]): A list of build info strings
minim... | 5,347,471 |
def make_chain(node, address, privkeys, parent_txid, parent_value, n=0, parent_locking_script=None, fee=DEFAULT_FEE):
"""Build a transaction that spends parent_txid.vout[n] and produces one output with
amount = parent_value with a fee deducted.
Return tuple (CTransaction object, raw hex, nValue, scriptPubKe... | 5,347,472 |
def parse_args():
"""
Parse input arguments
Returns
-------
args : object
Parsed args
"""
h = {
"program": "Simple Baselines training",
"train_folder": "Path to training data folder.",
"batch_size": "Number of images to load per batch. Set according to your PC... | 5,347,473 |
def timestamp(date):
"""Get the timestamp of the `date`, python2/3 compatible
:param datetime.datetime date: the utc date.
:return: the timestamp of the date.
:rtype: float
"""
return (date - datetime(1970, 1, 1)).total_seconds() | 5,347,474 |
def pratt_arrow_risk_aversion(t, c, theta, **params):
"""Assume constant relative risk aversion"""
return theta / c | 5,347,475 |
def parse_content_type(content_type):
"""
Parse a content-type and its parameters into values.
RFC 2616 sec 14.17 and 3.7 are pertinent.
**Examples**::
'text/plain; charset=UTF-8' -> ('text/plain', [('charset, 'UTF-8')])
'text/plain; charset=UTF-8; level=1' ->
('text/plain'... | 5,347,476 |
def mapplot(df, var, metric, ref_short, ref_grid_stepsize=None, plot_extent=None, colormap=None, projection=None,
add_cbar=True, figsize=globals.map_figsize, dpi=globals.dpi,
**style_kwargs):
"""
Create an overview map from df using df[var] as color.
Plots a scatt... | 5,347,477 |
def generate_athena(config):
"""Generate Athena Terraform.
Args:
config (dict): The loaded config from the 'conf/' directory
Returns:
dict: Athena dict to be marshalled to JSON
"""
result = infinitedict()
prefix = config['global']['account']['prefix']
athena_config = confi... | 5,347,478 |
def test_copying_custom_behvior():
"""Test copying a modification that was turned into a replacment.
"""
class Subclass(CopyModfifcationTurnedToReplacement):
pass
# Chech the test class work
c = CopyModfifcationTurnedToReplacement()
assert c.counter == 0
c.feat
assert c.counter... | 5,347,479 |
def _angular_rate_to_rotvec_dot_matrix(rotvecs):
"""Compute matrices to transform angular rates to rot. vector derivatives.
The matrices depend on the current attitude represented as a rotation
vector.
Parameters
----------
rotvecs : ndarray, shape (n, 3)
Set of rotation vectors.
... | 5,347,480 |
def get_all_learners() -> Any:
"""Get all learner configurations which are prepared."""
return {
"learner_types": sorted(
[
possible_dir.name
for possible_dir in LEARNERS_DIR.iterdir()
if possible_dir.is_dir()
]
)
} | 5,347,481 |
def getdate(targetconnection, ymdstr, default=None):
"""Convert a string of the form 'yyyy-MM-dd' to a Date object.
The returned Date is in the given targetconnection's format.
Arguments:
- targetconnection: a ConnectionWrapper whose underlying module's
Date format is used
- y... | 5,347,482 |
def _assert_unique_keys(variant_key_map):
"""Checks that the keys are unique across different submaps.
Other parts of the code make the assumption that they subkeys are unique.
I'm open to changing this requirement as long as we do it safely.
"""
field_name_sets = [(submap, set(variant_key_map[subm... | 5,347,483 |
def thermal_dm(n, u):
"""
return the thermal density matrix for a boson
n: integer
dimension of the Fock space
u: float
reduced temperature, omega/k_B T
"""
nlist = np.arange(n)
diags = exp(- nlist * u)
diags /= np.sum(diags)
rho = lil_matrix(n)
rho.setdiag(diags)... | 5,347,484 |
def _get_confidence_bounds(confidence):
"""
Get the upper and lower confidence bounds given a desired confidence level.
Args:
confidence (float): [description]
# TODO: ^^
Returns:
float, float:
- upper confidence bound
- lower confidence bound
... | 5,347,485 |
def zcml_strings(dir, domain="zope", site_zcml=None):
"""Retrieve all ZCML messages from `dir` that are in the `domain`."""
from zope.configuration import xmlconfig, config
# Load server-independent site config
context = config.ConfigurationMachine()
xmlconfig.registerCommonDirectives(context)
... | 5,347,486 |
def const_p(a: C) -> Projector[C]:
"""
Make a projector that always returns the same still frame
"""
return lambda _: a | 5,347,487 |
async def handle_all_log_servers(server_url_list, executor, args):
"""
Asynchronous function that handles each CT log server: it enqueues a list of
awaitable functions, one per CT log server, and give them to asyncio for
them to be run concurrently (green thread).
"""
async with aiohttp.ClientSe... | 5,347,488 |
def get_s3_bucket(bucket_name, s3):
""""
Takes the s3 and bucket_name and returns s3 bucket
If does not exist, it will create bucket with permissions
"""
bucket_name = bucket_name.lower().replace('/','-')
bucket = s3.Bucket(bucket_name)
exists = True
try:
s3.meta.client.head_buck... | 5,347,489 |
def rf_render_ascii(tile_col):
"""Render ASCII art of tile"""
return _apply_column_function('rf_render_ascii', tile_col) | 5,347,490 |
def index():
""" Display productpage with normal user and test user buttons"""
global productpage
table = json2html.convert(json = json.dumps(productpage),
table_attributes="class=\"table table-condensed table-bordered table-hover\"")
return render_template('index.html', ... | 5,347,491 |
def student_classes(id):
"""
Show students registrered to class
* display list of all students (GET)
"""
template = "admin/class_students.html"
if not valid_integer(id):
return (
render_template(
"errors/custom.html", title="400", message="Id must be intege... | 5,347,492 |
def _get_service_handler(request, service):
"""Add the service handler to the HttpSession.
We use the django session object to store the service handler's
representation of the remote service between sequentially logic steps.
This is done in order to improve user experience, as we avoid making
multi... | 5,347,493 |
def game(agent1f, agent2f):
"""Play the game.
`agent1f` is 'X' and `agent2f` is 'O'. `agent1f` hence begins the
game.
"""
board = [[None, None, None],
[None, None, None],
[None, None, None]]
agent1 = agent1f('X')
next(agent1) # Prime.
agent2 = agent2f('O'... | 5,347,494 |
def move_by_blurry(src_dir, blurry_dir, clear_dir, blurry_thr):
"""
根据blurry 移动图片
:return:
"""
mv_tasks = [move_img_by_blurry(im_name, blurry_dir, clear_dir, blurry_thr)
for im_name in os.listdir(src_dir) if im_name.endswith('.jpg')]
print('len of mv_tasks={}'.format(len(mv_tasks... | 5,347,495 |
def f_score(overlap_count, gold_count, guess_count, f=1):
"""Compute the f1 score.
:param overlap_count: `int` The number of true positives.
:param gold_count: `int` The number of gold positives (tp + fn)
:param guess_count: `int` The number of predicted positives (tp + fp)
:param f: `int` The beta... | 5,347,496 |
def phi(n):
"""Calculate phi using euler's product formula."""
assert math.sqrt(n) < primes[-1], "Not enough primes to deal with " + n
# For details, check:
# http://en.wikipedia.org/wiki/Euler's_totient_function#Euler.27s_product_formula
prod = n
for p in primes:
if p > n:
... | 5,347,497 |
def test_get_events_no_events(mocker):
"""Unit test
Given
- get_events command
- command args
- command raw response
When
- mock the Client's token generation.
- mock the Client's get_events_request response for no events.
Then
- Validate the human readable
"""
mocker.pat... | 5,347,498 |
def run_bert_pretrain(strategy, custom_callbacks=None):
"""Runs BERT pre-training."""
bert_config = configs.BertConfig.from_json_file(FLAGS.bert_config_file)
if not strategy:
raise ValueError('Distribution strategy is not specified.')
# Runs customized training loop.
logging.info('Training using customi... | 5,347,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.