content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_app_details() -> pd.DataFrame:
"""Loads a table with app information:
# load app details
# Note that...
# 1. only apps of interest are retained
# 2. the cluster for each app is added
# 3. `score` and `minInstalls` are converted to float and int, respetively
# 4. `score` is rounded t... | 60,300 |
def certify(name, cert_path: Path, token_with_cert, ca_path: Path):
"""Create an envoy workspace."""
os.makedirs(cert_path, exist_ok=True)
token, root_certificate = token_with_cert.split(TOKEN_DELIMITER)
token = base64.b64decode(token).decode('utf-8')
root_certificate = base64.b64decode(root_certif... | 60,301 |
def update_fw_nat_rule(fw_ip, elb_ip):
"""
Call our trivial playbook in order to upgrade firewall rules
:param fw_ip:
:param elb_ip:
:return bool, String success state and the corresponding message:
"""
if CFG.DEBUG:
return True, 'DUMMY Works!'
extra_vars = {
'host': fw... | 60,302 |
def image_reproject_to_healpix_to_file(array, target_image_hdu_header, coordsys='galactic', filepath=None):
"""reproject image array to healpix image and write file
:param array: image data
:param target_image_hdu_header: the HDU object of
:param coordsys: target coordi... | 60,303 |
def get_warnings(env=None):
"""
Returns list of warning flags by using diagtool.
"""
diagtool_bin = get_diagtool_bin()
if not diagtool_bin:
return []
try:
result = subprocess.check_output(
[diagtool_bin, 'tree'],
env=env,
universal_newlines=T... | 60,304 |
def list_objects(kind):
"""
Endpoint to fetch all objects of given type from MS graph API
:request_argument since - delta token returned from last request (if exist)
:return: JSON array with fetched groups
"""
if r.args.get('auth') and r.args.get('auth') == 'user':
init_dao_on_behalf_on(... | 60,305 |
def test_ls_exclude(exclude, exp, populated_tmp_dir):
"""Test `ls` function with an exclusion of some directories"""
df = ls(populated_tmp_dir, exclude=exclude)
assert sorted(df["Name"]) == sorted(exp) | 60,306 |
def init_logger(console: Console):
"""Initialize logger.
Args:
console (Console): Console object.
"""
level = os.getenv('LOG_LEVEL', 'INFO')
logging.basicConfig(
level=logging.getLevelName(level),
format='%(message)s',
datefmt='[%X]',
handlers=[RichHandler()... | 60,307 |
def test_can_generate(app, images_meta1, images_meta2, docx_meta):
"""Test metada with image files."""
assert can_generate(images_meta1) is True
assert can_generate(images_meta2) is True
assert can_generate(docx_meta) is False | 60,308 |
def test_one_led() -> None:
"""Test that we can only control LED 0."""
backend = SBArduinoConsoleBackend("test")
with pytest.raises(ValueError):
backend.set_led_state(1, False)
with pytest.raises(ValueError):
backend.get_led_state(1) | 60,309 |
def test_add_vertex_weak(graph):
"""Tests adding a weak vertex to the graph."""
graph["test.void"] = ComparisonGraph.Vertex(
("test", "test.void"), Result.Kind.EQUAL, dup("app/main.c"), (81, 82)
)
assert "test.void" in graph.vertices
assert graph["test.void"].names == ("test", "test.void")
... | 60,310 |
def dataset_donwload(url, path_target):
"""Donwload on disk the tar.gz file
Args:
url:
path_target:
Returns:
"""
import wget
log(f"Donwloading mnist dataset in {path_target}")
os.makedirs(path_target, exist_ok=True)
wget.download(url, path_target)
tar_name = url.spli... | 60,311 |
def get_client():
"""Utility function to retrieve an authenticated client object"""
try:
client = ContainerPlatformClient.create_from_config_file(
config_file=HPECP_CONFIG_FILE, profile=PROFILE
)
client.create_session()
return client
except APIException as e:
... | 60,312 |
def run_menu(file_path, sim_names, sim_var, loop_names, loop_var):
"""
Prints out an interactable menu allowing user to assign values and run the simulation
Parameters:
(I) file_path: path to the hologram file
(I) sim_names: names of the simulation parameters
... | 60,313 |
def resolve_presets(annotations):
"""Resolve annotation presets into actual annotations."""
result = []
for annotation in annotations:
if annotation in presets:
result.extend(resolve_presets(presets[annotation]))
else:
result.append(annotation)
return result | 60,314 |
def test_init_config_class(tmpdir):
"""Test the init and save methods when specifying `flow` as a class"""
from nessai.flows import RealNVP
output = str(tmpdir.mkdir('no_config'))
config = dict(model_config=dict(flow=RealNVP))
fm = FlowModel(config=config, output=output)
assert fm.model_config[... | 60,315 |
def trace(fout=None, format=None, byteorder=sys.byteorder, nanosecond=False): # pylint: disable=redefined-builtin
"""Trace TCP flows.
Arguments:
fout (str): output path
format (Optional[str]): output format
byteorder (str): output file byte order
nanosecond (bool): output nanos... | 60,316 |
def elementwise_grad(fun, argnum=0):
"""Like `jacobian`, but produces a function which computes just the diagonal
of the Jacobian, and does the computation in one pass rather than in a loop.
Note: this is only valid if the Jacobian is diagonal. Only arrays are
currently supported. Can be used for broadc... | 60,317 |
def _max(comparer: Optional[Comparer] = None) -> Callable[[Observable], Observable]:
"""Returns the maximum value in an observable sequence according to
the specified comparer.
Examples:
>>> op = max()
>>> op = max(lambda x, y: x.value - y.value)
Args:
comparer: [Optional] Com... | 60,318 |
def tokens_ngram_processor(tokens, ngram_len):
"""
Given a `tokens` sequence or iterable of Tokens, return an iterator of
tuples of Tokens where the tuples length is length `ngram_len`. Buffers at
most `ngram_len` iterable items. The returned tuples contains
either `ngram_len` items or less for thes... | 60,319 |
def assign_column_names_types(df: pd, metadata: dict = None) -> pd:
"""
Change column names to the names defined in metadata->data_descriptor block
Args:
df (pandas): pandas dataframe
metadata (dict): metadata of the data
Returns:
pandas dataframe
"""
metadata_columns =... | 60,320 |
def run_app():
"""Main function to run task manager database program"""
option_chosen = main_choice()
clear_screen()
# if user selects option one to add a new task to the database
if option_chosen == 1:
option_one()
run_app()
# calls functions to search records in the database
... | 60,321 |
def batch_for_variantcall(samples):
"""Prepare a set of samples for parallel variant calling.
CWL input target that groups samples into batches and variant callers
for parallel processing.
If doing joint calling, with `tools_on: [gvcf]`, split the sample into
individuals instead of combining into ... | 60,322 |
def publish_runs(ctx, args):
"""Publish one or more runs.
By default, runs are published to 'published-runs'
subdirectory. To specify a different location, use `--dest`.
A published run is a subdirectory of destination `DIR` that
contains run-specific files:
- `run.yml` - run information (e.g... | 60,323 |
def transform_grams(references, sentence, n):
"""
transforms all references and sentence according n-gram
:param references: list of reference translations
:param sentence: list containing the model proposed sentence
:param n: size of the n-gram to use for evaluation
:return: new_ref, new_senten... | 60,324 |
def curve(love):
"""
draws the love sign on the table
:param love: a Turtle object
:return: None (void function)
"""
love.hideturtle()
love.begin_fill()
love.setpos(0, 10)
for i in range(50): # Setting up a loop
love.right(1)
love.forward(1)
lo... | 60,325 |
def geomag2geog(phi, theta) -> tuple:
"""convert from geomagnetic to geographic
Parameters
----------
phi: float or ndarray
geomagnetic longitude in radians
theta: float or ndarray
geomagnetic latitude in radians
Results
-------
glon: float or ndarray
geograph... | 60,326 |
def poly_coeff(points):
"""
# 1. calc s=Q(t) for given 4 control points in 3rd order Bezier curve. Calc (s,t) pair for 1000 t values.
# 2. polynormial fit (t,s) pairs to get t = L(s) coeff
# 3. return poly fit coeff, s = Q(t=1)
"""
xpoints = [p[0] for p in points]
ypoints = [p[1] for p i... | 60,327 |
def prepare_attention_input(encoder_activations: fastmath_numpy.array,
decoder_activations: fastmath_numpy.array,
inputs: fastmath_numpy.array) -> tuple:
"""Prepare queries, keys, values and mask for attention.
Args:
encoder_activations fastnp... | 60,328 |
def setup_amqp_req(amqp):
"""Use the amqp interface to request access to the amqp broker using our
local configuration.
"""
amqp.request_access(username='aodh',
vhost='openstack')
aodh.assess_status() | 60,329 |
def TStrUtil_GetCleanWrdStr(*args):
"""
TStrUtil_GetCleanWrdStr(TChA ChA) -> TChA
Parameters:
ChA: TChA const &
"""
return _snap.TStrUtil_GetCleanWrdStr(*args) | 60,330 |
def train(cfg: TrainConfig) -> None:
"""train classifer.
Args:
cfg (TrainConfig): Configs whose type is checked by schema.
"""
# Make config read only.
# without this, config values might be changed accidentally.
OmegaConf.set_readonly(cfg, True) # type: ignore
logger.info(OmegaConf... | 60,331 |
def copy_project(project_name: str) -> Iterator[Path]:
"""Copy a project with name project_name from the assets directory to a temp directory.
This function returns a ContextManager, so it should be used in a `with` statement,
and when it goes out of scope it will delete the temporary directory.
Retur... | 60,332 |
def unregisterExtModuleTopLevel(name, URI):
"""Unregisters an extension module top-level element"""
ret = libxsltmod.xsltUnregisterExtModuleTopLevel(name, URI)
return ret | 60,333 |
async def test_get_run_command_missing_command(
decoy: Decoy,
engine_store: EngineStore,
) -> None:
"""It should 404 if you attempt to get a non-existent command."""
key_error = pe_errors.CommandDoesNotExistError("oh no")
run = Run(
id="run-id",
protocolId=None,
createdAt=da... | 60,334 |
def _convert_to_utc(date_string):
""" (private method) Expected input: YYYY-MM-DD-HH:MM:SS.
Conversion of standard date format to UTC.
:param date_string: string of date in format: YYYY-MM-DD-HH:MM:SS
:type date_string: string
"""
big_time_tmp = date_string.split("-")
year = int(big_time_tmp... | 60,335 |
def test_filter_barrier_plans_location(location, location_query, expected):
"""
Ensure that filtering with location is working correctly.
"""
api_client = get_api_client()
barrier_plan = get_barrier_plan(location)
response = api_client.get(
reverse("v1:barrierplan-list"), {"location": l... | 60,336 |
def init():
"""Glut init function."""
glClearColor(0, 0, 0, 0)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 0)
glLightfv(GL_LIGHT0, GL_POSITION, [2, 0, 10, 1])
lA = 0.8
glLightfv(GL_LIGHT0, GL_AMB... | 60,337 |
def FGP_Module(V, W, check=True):
"""
INPUT:
- ``V`` -- a free R-module
- ``W`` -- a free R-submodule of ``V``
- ``check`` -- bool (default: ``True``); if ``True``, more checks
on correctness are performed; in particular, we check the data
types of ``V`` and ``W``, and that ``W`` is a... | 60,338 |
def run(leave_running_atexit=False):
"""Ensure an API server is running, and ARVADOS_API_* env vars have
admin credentials for it.
If ARVADOS_TEST_API_HOST is set, a parent process has started a
test server for us to use: we just need to reset() it using the
admin token fixture.
If a previous ... | 60,339 |
def fromMorse(message: str) -> str:
"""decodes morse code into a message"""
morseToChar = {v: k for k,v in charToMorse.items()}
morseToChar['/'] = ' '
res = ''
for c in message.split():
res += morseToChar.get(c,'_')
if res[-1] == '_':
print("# Warning: {} not correct... | 60,340 |
def ensure_column_exists(df, col_name, col_alt = False, raise_error = True):
"""Checks if a particular name is among the column names of a dataframe. Alternative names can be given, which when
found will be changed to the desired name. The DataFrame will be changed in place. If no matching name is found an
... | 60,341 |
def _wait_for_ifc_up(ifname, timespan=10):
""" Waits up to timespan seconds for the specified interface to be up.
Prints a message if the interface is not up in 2 seconds.
Args:
ifname (str) : Name of the interface
timespan (int) : length of time to wait in seconds
Returns:
True ... | 60,342 |
def search_by_keyword(keyword="", uuid=""):
"""
Uses the `/search` endpoint.
takes a user uuid and a keyword.
If you specify no `uuid`, the search will not show private streams?
If the keyword is empty, it will return all the streams from the app.
e.g. uuid="e9c3d27e-406b-4f4a-9b87-6d3460c60ca6... | 60,343 |
def getArguments():
"""
Get argumments from command-line
If pass only dataframe path, pop and gen will be default
"""
dfPath = sys.argv[1]
if(len(sys.argv) == 4):
pop = int(sys.argv[2])
gen = int(sys.argv[3])
else:
pop = 10
gen = 2
return dfPath, pop, gen | 60,344 |
def plot_sigma_report(
ds,
temp_label,
temp_var_acc_label,
temp_var_prec_label=None,
itimes=None):
"""
Returns two sub-plots. first a temperature with confidence boundaries.
Parameters
----------
ds
temp_label
temp_var_label
itimes
"""
time... | 60,345 |
def test_torsiondrive_procedure(storage_socket, session):
"""
Torsiondrive procedure
"""
assert session.query(TorsionDriveProcedureORM).count() == 0
# assert Keywords.objects().count() == 0
# molecules = MoleculeORM.objects(molecular_formula='H4O2')
# assert molecules.count() == 2
... | 60,346 |
def get_feedback(post_id):
""" Get the list of feedback on post. """
# Returns: [(uid, feedback)]
route = '{}/api/v2.0/feedbacks/post/' +\
'{}?key={}&filter=JJLFGJOFIOMFLGHJLHNIFMGJILKJKHOLMHIFGGOLFNIHF'
response = requests.get(route.format(ms_config["ms_host"], post_id, ms_config["api_key"... | 60,347 |
def load_state_dict(model, fname):
"""
Set parameters converted from Caffe models authors of VGGFace2 provide.
See https://www.robots.ox.ac.uk/~vgg/data/vgg_face2/.
Arguments:
model: model
fname: file name of parameters converted from a Caffe model, assuming the file format is Pickle.
... | 60,348 |
def projected_co(verts, matrix):
""" converts coordinates of points from OCS to WCS->ScreenCS
needs matrix: a projection matrix
needs verts: a list of vectors[x,y,z]
returns a list of [x,y,z]
"""
#print 'deb:projected_co() verts=', verts #---------
temp_verts = [Mathutils.Vector(v)*matrix for v in verts]
#prin... | 60,349 |
def cost2_sabx(p,x,y):
"""
Sum of squared deviations of obs and square root of general 1/x function: sqrt(a + b/x)
Parameters
----------
p : iterable of floats
parameters (`len(p)=2`)
`p[0]` a
`p[1]` b
x : float or array_like of floats
independent variable
... | 60,350 |
def set_matrix_world(obj, matrix_world):
"""
Seems only set pose by obj.location and obj.rotation_euler
"""
if len(matrix_world) == 3:
matrix_world = homo_coord(matrix_world)
obj.location, quaternion, obj.scale = mathutils.Matrix(matrix_world).decompose()
obj.rotation_euler = quaternion... | 60,351 |
def createsuperuser():
""" Creates new superuser in Django. """
require('hosts')
require('code_dir')
management_cmd('createsuperuser') | 60,352 |
def build_img_fda_head(cfg, input_shape):
"""
Build a image-level feature distribution alignment head
defined by `cfg.MODEL.IMG_FDA_HEAD.NAME`.
"""
head_name = cfg.MODEL.IMG_FDA_HEAD.NAME
return IMG_FDA_HEAD_REGISTRY.get(head_name)(cfg, input_shape) | 60,353 |
def status(jobid, results_dir_path=None, extract=False, silent=False,
host="http://www.compbio.dundee.ac.uk/jpred4/cgi-bin/rest",
jpred4="http://www.compbio.dundee.ac.uk/jpred4"):
"""Check status of the submitted job.
:param str jobid: Job id.
:param str results_dir_path: Directory pa... | 60,354 |
def underline_filter(text):
"""Jinja2 filter adding =-underline to row of text
>>> underline_filter("headline")
"headline\\n========"
"""
return text + "\n" + "=" * len(text) | 60,355 |
def select_training_set_labels_from_database(
label_columns,
filter_args=None,
filter_func=None,
limit=None,
**kwargs
):
"""
Construct a set of training labels from a query to the SDSS-V database.
:param label_columns:
A tuple of database column... | 60,356 |
def pa_to_mbar(x):
"""Pa to mbar.
Parameters
----------
x : float or array of floats
Air pressure (in Pa)
Returns
-------
output : float or array of floats
Air pressure (in mbar)
"""
return x / 100. | 60,357 |
def myLogger(Folder, LogFileName):
"""
Since logging in a loop does always write to the first instaniated file,
we make a little wrapper around the logger function to write to a defined
log file.
Based on http://stackoverflow.com/a/2754216/323100
"""
import logging
import os
logger ... | 60,358 |
def vicare_login(hass, entry_data):
"""Login via PyVicare API."""
vicare_api = PyViCare()
vicare_api.setCacheDuration(entry_data[CONF_SCAN_INTERVAL])
vicare_api.initWithCredentials(
entry_data[CONF_USERNAME],
entry_data[CONF_PASSWORD],
entry_data[CONF_CLIENT_ID],
hass.con... | 60,359 |
def test_unused_variable_tuple_definition(
assert_errors,
parse_ast_tree,
context,
indentation,
bad_name,
forbidden_tuple_unused_template,
default_options,
):
"""Testing that any variable cannot be used if it is marked as unused."""
tree = parse_ast_tree(
context.format(
... | 60,360 |
def test_random_uniform():
"""Random uniform initializer test
"""
tf.reset_default_graph()
tf.random.set_random_seed(0)
runiform_class = INITIALIZER_REGISTRY['uniform']
runiform_obj = runiform_class({"low":0.1, "high":0.4})
tf_init = runiform_obj.get_tf_initializer()
var1 = tf.get_variab... | 60,361 |
def markup(pre, string):
"""
By Adam O'Hern for Mechanical Color
Returns a formatting string for modo treeview objects.
Requires a prefix (usually "c" or "f" for colors and fonts respectively),
followed by a string.
Colors are done with "\03(c:color)", where "color" is a string represe... | 60,362 |
def no_translate_logs(logical_line, filename):
"""Check for 'LOG.*(_('
Starting with the Pike series, OpenStack no longer supports log
translation. We shouldn't translate logs.
- This check assumes that 'LOG' is a logger.
- Use filename so we can start enforcing this in specific folders
inst... | 60,363 |
def get_height(tracker: TrackerComponent):
"""Returns the height of the tracker, assuming relative to the floor."""
if tracker.is_hardware:
torso_state = tracker.get_state('torso')
return torso_state.pos[2]
return 0 | 60,364 |
def compute_pairs(a: Array, op: Callable[[Array, Array], Array]) -> Array:
"""Computes pairs based on values of `a` and the given pairwise `op`.
Args:
a: The array used to form pairs. The last axis is used to form pairs.
op: The binary op to map a pair of values to a single value.
Returns:
A new arr... | 60,365 |
def polyfit(dates, levels, p):
"""given the water level time history (dates, levels) for a station computes a least-squares fit of a polynomial of
degree p to water level data. return a tuple of the polynomial object and any shift of the time (date) axis"""
days = matplotlib.dates.date2num(dates)
if d... | 60,366 |
def _release_chain_resources(chain: Chain):
"""
Remove all 'heavy' parts from the chain
:param chain: fitted chain
:return: chain without fitted models and data
"""
chain.unfit()
gc.collect()
return chain | 60,367 |
def load_x(x):
"""Load the x coordinate of public key in dmem at appropriate location according to calling conventions"""
dmem[pX] = x | 60,368 |
def ricker_wavelet(v, sigma):
""" Returns the ricker wavelet, or mexican hat wavelet, like this:
https://en.wikipedia.org/wiki/Mexican_hat_wavelet
"""
sigma_cast = tf.cast(sigma, tf.float32)
sigmasquared = tf.pow(sigma_cast, 2.0)
f = 3.0 * np.power(np.pi, 0.25)
p1 = 2.0 / (tf.sqrt(sigma_cas... | 60,369 |
def solve_efield_from_potential_periodic(phi_N, delta_x_N):
"""Given potential field, solves for e-field in 1D"""
# Perform calculation
E_N = -(np.roll(phi_N, -1) - np.roll(phi_N, 1))/(2*delta_x_N)
# Return E-field
return(E_N) | 60,370 |
def add_header16(header_type_name, field_dec):
"""
This method returns a header definition with its fields description
:param header_type_name: the type name of the header
:type header_type_name: str
:param field_dec: the field description of the header
:type field_dec: str
:returns: str -... | 60,371 |
async def on_guild_channel_create(channel: discord.TextChannel):
""" Update the changelog with created channels. """
if isinstance(channel, discord.abc.PrivateChannel):
return
changelog_channel = get_changelog_channel(channel.guild)
if not changelog_channel:
return
# Differ between... | 60,372 |
def response2dict(response):
"""
This converts the response from urllib2's call into a dict
:param response:
:return:
"""
split_newlines = response.split('\r\n')
split_tabs = [s.split('\t') for s in split_newlines if s !='']
return split_tabs | 60,373 |
def test_export_burst_folder_album():
"""test non-selected burst photos are exported with the album their key photo is in, issue #401"""
import glob
import os
import os.path
import pathlib
from osxphotos.cli import export
runner = CliRunner()
cwd = os.getcwd()
# pylint: disable=not... | 60,374 |
def handle_new_conn(sock, fd_to_socket, poller):
"""Handles a new connection to the server.
Accepts the socket sonnection and registers the socket with the poller
appropriately.
Arguments:
sock (:obj: `socket`) socket object associated with the server socket
fd_to_socket (:obj: `dict`)... | 60,375 |
def data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_bandwidth_profile_get(uuid, node_uuid, node_rule_group_uuid): # noqa: E501
"""data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_available_capacity_bandwidth... | 60,376 |
def _enforce_names_consistency(specs):
"""Enforces that either all specs have names or none do."""
def _has_name(spec):
return hasattr(spec, 'name') and spec.name is not None
def _clear_name(spec):
spec = copy.deepcopy(spec)
if hasattr(spec, 'name'):
spec._name = None # pylint:disable=protect... | 60,377 |
def get_job_status(ibs, jobid):
"""
Web call that returns the status of a job
CommandLine:
# Run Everything together
python -m ibeis.web.job_engine --exec-get_job_status
# Start job queue in its own process
python -m ibeis.web.job_engine test_job_engine --bg
# Start... | 60,378 |
def plot(set_num, ref, test, diff, metrics_dict, parameter):
"""Based on set_num and parameter.backend,
call the correct plotting function."""
if hasattr(parameter, 'plot'):
parameter.plot(ref, test, diff, metrics_dict, parameter)
else:
if parameter.backend not in ['vcs', 'cartopy', 'mpl... | 60,379 |
def wedschedule():
"""Wednesday Schedule"""
now = wait(datetime.now(), 9, 45)
if now >= now.replace(hour=9, minute=45) and now < now.replace(hour=11, minute=45):
start_session(ap, now.replace(hour=11, minute=45))
now = wait(datetime.now(), 11, 45)
if now >= now.replace(hour=11, minute=4... | 60,380 |
def int2D(igrad_x, igrad_y, idx, idy, const_at_edge=False):
"""
Sparse matrix integration to solve grad(a) = b for a
Requires integration constant (= reference value at position [1,1] = iconst)
Assumes uniform spacing
Based on:
https://math.stackexchange.com/questions/1340719/numerically-find-a... | 60,381 |
def test_bad_X_y_inputation(nameTree, Tree, nameSet, dataXY):
"""Checks the reaction of the estimator with bad inputation of X and y
Parameters
----------
nameTree : str
Name of the tree estimator
Tree : estimator
estimator to check
nameSet : str
Name of the dataset
... | 60,382 |
def _gr0_sorted_ ( graph , reverse = False ) :
"""Make sorted graph
>>> graph = ...
>>> s = graph.sorted()
"""
oitems = ( i for i in graph.iteritems() )
sitems = sorted ( oitems , key = lambda s :s[1] , reverse = reverse )
new_graph = ROOT.TGraph ( len( graph ) )
c... | 60,383 |
def fake_io(write_func: Callable[[str], int]) -> Iterator[None]:
"""Run code with stdout and stderr replaced by FakeIOStreams.
Args:
write_func: The function to call when write is called.
"""
old_stdout = sys.stdout
old_stderr = sys.stderr
fake_stderr = FakeIOStream(write_func)
fake... | 60,384 |
def create_big_number(title, large_number, render_func, pacing='--'):
"""
title = description of big number
large_number = whatever number you want to highlight
render_func = plotly rendering function like iplot
"""
pacing_font_color = utilities.warning_color_font(pacing)
background_color = ... | 60,385 |
def test_list_enabled_plugins():
"""
Test if it returns a list of plugins.
"""
mock_run = MagicMock(
return_value={"retcode": 0, "stdout": "saltstack\nsalt\nother", "stderr": ""}
)
mock_pkg = MagicMock(return_value="")
with patch.dict(
rabbitmq.__salt__, {"cmd.run_all": mock_... | 60,386 |
def affine_forward(
backbone: tf.keras.Model,
moving_image: tf.Tensor,
fixed_image: tf.Tensor,
moving_label: (tf.Tensor, None),
moving_image_size: tuple,
fixed_image_size: tuple,
):
"""
Perform the network forward pass.
:param backbone: model architecture object, e.g. model.backbone... | 60,387 |
def compare_size_with_json():
"""
Compares size between PROTO and JSON
:return:
"""
with open('proto.txt', 'w') as the_file:
json_str = json.dumps({"employee_id" : str(uuid.uuid4()), "name" : "Bob", "type" : "FULLTIME", "email" : "bob@company.com", "extension": 9090, "groups" : ["seattle","s... | 60,388 |
def im_click(im, color_mapper=None, plot_height=400, plot_width=None,
length_units='pixels', interpixel_distance=1.0,
x_range=None, y_range=None,
no_ticks=False, x_axis_label=None, y_axis_label=None,
title=None, flip=True):
"""
"""
def display_event(div,... | 60,389 |
def compartment_list(conf: OCIConfig):
"""
list all compartments
:param conf: OCIConfig object
"""
region_tree = {}
for r in conf.region_subscriptions:
conf.workon_region = r.region_name
region_tree[r.region_name] = compartment_tree_build(conf)
conf.compartments_tree = regio... | 60,390 |
def is_param_comment(token, next_token, comment_syntax):
"""
SQLエンジンのパラメータコメント判定
"""
return get_comment_type(token, comment_syntax) == EngineComment.param \
and (is_literal(next_token) or is_wildcard(next_token) or is_parenthesis(next_token)) | 60,391 |
def train(**kwargs):
"""
Train model
Load the whole train data in memory for faster operations
args: **kwargs (dict) keyword arguments that specify the model hyperparameters
"""
# Roll out the parameters
img_dim = kwargs["img_dim"]
patch_size = kwargs["patch_size"]
image_data_form... | 60,392 |
def multi_ts_support(func):
"""
This decorator further adapts the metrics that took as input two univariate/multivariate `TimeSeries` instances,
adding support for equally-sized sequences of `TimeSeries` instances. The decorator computes the pairwise metric for
`TimeSeries` with the same indices, and re... | 60,393 |
def course_search_index_handler(request, course_key_string):
"""
The restful handler for course indexing.
GET
html: return status of indexing task
json: return status of indexing task
"""
# Only global staff (PMs) are able to index courses
if not GlobalStaff().has_user(request.us... | 60,394 |
def test_data_file_update_url_different_file_not_indexed(
create_alias,
create_index,
get_index_uuid,
get_index_hash,
client,
pg_driver,
admin,
submitter,
cgci_blgsp,
):
"""
Test submitting the different data (with NO id provided) and updating the
URL field.
HOWEVER ... | 60,395 |
async def data(ctx: lightbulb.Context) -> None:
"""Load or read data from the node.
If just `data` is ran, it will show the current data, but if `data <key> <value>` is ran, it
will insert that data to the node and display it."""
node = await plugin.bot.d.lavalink.get_guild_node(ctx.guild_id)
if n... | 60,396 |
def main():
"""The Imperial March Sounds"""
args = get_args()
cluster_ids = set()
#protein_ids = set()
num_sequence = 0
count= 0
for line in args.cdhit:
if line.startswith('>'):
continue
else:
match = re.search(r'>(\d+)', line)
id = match... | 60,397 |
def report_account_status(context):
"""报告账户持仓状态"""
if context.now.isoweekday() > 5:
return
logger = context.logger
latest_dt = context.now.strftime(dt_fmt)
account = context.account(account_id=context.account_id)
cash = account.cash
positions = account.positions()
logger.info("... | 60,398 |
def generate_demos(match="demo_"):
"""
Load the use case manager and run every function inside it which contains
a match to the string given in the argument of this function.
The function docstrings get rendered as a markdown page. If images are
generated and saved as a result, those are added to t... | 60,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.