content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def add_edit_button(user_id):
"""Determines if home page requires an edit button
Args:
user_id:
user_id being used to request home page
Returns:
list
list of dictionaries containing buttons
"""
button_list = [
{
"textButton": {
"text": "START ... | 5,294,100 |
def not_found(error):
""" error handler """
return make_response(jsonify({'error': 'Not found'}), 404) | 5,294,101 |
def port(port_data):
"""Represents a view for a port object"""
keys = ('id', 'network_id', 'mac_address', 'fixed_ips',
'device_id', 'admin_state_up', 'tenant_id', 'status')
return resource(port_data, keys) | 5,294,102 |
def connection_info():
"""
Return a string showing the figure and connection status for
the backend. This is intended as a diagnostic tool, and not for general
use.
"""
from matplotlib._pylab_helpers import Gcf
result = []
for manager in Gcf.get_all_fig_managers():
fig = manager... | 5,294,103 |
def get_bridge(ip):
"""The name to be used for the bridge interface connecting the VMs and the host."""
return "spirebr%s" % ip.packed.hex().upper() | 5,294,104 |
def main():
"""
Allows FT5_OpenFloodVeg_merge Tool to be executed from commmand line
instead of GUI.
Function "main()" allows the FT5_OpenFloodVeg_merge module to be run as a
script in batch, called from the command line or managing script rather
than through a Toolbo... | 5,294,105 |
def test1():
"""test case 1
Returns:
matrix: np.array
vector b: np.array
vector c: np.array
vector j: np.array
"""
A = np.array([
[-2, -1, -4, 1, 0],
[-2, -2, -2, 0, 1]
])
b = np.array([-1, -1.5])
c = np.array([-4, -3, -7, 0, 0])
J = np.ar... | 5,294,106 |
def read_text_file(file_path):
"""
Read text file utility
Read the text file from the given path
if file is not present, exit
params: file_path - string
returns: file_data - list
"""
logger.debug("<<<< 'Current Executing Function' >>>>")
if os.path.exists(file_path):
... | 5,294,107 |
def try_deserialize_handler(serialized_handler):
"""Reverse function of try_serialize_handler.
Args:
serialized_handler: serialized handler str or None.
Returns:
handler instance or None.
"""
if serialized_handler:
return pickle.loads(serialized_handler) | 5,294,108 |
async def load_from_server(
component_builder: Optional[ComponentBuilder] = None,
project: Optional[Text] = None,
project_dir: Optional[Text] = None,
remote_storage: Optional[Text] = None,
model_server: Optional[EndpointConfig] = None,
wait_time_between_pulls: Optional[int] = None,
) -> "Project... | 5,294,109 |
def create_superuser(firstname, lastname, email):
"""Create superuser
"""
import getpass
try:
password = getpass.getpass('Enter your password: ')
while password is '':
print('Password cannot be blank')
password = getpass.getpass('Enter your password: ')
w... | 5,294,110 |
def unravel_index(ind, tensor_shape):
"""no official tensorflow implementation for this yet;
this is based on one proposed in https://github.com/tensorflow/tensorflow/issues/2075
"""
ind = tf.expand_dims(tf.cast(ind, tf.int64), 0)
tensor_shape = tf.expand_dims(tf.cast(tensor_shape, tf.int64), 1)
... | 5,294,111 |
def write_tfrecord_from_tensorrec_dataset(tfrecord_path, dataset):
"""
Writes the contents of a TensorRec Dataset to a TFRecord file.
:param tfrecord_path: str
:param dataset: tf.data.Dataset
:return: str
The tfrecord path
"""
session = get_session()
iterator = create_tensorrec_itera... | 5,294,112 |
def __test_basic_loop(conn):
"""
Test basic continuous output sending
"""
code= """
def loop():
y= 5
while y > 0:
api.send('y= ' + str(y))
y-=1
"""
token, errmsg= conn.send_store_request("loop", code)
if errmsg is not None:
logging.error(f"error message f... | 5,294,113 |
def test_exec_server_schedules():
"""test_exec_server_schedules"""
exec_server_schedules.main(pytest.db_test)
pytest1_end_time = query_test_db(
"""SELECT end_time FROM schedule_log WHERE returncode = 0 AND schedule_id='pytest1'"""
)[0][0]
pytest2_start_time = query_test_db(
"""SELE... | 5,294,114 |
def _weights_init(m):
"""Random initialization of weights.
:param m: pytorch model
:type m: nn.Module
"""
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight) | 5,294,115 |
def _convert_universal_format(format):
"""Converts Universal Date Time Format to Python strftime format string"""
i = 0
token_string = format
python_format = format
token_map = sorted(_DATETIME_FORMAT_MAP, key=lambda t: t[0], reverse=True)
calculated_tokens = {}
for f in token_map:
i... | 5,294,116 |
def get_loader(dataset: str, batch_size: int) -> Tuple:
"""
:param dataset: The name of the dataset we want to use. Either JSB_Chorales, MuseData, Nottingham, or Piano_midi.
:param batch_size: how many sequences to train on at once.
:return: DataLoaders for training, testing, and validation.
"""
... | 5,294,117 |
def librato_flush_metrics(gauges, counters, data):
"""
POST a collection of gauges and counters to Librato Metrics.
"""
headers = {
'Content-Type': 'application/json',
'User-Agent': config['user_agent'],
'Authorization': 'Basic %s' % config['auth_header']
}
body = j... | 5,294,118 |
def hardwareVersionToString (hwversion):
"""
Converts a raw integer value into a human readable string a.b.c.d.
:param int hwversion: raw value as received from the generator
:return str: a human readable string 'a.b.c.d'.
"""
if ((hwversion >> 30) & 1) != 0:
# new format 30-22 + 21-16
# mask here with 0xFF ... | 5,294,119 |
def enumerateIds(referenceWindow=None):
"""
Enumerate all refIds (subject to the referenceWindow restriction, if provided).
"""
assert isLoaded()
if referenceWindow is None:
for refId in byId: yield refId
else:
refId, refStart, refEnd = referenceWindow
yield refId | 5,294,120 |
def pareto_mtl_search(ref_vecs,i,t_iter = 100, n_dim = 20, step_size = 1):
"""
Pareto MTL
"""
# randomly generate one solution
x = np.random.uniform(-0.5,0.5,n_dim)
# find the initial solution
for t in range(int(t_iter * 0.2)):
f, f_dx = concave_fun_eval(x)
... | 5,294,121 |
def get_region_stats_np(im: np.ndarray, region: Box) -> Stat:
"""Get array region stats using Numpy.
Parameters
----------
im : np.ndarray
Input image to analyze
region : Box
Coordinates for region
Returns
-------
Stat
Stat object containing various statistics o... | 5,294,122 |
def test_collocation_single_words():
"""
word_cloud can be called with an array of single words (e.g. a column
of cells containing single words)
"""
grams = collocation(['time', 'nick of time'])
assert grams == [
('of-time', 1),
('nick-of', 1),
('nick-time', 1)
] | 5,294,123 |
def _create_pipeline(
pipeline_root: str,
csv_input_location: str,
taxi_module_file: tfx.dsl.experimental.RuntimeParameter,
push_destination: tfx.dsl.experimental.RuntimeParameter,
enable_cache: bool
):
"""Creates a simple Kubeflow-based Chicago Taxi TFX pipeline.
Args:
pipeline_root: The r... | 5,294,124 |
def gz(tesseroid, lons, lats, radii, nodes, weights):
"""
Integrate gz using the Gauss-Legendre Quadrature
"""
order = len(nodes)
lonc, latc, rc, scale = _scale_nodes(tesseroid, nodes)
# Pre-compute sines, cossines and powers
sinlatc = numpy.sin(latc)
coslatc = numpy.cos(latc)
sinlat... | 5,294,125 |
def polynomial_coefficients_fast(r,s,alpha,beta,_=None):
""" Return the coefficients of the Farey polynomial of slope r/s.
The method used is the recursion algorithm.
Arguments:
r,s -- coprime integers representing the slope of the desired polynomial
alpha, beta -- parameters o... | 5,294,126 |
def get_light_threshold(response):
"""Get light from response."""
light_threshold = response.get("highlight")
return light_threshold | 5,294,127 |
def variant_ids(
locus: hl.expr.LocusExpression, alleles: hl.expr.ArrayExpression, max_length: int = None
) -> hl.expr.ArrayExpression:
"""
Return a list of variant ids - one for each alt allele in the variant
"""
def compute_variant_id(alt):
return hl.rbind(
hl.min_rep(locus, [... | 5,294,128 |
def mkdir(dir_name):
"""mkdir(dir_name) -> None Equivalent to 'mkdir' in a shell except
that if the directory exists, it will not be overwritten.
"""
if not os.path.isdir(dir_name):
os.mkdir(dir_name) | 5,294,129 |
def normalize_img_to_rgb(img_1_, img_h_, img_w_):
"""
Normalize the given image
"""
rgb_img_1 = cv2.imread(img_1_, 1)[:, :, ::-1]
rgb_img_1 = cv2.resize(rgb_img_1, (img_h_, img_w_))
rgb_img_1 = np.float32(rgb_img_1) / 255.
return rgb_img_1 | 5,294,130 |
def getonts():
"""get the list of ont terms"""
return Ontterms.objects.all().filter(to_remove__isnull=True).order_by('title') | 5,294,131 |
def exit_wd(cwd):
"""
Enter working directory
Parameters
----------
cwd : string
Current working directory
"""
# Step out of working directory
os.chdir(cwd)
# Return
return | 5,294,132 |
def load_frame_building_sample_data():
"""
Sample data for the BuildingFrame object
"""
number_of_storeys = 6
interstorey_height = 3.4 # m
masses = 40.0e3 # kg
n_bays = 3
fb = models.FrameBuilding(number_of_storeys, n_bays)
fb.interstorey_heights = interstorey_height * np.ones(num... | 5,294,133 |
def analyze_group(group, verbosity, error_level):
"""analyze AD group object
group -- group object to be analyzed
verbosity - NAGIOS verbosity level - ignored
error_level - ignored
Returns the Nagios error code (always 0) and error message (group defn)
"""
return 0, '{name:%s, description:%... | 5,294,134 |
def discount_rewards(x: Sequence, gamma: float) -> np.ndarray:
"""
Given vector x, computes a vector y such that
y[i] = x[i] + gamma * x[i+1] + gamma^2 x[i+2] + ...
"""
return signal.lfilter([1], [1, -gamma], x[::-1], axis=0)[::-1] | 5,294,135 |
def type_for_objcclass(objcclass):
"""Look up the :class:`ObjCInstance` subclass used to represent instances of the given Objective-C class in Python.
If the exact Objective-C class is not registered, each superclass is also checked,
defaulting to :class:`ObjCInstance` if none of the classes in the supercl... | 5,294,136 |
def command(name=None, descr=None, long_descr=None, examples=None, free_form=False, kind='command'):
"""Define a model command.
:param name: An optional name of the command. Defaults to the name of the function.
:param descr: A short description of the command
:param long_descr: A long de... | 5,294,137 |
def atualizar():
"""
Função para atualizar um produto
"""
conn = conectar()
cursor = conn.cursor()
codigo = int(input('Codigo da Classificação Indicativa: '))
idade = int(input('Nova Classificação indicativa: '))
cursor.execute(f'UPDATE classificacao SET idade = {idade} WHERE id ... | 5,294,138 |
def bilinearUpsample2Don3D(input_tensor):
""" Using tf.image.resize for bilinear interpolation """
""" ATTENTION: bilinear seems only works on 2D image """
##### NOTE: this bilinaer upsampling works on axies [1,2] in [0,1,2,3,4] #####
input_shape = input_tensor.shape
switch_axes = [0,3,1,2,4]
re... | 5,294,139 |
def builtin_locals(self, context, looping=False):
"""Get the definitions local to the current scope."""
lv = []
for (name, value) in sorted(context.scope.items(), key=lambda x: x[0]):
lv.append(BList([BStr(name), value]))
context.push(BList(lv)) | 5,294,140 |
def fromhaeberlen(diso, delta, eta):
"""
Converts from the haeberlen convention to the PAS CSA tensor.
Parameters
----------
diso : float
diso == 1/3(d11 + d22 + d33)
delta : flaot
dzz - diso
eta : float
(dyy - dxx)/delta (0 <= eta <= 1)
Returns
----------
... | 5,294,141 |
def gst00b(uta, utb):
""" Greenwich apparent sidereal time, consistent with IAU 2000 resolutions,
using truncated nutation model IAU 2000B.
:param uta, utb: UT1 as a two-part Julian date.
:type uta, utb: float
:returns: Greenwich apparent sidereal time in radians (float).
.. seealso:: |MANUAL... | 5,294,142 |
def cleanup_rollback():
"""
Remove and archive rolled-back release.
"""
last_release = run("ls -xt %s" % paths.releases_path).split()[0]
last_release_path = paths.releases_path.join(last_release)
args = (paths.current_path, last_release_path)
if test("[ `readlink %s` != %s ]" % args):
... | 5,294,143 |
def search_bad_symbols_and_username(username):
"""Поиск зарезервированных слов и запрещенных символов"""
search_bad_symbols_result = 'No'
bad_username = ['root', 'admin', 'moderator', 'support', 'supports', 'helpdesk']
bad_symbols = ['&', ' ', '=', '+', '<', '>', ',', '.', '\"', '\'', '?', '!', ':', ';... | 5,294,144 |
def insert_into_tables(conn,insert,dic):
"""
Insert data in the tables
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
try:
cur.execute(insert, (dic))
except sqlite3.Error as e:
print(e) | 5,294,145 |
def synthesize_edge_selector(sel_data,):
"""
Synthesizes an edge selector string based on what edges were selected.
"""
selector_str = '.edges("{filter}{axis}")' # {index}")'
axis_index = -1
axis_str = ""
filter_str = ""
index_str = ""
axis_str = None
axis_filter = None
# ... | 5,294,146 |
def to_ascii(voxels, bounding_box, outputFilePath):
"""
Create an ascii file and store the voxel array
"""
output = open(outputFilePath, 'w')
for z in bounding_box[2]:
for x in bounding_box[0]:
for y in bounding_box[1]:
if voxels[z][x][y]:
outp... | 5,294,147 |
def bundle(ctx, enabled, disabled, verbose):
"""Manage command bundles and their config.
If no subcommand is given, lists all bundles installed, and their
currently enabled version, if any.
"""
if ctx.invoked_subcommand is None:
bundles = ctx.obj.api.bundles()
if enabled and disab... | 5,294,148 |
def FilterMatchesTest(filter_string, test_string):
"""Does something close enough to base/strings/pattern.h's MatchPattern() for
our purposes here."""
return fnmatch.fnmatch(test_string, filter_string) | 5,294,149 |
def validate_car_with_id_exists(db: Session, car_id: int) -> None:
"""
Raises CarNotFoundException if car by given id doesn't exist
"""
car = services.car.get(db=db, _id=car_id)
if not car:
raise CarNotFoundException() | 5,294,150 |
def _exit():
"""
Schedule stopping scripts.
"""
if _loop is not None and not _loop.is_closed():
logger = _utils.get_logger()
logger.debug('Scheduling script termination')
# Schedule stop routine
def __stop(loop):
logger.debug('Stopping scripts')
l... | 5,294,151 |
def test_delete_branch_miss_left_call(branch_node):
"""
GIVEN branch node and value that is less than the node value
WHEN delete is called with the value
THEN the left child delete is called with the value.
"""
left_child = branch_node.left
branch_node.delete(-1)
left_child.delete.asse... | 5,294,152 |
def make_path(components):
"""Build a path from a list of components."""
return '/{}'.format(
'/'.join([quote(str(c), '') for c in components if c])) | 5,294,153 |
def nnet_align(i, config, train_directory, align_directory, num_jobs):
"""
Multiprocessing function that generates an nnet alignment
See:
- http://kaldi-asr.org/doc/nnet-align-compiled_8cc.html
for more details
on the Kaldi binary this runs.
Also see https://github.com/kaldi-asr/kaldi/bl... | 5,294,154 |
def register_coco(
ann_file: str,
img_dir: str,
dataset_name: str,
class_names: List[str]
):
"""Register dataset with annotations in COCO format in Detectron2.
Parameters
----------
ann_file : str
Path of annotation json file
img_dir : str
Directory containing JP... | 5,294,155 |
def test_name_field(u1_ml100k, pkf):
"""Ensure the name field is taken into account."""
sim_options = {'name': 'cosine'}
algo = KNNBasic(sim_options=sim_options)
rmse_cosine = cross_validate(algo, u1_ml100k, ['rmse'], pkf)['test_rmse']
sim_options = {'name': 'msd'}
algo = KNNBasic(sim_options=... | 5,294,156 |
def price_task(request):
""" Lista de nomes, datas e VALORES das tarefas"""
context = {}
cliente = request.user
try:
cliente = Cliente.objects.get(usuario=cliente)
# filter mostra como está a saida em __str__
# do models da classe
# cronograma = Cronograma.objects.filter(... | 5,294,157 |
def quotation_detail(request, quotation_id):
""" View to show all record detail for a particular quotation """
try:
quotation = get_object_or_404(Quotation, pk=quotation_id)
except Exception as e:
messages.error(request, f'ERROR: {e}')
return redirect(reverse('quotations'))
co... | 5,294,158 |
def li(content, value: str="", accesskey:str ="", class_: str ="", contenteditable: str ="",
data_key: str="", data_value: str="", dir_: str="", draggable: str="",
hidden: str="", id_: str="", lang: str="", spellcheck: str="",
style: str="", tabindex: str="", title: st... | 5,294,159 |
def get_relations() -> List[Dict[str, str]]:
"""
Get the relations used for annotation for this app.
"""
return configuration.relations | 5,294,160 |
def d2elam_met_loc_node(node):
""" Next locs and nodes. """
sub_node = node[1]
yield from d2exp_loc_node(sub_node) | 5,294,161 |
def sem():
"""Create and return SEM (base class) instance with default config."""
return SEM(config, sysconfig) | 5,294,162 |
def sort_by_color(e: Dict) -> float:
"""Sorting function, using a globally-declared color variable."""
return e[color] | 5,294,163 |
def get_texts_from_url_and_selector(url: str, selector: str) -> t.List[str]:
"""Get the texts of the elements found at the url and selector"""
elements = get_elements_from_url_and_selector(url=url, selector=selector)
texts = [element.text for element in elements]
return texts | 5,294,164 |
def concrete_post(update, state, expr = None):
""" Apply an update concretely (compute concrete post). ".
"""
# TODO: axioms could change as scope changes
axioms = state.domain.background_theory(state.in_scope)
# print "concrete post: axioms = {}".format(axioms)
cons = compose_state_action(s... | 5,294,165 |
def undying_base_critter_type():
"""Modifies the BaseCritter class to never die"""
original_tick_penalty = BaseCritter.HEALTH_TICK_PENALTY
yield BaseCritter
BaseCritter.HEALTH_TICK_PENALTY = original_tick_penalty | 5,294,166 |
def init(cluster: str = "ray"):
"""Initialize the global environment.
Args:
cluster: The distributed cluster.
Possible choices: {"local", "ray"}.
"""
global is_initialized
if is_initialized:
return
is_initialized = True
init_global_cluster(cluster) | 5,294,167 |
def flat_monte_carlo(func, z_min, z_max, epsilon):
"""
Operate Monte Carlo integration on specified function. Random numbers are generated with a flat distribution function.
----------
Input:
func: the function of integrand
z_min: lower limit of the integration
z_max: upper limit... | 5,294,168 |
async def main():
"""
Main function
Set up and start application
"""
# ------------------------------------------------------------------------------------------------------------------
TOKEN = os.environ['TOKEN']
# HEROKU_APP_NAME = os.getenv('HEROKU_APP_NAME')
MONGODATABASE_USER = o... | 5,294,169 |
def test_generate_header_body_str(header):
"""Test we can get correct header body strings.
Make sure we get the correct headers structure, because there are strict
requirements on the headers structure when requesting it.
"""
results = '[POST]tests.com:api_url&UTCTimestamp=32166266&accessId=xxx&ch... | 5,294,170 |
def hbp_fn():
"""Create a 2d convolution layer with HBP functionality."""
set_seeds(0)
return HBPConv2d(
in_channels,
out_channels,
kernel_size,
stride=stride,
padding=padding,
dilation=dilation,
bias=bias,
) | 5,294,171 |
def GetMonitorsRect() -> List[Rect]:
"""Return monitors rect"""
SM_CMONITORS = 80
monitorsCount = ctypes.windll.user32.GetSystemMetrics(SM_CMONITORS)
arrayType = ctypes.c_int * (monitorsCount * 4)
values = arrayType()
monitorsCount = _DllClient.instance().dll.GetMonitorsRect(values, monitorsCoun... | 5,294,172 |
def display_frames_as_gif(frames, filename_gif = None):
"""
Making GIF from continuous photos
"""
plt.figure(figsize=(frames[0].shape[1] / 72.0, frames[0].shape[0] / 72.0), dpi = 72)
patch = plt.imshow(frames[0])
plt.axis('off')
def animate(i):
patch.set_data(frames[i])
... | 5,294,173 |
def _get_model_maker(complete_conf, cache=True):
"""Locate and instantiate class of data-scientist-provided ModelMaker
(which the data scientist inherited from ModelMakerInterface).
For this to work, your model module (.py file) needs to be in python's
sys.path (usually the case).
Also set the confi... | 5,294,174 |
def main(_):
"""Run an interactive console."""
code.interact()
return 0 | 5,294,175 |
def fit_r_mdv_scipy(configure, experiments, numbers, vectors, matrixinv, func, flux, method = "SLSQP"):
"""Low level function for model fitting using scipy.optimize.minimize
Args:
configures (dict): "model.configures" including various configulatoins of the model.
experiments (dict): "model.e... | 5,294,176 |
def cli():
"""Provide a terminal interface to the package."""
pass | 5,294,177 |
def heapmerge(*inputs):
"""Like heapq.merge(), merges multiple sorted inputs (any iterables) into a single sorted output, but provides more convenient API:
each input is a pair of (iterable, label) and each yielded result is a pair of (item, label of the input) - so that it's known what input a given item origi... | 5,294,178 |
def histograma(img):
"""Calcula y representa el histograma de una imagen RGB.
Args:
img (Numpy array 3d): Un imagen RGB
Returns:
List: Devuelve una lista con el array del histograma de cada canal RGB.
Cada canal contendra un array de dos dimensiones, la primera contendra
la... | 5,294,179 |
def get_all_data(start=datetime.date(1970, 1, 1), end=datetime.date(2099, 12, 31)) -> pd.DataFrame:
"""得到一段日期内的全部信息"""
return _calendar.get_all_data(str(start), str(end)) | 5,294,180 |
def cli(ctx):
"""Simple template"""
# ------------------------------------------------
# imports
from os.path import join
from vframe.settings import app_cfg
# ------------------------------------------------
# start
log = app_cfg.LOG
log.info('Template info message')
log.debug('Template debug... | 5,294,181 |
def tb_extent(table, db='main'):
"""Get the extent of the table"""
data = []
try:
conn = psycopg2.connect(conn_str(db))
cur = conn.cursor()
sql = f"""
SELECT ST_AsText(ST_SetSRID(ST_Extent(st_transform(wkb_geometry, 4326)),
4326)) As bextent
FROM {table};"... | 5,294,182 |
def _avro_pfb_schema(azul_avro_schema: Iterable[JSON]) -> JSON:
"""
The boilerplate Avro schema that comprises a PFB's schema is returned in
this JSON literal below. This schema was copied from
https://github.com/uc-cdis/pypfb/blob/1497bf50e5c85201f6bad9ca69616138b17b8c77/src/pfb/writer.py#L85
:par... | 5,294,183 |
def _extend_job_info(connection, info):
"""Extends job info with connection/API related data."""
info['path'] = '/jobs/%s/%s' % (connection.id, info['uid'])
info['agent'] = {
'platform': connection.handshake_data[pagent.identity.KEY_PLATFORM],
'properties': connection.handshake_data[pagent.i... | 5,294,184 |
def get_timeseries_data_as_df(quantum:object, entity:object, attribute:str=None):
"""
:param quantum: An instance of quantumleap where the timeseries data should be obtained from
:param entity: The entity of which the data should be obtained
:param attribute: The attribute of which the data should be ... | 5,294,185 |
async def login_for_access_token(
form_data: OAuth2PasswordRequestForm = Depends(),
db: AsyncSession = Depends(get_db_session),
):
"""Generate and return a token"""
user = await crud.backend_user.authenticate(db=db, user_name=form_data.username, password=form_data.password)
# check if OK
if us... | 5,294,186 |
def test_launch_args():
"""test creating launch arguments - also test spot_instance"""
jobid = create_jobid()
log_bucket = 'tibanna-output'
input_dict = {'args': {'output_S3_bucket': 'somebucket',
'cwl_main_filename': 'md5.cwl',
'cwl_directory_url': ... | 5,294,187 |
def utc_float_to_pretty(utc_float=None, fmt=None, timezone=None):
"""Return the formatted version of utc_float
- fmt: a strftime format
- timezone: a timezone
If no utc_float is provided, a utc_float for "right now" will be used. If no
fmt is provided and admin_date_fmt is in settings.ini, setting... | 5,294,188 |
def run_test_practice_problem3e():
""" Tests the practice_problem3e function. """
# ------------------------------------------------------------------
# 5 tests. They use the imported simple_testing (st) module.
# Each test is a SimpleTestCase with 3 arguments:
# -- the function to test... | 5,294,189 |
def find_teacher(req: str):
"""
Find teacher
:param req: Request
:return: Search result as string
"""
if len(req) < 3:
return r_teacher_find_symbols
req_f = f"%{req.lower()}%"
res = cur.execute("SELECT * FROM teachers WHERE teacherClassSearchable LIKE ? LIMIT 5", (req_f,)).fetch... | 5,294,190 |
def shell(r:Union[RRef,DRef,Build,Path,str,None]=None, S=None)->None:
""" Open the Unix Shell in the directory associated with the argument passed.
Path to the shell executable is read from the `SHELL` environment variable,
defaulting to `/bin/sh`. If `r` is None, open the shell in the root of the
Pylightnix st... | 5,294,191 |
def reward_txs(wallet_info, exporter, progress):
""" Get reward transactions across all staking addresses for this wallet """
staking_addresses = wallet_info.get_staking_addresses()
wallet_address = wallet_info.wallet_address
for i, addr in enumerate(staking_addresses):
progress.report("staking... | 5,294,192 |
def pause_synchronization():
"""
Pauses synchronization of files from Artella server
"""
client = get_artella_client()
return client.pause_downloads() | 5,294,193 |
def get_and_tweet(args_book, no_tweet, config, local_now, play_dict):
"""
Get a cursor, get the play, check for books, send the tweet
"""
with db_cursor(config['db']) as cursor:
play = get_play(cursor, local_now, play_dict)
book_result = check_books_api(
args_book, config['p... | 5,294,194 |
def create_port_group(session, pg_name, vswitch_name, vlan_id=0, cluster=None):
"""Creates a port group on the host system with the vlan tags
supplied. VLAN id 0 means no vlan id association.
"""
client_factory = session._get_vim().client.factory
add_prt_grp_spec = vm_util.get_add_vswitch_port_group... | 5,294,195 |
def shortest_common_super_sequence(a, b):
"""
get the shortest common string for a and b
This cannot solve complex case like the one in the test case, when same
char repeats before the next common substring letter.
"""
def separate_by_char(letter, seq):
idx_seq = seq.find(letter)
... | 5,294,196 |
def test_platform():
"""Test instance of Platform. """
platform = Platform()
assert platform.pythonista is False | 5,294,197 |
def issue_column(argv=None):
"""
Moves an issue to the given column
"""
parser = argparse.ArgumentParser()
parser.add_argument('project', help='the project name')
parser.add_argument('issue_number', type=int, help='the issue tracker\'s issue number')
parser.add_argument('column', help='the ... | 5,294,198 |
def contains_carriage_return(text):
"""Check if carriage return is present."""
return "↵" in clean_string(text) | 5,294,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.