content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def all_main(settings_file, mode, campus, debug, skip):
"""Meta function to call the below in series, looping through campuses"""
config = filework.process_config(settings_file, campus)
skiplist = skip.split(sep=",") if skip else []
for local_campus in config["campus_list"]:
if local_camp... | 5,305,900 |
def maskToOrignimalImg(img,mask):
"""add mask to color image"""
if img.shape != mask.shape:
#mask = expandImageTo3chan(mask)
img = expandImageTo3chan(img)
#print(img.shape,mask.shape)
return cv2.addWeighted(img, 1.0, mask, 0.8, 0) | 5,305,901 |
def has_clockwise_orientation(vertices: Iterable['Vertex']) -> bool:
""" Returns True if 2D `vertices` have clockwise orientation. Ignores
z-axis of all vertices.
Args:
vertices: iterable of :class:`Vec2` compatible objects
Raises:
ValueError: less than 3 vertices
"""
vertices... | 5,305,902 |
def parse_views(data):
"""parse view count to .views"""
m = re.search("videoPlayCount: \d+", data)
return int(m.group(0)[16:]) | 5,305,903 |
def row_to_dict():
"""Convert pyspark.Row to dict for easier unordered comparison"""
def func(row, recursive=True):
return row.asDict(recursive=recursive)
return func | 5,305,904 |
def get_flask_celery_apps():
"""Call generate_context() and generate_config().
:return: First item is the Flask app instance, second is the Celery app instance.
:rtype: tuple
"""
config = generate_config()
flask_app = generate_context(config=config)
celery_app = flask_app.extensions['celery... | 5,305,905 |
def user_create(email, name, password, admin):
"""Create a new user."""
if email is False:
email = click.prompt('Enter the email')
if name is False:
name = click.prompt('Enter the name')
if password is False:
password = click.prompt('Enter the password', hide_input=True)
... | 5,305,906 |
def is_type_bitfld(*args):
"""
is_type_bitfld(t) -> bool
See 'BT_BITFIELD' .
@param t (C++: type_t)
"""
return _ida_typeinf.is_type_bitfld(*args) | 5,305,907 |
def cli(*args, **kwargs) -> None: # type: ignore
"""circulation-import is an application simplifying
the process of importing book collections into Circulation Manager"""
pass | 5,305,908 |
def check_and_fix_directory(dir_name):
"""This function is using for creating given directpry, if it is not exists."""
if not os.path.exists(dir_name):
os.mkdir(dir_name) | 5,305,909 |
def run_with_conf_and_verify(tmpdir, conf_filename, verification_func):
"""Verifies that a workload simulation executes correctly.
Args:
tmpdir: The path to a temporary directory where the Scheduler's Worker can store its
continuous monitor file. The caller is responsible for cleaning up this directory.
... | 5,305,910 |
def distance_histograms(image, block_size):
"""obtaining 10-bin histograms of centroid distances"""
otsu_global_labels = global_labels(image)
local_adaptive_labels = local_labels(image, block_size)
properties_global = measure.regionprops(otsu_global_labels)
properties_local = measure.regionprops(loc... | 5,305,911 |
def subpool_map(pool_size, func, iterable):
""" Starts a Gevent pool and run a map. Takes care of setting current_job and cleaning up. """
if not pool_size:
return [func(*args) for args in iterable]
counter = itertools_count()
current_job = get_current_job()
def inner_func(*args):
... | 5,305,912 |
def test_global_efficiency():
"""
The following test checks global efficiency before any perturbation.
"""
g = ParallelGeneralGraph()
g.load("tests/TOY_graph.csv")
np.testing.assert_almost_equal(g.global_efficiency, 0.1759191750419821,
err_msg="ORIGINAL GLOBAL EFFICIENCY failure") | 5,305,913 |
def parse_xiaogui(self, data, source_mac, rssi):
"""Xiaogui Scales parser"""
msg_length = len(data)
if msg_length == 17:
firmware = "Xiaogui"
xiaogui_mac = data[11:]
if xiaogui_mac != source_mac:
_LOGGER.error("Xiaogui MAC address doesn't match data MAC address. Data: %... | 5,305,914 |
def eval_function(dataset, function, functions):
"""Evaluate a given function on a dataset.
This function parses and evaluates a (possibly nested) function call,
returning its result.
"""
name, args = FUNCTION.match(function).groups()
def tokenize(input):
start = pos = count = 0
... | 5,305,915 |
def mesh_borehole(*, hole_diameter=1):
"""
Mesh the borehole geometry.
See https://en.wikipedia.org/wiki/Snell%27s_law
Parameters
----------
hole_diameter : float
Diameter of the borehole.
Returns
-------
theta : float
refraction angle
Examples
--------
... | 5,305,916 |
def RSI(data, period=14, price='close'):
"""
Relative Strength Index
RSI is a momentum oscillator that measures the speed and change of price movements.
RSI oscillates between zero and 100. Traditionally, and according to Wilder, RSI is considered overbought when
above 70 and oversold when below 3... | 5,305,917 |
def qrscaner():
"""Render template with QR scanner."""
title = 'Сканер'
return render_template(
'receipt/qrscaner.html',
page_title=title,
) | 5,305,918 |
def get_extrinsics(sim, cam_name):
"""
TODO: for some reason this returns me the -ve z-axis
fix that
TODO: also the extrinsic is correct for the flipped images
fix that too
"""
pos = sim.data.get_camera_xpos(cam_name)
mat = sim.data.get_camera_xmat(cam_name)
... | 5,305,919 |
def ConvertVFSGRRClient(client):
"""Converts from `VFSGRRClient` to `rdfvalues.objects.ClientSnapshot`."""
snapshot = rdf_objects.ClientSnapshot(client_id=client.urn.Basename())
snapshot.filesystems = client.Get(client.Schema.FILESYSTEM)
snapshot.hostname = client.Get(client.Schema.HOSTNAME)
snapshot.fqdn = ... | 5,305,920 |
def validate_trigger(config: Config, trigger: client.models.v1_config_map.V1ConfigMap) -> bool:
"""Evaluate trigger ConfigMap age, returning True if valid."""
cm_ts = trigger.metadata.creation_timestamp.timestamp()
now = datetime.now().timestamp()
return cm_ts + config.trigger_max_age >= now | 5,305,921 |
def add_encryption_layer(api_client, encryption_conf_file):
"""Decorate APIClient.call_api with field level encryption"""
api_encryption = ApiEncryption(encryption_conf_file)
api_client.request = api_encryption.field_encryption(api_client.request)
api_client.call_api = api_encryption.field_encryption_c... | 5,305,922 |
def PrepareLocalPatches(manifest, patches):
"""Finish validation of parameters, and save patches to a temp folder.
Args:
manifest: The manifest object for the checkout in question.
patches: A list of user-specified patches, in project[:branch] form.
"""
patch_info = []
for patch in _CheckLocalPatches... | 5,305,923 |
def update_hsl_value(color, hue=None, sat=None, lum=None, inmodel=HSL, outmodel=HSL):
"""Change hue, saturation, or lumenosity of the color based on the
hue, sat, lum parameters provided.
Parameters:
color (Any):
The color
hue (int):
A number between 0 and 360.... | 5,305,924 |
def is_datetime64_dtype(arr_or_dtype: List[Literal["d", "a", "b", "c"]]):
"""
usage.seaborn: 1
"""
... | 5,305,925 |
def main():
"""GUI LOGIN PAGE"""
st.set_page_config(page_title="GEA Calendar")
st.image("resource/ltts.png")
st.subheader(f"{greeting()} Welcome to GEA calendar automation app")
st.sidebar.title("GEA calendar automation")
st.sidebar.image("resource/gea.jpg")
info = st.sidebar.selectbox("Info... | 5,305,926 |
def get_fits_image(fimage):
"""
reads fits image data and header
fimage: filename with or without extension
converts 32-bit floating values and 16-bit data to Python compatible values
reads also color images and transposes matrix to correct order
(normalizes images to +/- 1 range)
ret... | 5,305,927 |
def morph_trans(original_images, transformation):
"""
Apply morphological transformations on images.
:param: original_images - the images to applied transformations on.
:param: transformation - the standard transformation to apply.
:return: the transformed dataset.
"""
if MODE.DEBUG:
... | 5,305,928 |
def plot_histograms(ax, prng, nb_samples=10000):
"""Plot 4 histograms and a text annotation.
"""
params = ((10, 10), (4, 12), (50, 12), (6, 55))
for a, b in params:
values = prng.beta(a, b, size=nb_samples)
ax.hist(values, histtype="stepfilled", bins=30,
alpha=0.8)#, dens... | 5,305,929 |
def cleanup(wd, initdir, wrflag, rmwkdir):
""" cleanup function """
tolog("Overall cleanup function is called")
# collect any zombie processes
wd.collectZombieJob(tn=10)
tolog("Collected zombie processes")
# get the current work dir
wkdir = readStringFromFile(os.path.join(initdir, "CURRENT... | 5,305,930 |
def render_rays_sm(img_idx,
chain_bwd,
chain_5frames,
num_img,
ray_batch,
network_fn,
network_query_fn,
rigid_network_query_fn,
N_samples,
retraw=False,
lindi... | 5,305,931 |
def generate_locations(
staypoints,
method="dbscan",
epsilon=100,
num_samples=1,
distance_metric="haversine",
agg_level="user",
print_progress=False,
):
"""
Generate locations from the staypoints.
Parameters
----------
staypoints : GeoDataFrame (as trackintel staypoints)... | 5,305,932 |
def expand(im, filter_vec):
"""
Zero pads and blurs an image to expand it by 2
:param im: a grayscale image with double values in [0,1]
:param filter_vec: row vector of shape(1, filter_size) to blur with
:return: expanded image
"""
expanded_im = np.zeros((2 * im.shape[0], 2 * im.shape[1])) ... | 5,305,933 |
def candidacy(request):
"""Generate a page to choose and request candidacy among the legal ones."""
# TODO Lots of unnecessary SQL queries; subgroups sorted by network should be queried all at once.
user = request.user
user_of_subgroups = m.Subgroup.objects.filter(users__in=[user])
candidacies = m.C... | 5,305,934 |
def apply_dof_transformation_hexahedron(
entity_transformations: _Dict[str, _npt.NDArray[_np.float64]], entity_dofs: _Dict[str, _npt.NDArray[_np.int32]],
data: _np.array, cell_info: int
):
"""Apply dof transformations to some data on a hexahedron.
Args:
entity_transformations: The DOF transform... | 5,305,935 |
def calc_f2_score(gt_bboxes_list, pred_bboxes_list, verbose=False):
"""
gt_bboxes_list: list of (N, 4) np.array in xywh format
pred_bboxes_list: list of (N, 5) np.array in conf+xywh format
"""
#f2s = []
f2_dict = {'f2':0, "P":0, "R": 0}
all_tps = [list([0] * 11) for _ in range(len(gt_bboxes... | 5,305,936 |
def decode(serialized_example):
"""
Parses an image and label from the given `serialized_example`
:param serialized_example:
:return:
"""
features = tf.parse_single_example(
serialized_example,
# Defaults are not specified since both keys are required.
features={
... | 5,305,937 |
def test_tempdir():
"""Test TempDir."""
tempdir2 = _TempDir()
assert (op.isdir(tempdir2))
x = str(tempdir2)
del tempdir2
assert (not op.isdir(x)) | 5,305,938 |
def dateformated(x):
"""
===========================================================
dateformated(x)
===========================================================
this function converts the the date read from a list to a datetime format
input:
x is a list of tuples of string date ... | 5,305,939 |
def comboBox(
widget,
master,
value,
box=None,
label=None,
labelWidth=None,
orientation=Qt.Vertical,
items=(),
callback=None,
sendSelectedValue=False,
valueType=str,
emptyString=None,
editable=False,
contentsLength=None,
maximumContentsLength=25,
**misc
):... | 5,305,940 |
def emit_run(wf, jarname):
"""Emit command to invoke VM on jar."""
intflag = ""
wrap_run = ""
if flag_strace:
wrap_run = "strace -f -o /data/local/tmp/run-trace.txt "
if flag_simpleperf:
aarg = ""
sp = "simpleperf"
if flag_simpleperf_systemwide:
aarg = "-a "
if flag_simpleperf_static... | 5,305,941 |
def lowerbranch_subtract(X):
"""Function to subtract lower hysteresis branch from FORC magnetizations
Inputs:
H: Measurement applied field [float, SI units]
Hr: Reversal field [float, SI units]
M: Measured magnetization [float, SI units]
Fk: Index of measured FORC (int)
Fj: Index of giv... | 5,305,942 |
def load_annotated_project(project_root_path):
"""
loads annotated symbols into a set of ModuleSymbols
:param project_root_path: symbols we will use to write out new source code
:return: set of ModuleSymbols objects
"""
return load_modules_into_module_symbol_objects(project_root_path,
... | 5,305,943 |
def verify_annotation(ann_obj, projectconf):
"""
Verifies the correctness of a given AnnotationFile.
Returns a list of AnnotationIssues.
"""
issues = []
issues += verify_annotation_types(ann_obj, projectconf)
issues += verify_equivs(ann_obj, projectconf)
issues += verify_entity_overla... | 5,305,944 |
def statesCheck(accessible, control, invalid_states=[],
add_states=[], pause=True):
"""Check the states of an accessible using the default states
of the accessible (specified by control class in states.py) as
the default expected states.
Keyword arguments:... | 5,305,945 |
def schedule_conv2d_nhwc_winograd_tensorcore_without_weight_transform(cfg, outs):
"""TOPI schedule callback"""
s = te.create_schedule([x.op for x in outs])
def _callback(op):
if "conv2d_nhwc_winograd" in op.tag:
schedule_nhwc_winograd_cuda(
cfg, s, op.output(0), use_tens... | 5,305,946 |
def encode_dataset(dataset, vocabulary):
"""Encode from strings to token ids.
Args:
dataset: a tf.data.Dataset with string values.
vocabulary: a mesh_tensorflow.transformer.Vocabulary
Returns:
a tf.data.Dataset with integer-vector values ending in EOS=1
"""
def encode(features):
return {k: vo... | 5,305,947 |
def test_load_checks():
"""Loading checks should load and return Python modules."""
modules = load_checks()
assert modules | 5,305,948 |
def now():
"""
Get current time.
:return: now as datetime with timezone
"""
return datetime.now(UTC) | 5,305,949 |
def confirmOverDrive(autoRespond):
""" Print the warning for OverDrive functionality and prompt user to accept the terms.
Parameters:
autoRespond -- Response to automatically provide for all prompts
"""
print('''
******WARNING******\n
Operating your AMD GPU outside of official ... | 5,305,950 |
def game_score(score):
""" Prints SCORE and the player's score when the player loses """
game_score_font_size = 80
game_score_font = pygame.font.SysFont('impact', game_score_font_size)
game_score_pos = (170,300)
game_score_text = game_score_font.render("Score", True, purple)
... | 5,305,951 |
def CallGraphToFunctionCallCounts(g: nx.MultiDiGraph,) -> typing.Dict[str, int]:
"""Build a table of call counts for each function.
Args:
g: A call graph, such as produced by LLVM's -dot-callgraph pass.
See CallGraphFromDotSource().
Returns:
A dictionary where each function in the graph is a key, ... | 5,305,952 |
def create_multi_stores(conf=CONF, reserved_stores=None):
"""
Registers all store modules and all schemes from the given configuration
object.
:param conf: A oslo_config (or compatible) object
:param reserved_stores: A list of stores for the consuming service's
internal ... | 5,305,953 |
def decompose(args):
"""
Make a decomposition of the energy into some if its residue components.
"""
if args.resList is None:
msg = 'TERMINATED. List of residues not provided.'
logging.info(msg)
return None
gmx = search_commands(['gmx', 'gmx_mpi'], args.gmxEnv)
if gmx is... | 5,305,954 |
def define_generator(image_shape, n_resnet):
"""
Creates the generator
:param image_shape: shape of the input image
:param n_resnet: Number of resnet blocks
:return: generator model
"""
# Weight initialization
init = RandomNormal(stddev=0.02)
# Image input
in_image = Input(shape... | 5,305,955 |
def duplicates_allclose(dataframe, dcols, fcols):
"""Determine duplicates in dataframe based on tolerances
Args:
dataframe: the dataframe
dcols: the columns that are tested for exact duplicates
fcols: the columns that are checked for tolerance, dict with
tolerances
This is the si... | 5,305,956 |
def base_app(tmp_shared_volume_path):
"""Flask application fixture."""
config_mapping = {
"SERVER_NAME": "localhost:5000",
"SECRET_KEY": "SECRET_KEY",
"TESTING": True,
"SHARED_VOLUME_PATH": tmp_shared_volume_path,
"SQLALCHEMY_DATABASE_URI": os.getenv("REANA_SQLALCHEMY_DAT... | 5,305,957 |
def unlock_version_dir(vdir):
"""Unlock the given version dir, allowing it to be uninstalled."""
os_close(_locked_version_dirs[vdir].pop()) | 5,305,958 |
def get_topic_summary_by_id(topic_id, strict=True):
"""Returns a domain object representing a topic summary.
Args:
topic_id: str. ID of the topic summary.
strict: bool. Whether to fail noisily if no topic summary with the given
id exists in the datastore.
Returns:
Topic... | 5,305,959 |
def update(state: State, grid: Grid, parameters: Parameters, config: Benedict) -> None:
"""Advance the simulation one timestamp.
Args:
state (State): the current model state; will be mutated
grid (Grid): the model grid
parameters (Parameters): the model parameters
config (Benedi... | 5,305,960 |
def smoothing_Negative_rx0(MSK, Hobs, rx0max):
"""
This program use an opposite methode to the direct iterative method from
Martinho and Batteen (2006). This program optimizes the bathymetry for
a given rx0 factor by decreasing it.
Usage:
RetBathy = smoothing_Negative_rx0(MSK, Hobs, rx0max)
... | 5,305,961 |
def adjust_learning_rate(optimizer, gamma, step):
"""Sets the learning rate to the initial LR decayed by 10 at every
specified step
# Adapted from PyTorch Imagenet example:
# https://github.com/pytorch/examples/blob/master/imagenet/main.py
"""
lr = args.lr * (0.8 ** step)
print(lr)
f... | 5,305,962 |
def cgraphics_vec_to_RGBangle(source, w, h, cm, colorcorrect):
"""Pixelwise conversion of a 2D vectors to RGB angular image.
This is especially useful for optic-flow visualization.
Parameter
---------
source : numpy array [2 * dim_x * dim_y]
The 2D vector image of resolution dim_x x dim_y.... | 5,305,963 |
def get_port():
"""Returns a port number."""
return 0 | 5,305,964 |
def add_images(img_1, img_2):
"""
Open CV 相加如果两张图片大小相同则会使用 pairwise
如果第二个参数使一个 scalar 则会使用 element-wise 相加
"""
if img_1.shape == img_2.shape:
sum_img = cv2.add(img_1, img_2)
cv2.imshow('Summed Image', sum_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
scaled_img... | 5,305,965 |
def test_task_init_3(splitter, state_splitter, state_rpn, states_ind, states_val):
""" task with inputs and splitter"""
nn = fun_addtwo(name="NA", a=[3, 5]).split(splitter=splitter)
assert np.allclose(nn.inputs.a, [3, 5])
assert nn.state.splitter == state_splitter
assert nn.state.splitter_rpn == st... | 5,305,966 |
def test_ptdx():
""" OK """
rv, out = getstatusoutput(f'{PRG} -w {DICT3} ptdx patientdiagnosis')
assert rv == 0
expected = '\n'.join(['pt + dx', 'patient + diagnosis'])
assert out == expected | 5,305,967 |
def return_car_dict(car: Car):
"""
Returns a Car Object as dictionary
:param car: The car object being formatted
:return: Returns the car object formatted to return as dictionary
"""
riders = []
for rider in car.riders:
riders.append(rider.username)
return {
'id': car.id,... | 5,305,968 |
def sort_unique(edges):
"""Make sure there are no duplicate edges and that for each
``coo_a < coo_b``.
"""
return tuple(sorted(
tuple(sorted(edge))
for edge in set(map(frozenset, edges))
)) | 5,305,969 |
def ext_subtable23(cxt: DecoderContext, fmt: Format):
""" EI | DI | SYSCALL | CLL | PUSHSP | POPSP | undef """
if fmt.lo5 == 0 and fmt.ext_hi5 == 0 and fmt.ext_lo5 == 0:
ff_hi = fmt[15:14]
ff_lo = fmt[13:11]
mnem = [[MNEM.DI] + [MNEM.UNDEF_CODE] * 3,
[MNEM.UNDEF_CODE] * 4... | 5,305,970 |
def if_else(vector: np.ndarray) -> np.ndarray:
"""Copies vector but sets elements lower than 3 to 0
Parameters
----------
vector : np.ndarray
shape = (n, )
Returns
-------
np.ndarray
shape = (n, )
Examples
--------
>>> a = np.array([1, 2, 3, 4, 5, 6])
>>> i... | 5,305,971 |
async def test_get_location(vehicle: RenaultVehicle) -> None:
"""Test get_location."""
with aioresponses() as mocked_responses:
mocked_responses.get(
f"{TEST_KAMEREON_VEHICLE_URL1}/location?{QUERY_STRING}",
status=200,
body=get_file_content(f"{FIXTURE_PATH}/vehicle_da... | 5,305,972 |
def daast_from_file(filename, args=None):
"""Generates DistAlgo AST from source file.
'filename' is the filename of source file. Optional argument 'args' is a
Namespace object containing the command line parameters for the compiler.
Returns the generated DistAlgo AST.
"""
try:
with ope... | 5,305,973 |
def plot_roc_auc_f1(y_test, y_proba, title=None):
"""Plot ROC curve and random comparison, along with f1 and AUC metrics"""
std_f1 = f1_score(y_test, y_proba[:, 1] > 0.5)
fpr, tpr, _ = roc_curve(y_test, y_proba[:, 1])
auc_score = auc(fpr, tpr)
fig, axis = plt.subplots(figsize=(6, 6))
if title is... | 5,305,974 |
def get_var_names(var_name):
"""Defines replacement dictionary for the bare variable name and
the names derived from it - the optimization flag and the identifier name.
"""
repl = dict()
repl['opt_var_name'] = "Opt_%s"%var_name
repl['id_var_name'] = "ID_%s"%var_name
repl['var_name'] = var_name
return... | 5,305,975 |
def WriteZipFile(zip_path, zip_contents):
"""Writes the provided contents to the given zip file.
Note that this uses python's zipfile module and is done in a separate
process to avoid hogging the GIL.
Args:
zip_path: String path to the zip file to write.
zip_contents: A list of (host path, archive pat... | 5,305,976 |
def params(args):
"""
Implement functionality for 'params' command
"""
analysis_dir = args.analysis_dir
if not analysis_dir:
analysis_dir = os.getcwd()
d = AutoProcess(analysis_dir,allow_save_params=False)
# Update the project-specific parameters
if args.key_value is not None:
... | 5,305,977 |
def progressbar(it, prefix="", size=60, file=sys.stdout):
"""A super simple progressbar.
Args:
it ([type]): [description]
prefix (str, optional): [description]. Defaults to "".
size (int, optional): [description]. Defaults to 60.
file ([type], optional): [description]. Defaults ... | 5,305,978 |
def hubble_parameter(z):
"""
It calculates the Hubble parameter at any redshift.
"""
part = np.sqrt(const.Omega0*(1.+z)**3+const.lam)
return const.H0 * part | 5,305,979 |
def worker_init_fn(worker_id, seed=0):
"""Helper to make random number generation independent in each process."""
np.random.seed(8*seed + worker_id) | 5,305,980 |
def default_output_name(input_name):
"""Return the default output name for the specified input name.
This function is invoked when no ``--output`` option is specified
(see the documentation of this option for further details).
"""
tokens = os.path.split(input_name)
basename = (tokens[-1][:-len(... | 5,305,981 |
def is_valid_snmp_v2_credential(credential):
"""check if credential is valid snmp v2 credential."""
if credential.keys() != SNMP_V2_CREDENTIALS.keys():
return False
if credential['version'] != '2c':
logging.error("The value of version in credential is not '2c'!")
return False
ret... | 5,305,982 |
def test_remove_existing_last_key(mocker):
"""
Given:
- a nonempty list with 1 value
- a key that exists in the list (the only one that exists)
When
- trying to remove the last key of the list
Then
- requested key is removed from list
- list is empty
"""
M... | 5,305,983 |
def test_marker(testdir, module, kwargs, outcomes):
"""Test that the requires marker works properly
"""
testdir.makepyfile("""
import pytest
@pytest.mark.requires('{module}', **{kwargs})
def test_one():
pass
""".format(module=module, kwargs=kwargs))
result = tes... | 5,305,984 |
def setup_bucket(
add_model=False, add_mm=False, add_tests=False,
add_results=False, add_model_stats=False, add_test_stats=False):
"""
This function creates a new (local) bucket mocking S3 bucket at each call.
Then all calls to S3 are calling this bucket instead of real S3 bucket.
Depend... | 5,305,985 |
def get_school_deadlines(college):
"""Get the admissions deadlines for the provided college."""
if college:
college = college.lower()
for deadline in DEADLINES:
if college in deadline.lower():
return statement(deadline)
return statement(
'Sorry, we are sti... | 5,305,986 |
def function_grandkids_cell():
"""Returns string see usage"""
return "\n".join(["F1 is a function", "F1a is a function", "F1a1 is a function",
"F1 is composed of F1a", "F1a is composed of F1a1", "a is a data",
"F1a produces a", "b is a data", "F1a consumes b", "c is a... | 5,305,987 |
def insert_sort(s):
"""Sort list of comparable elements into nondecreasing order."""
for k in range(1, len(s)):
while k > 0:
if s[k] > s[k - 1]:
break
s[k], s[k - 1] = s[k - 1], s[k]
k -= 1 | 5,305,988 |
def euclidean(matrix, vector, assure_consistency=False):
"""
Calculate inversed euclidean distance for all words in matrix against vector.
"""
if assure_consistency:
vector = _assure_consistency(matrix, vector)
inv_euc= 1/(1+matrix.subtract(vector).norm(axis=1))
return inv_euc.sort(ascen... | 5,305,989 |
def banner():
"""Prints a figlet type banner"""
print("""\033[92m
_____ _ _ _ _____ _____
| | | | |_ _| __|
| | | | | | | | | __|
|_____|_____| |_| |__|
@owtfp
http://owtf.org
\033[0m""") | 5,305,990 |
def search(dict, post, queries, out):
"""
Gets the dictionary, gets the queries, gets the lengths, gets the synonyms
for each term in the query and then evalutes the query. The method used to
evaluate the query depends on if the query is positional or not
"""
print ("testing s... | 5,305,991 |
def alfred_items_for_value(value):
"""
Given a Chinese language string, return a list of alfred items for each of the results
"""
index = 0
results = []
config_list = [
('t2s.json', u'繁體到簡體', 'SimplifiedChinese.png'),
('s2t.json', u'簡體到繁體', 'TraditionalChinese.png'),
('s... | 5,305,992 |
def preprocess_caption(row, mode):
"""Applies the selected preprocessing steps to the text.
Args:
row: A UTF-8 string.
mode: A string indicating the selected preprocessing strategy.
Valid values include: 'no_preprocessing' (no preprocessing),
'rm_all' (remove al... | 5,305,993 |
def encode(val, base, minlen=0):
"""Returns the encoded string"""
code_string = get_code_string(base)
result = ""
while val > 0:
result = code_string[val % base] + result
val /= base
if len(result) < minlen:
result = code_string[0] * (minlen - len(result)) + result
return... | 5,305,994 |
def parse_header_links(value: str) -> List[Dict[str, str]]:
"""
Returns a list of parsed link headers, for more info see:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link
The generic syntax of those is:
::
Link: < uri-reference >; param1=value1; param2="value2"
So for i... | 5,305,995 |
def register_instances_with_load_balancer(LoadBalancerName=None, Instances=None):
"""
Adds the specified instances to the specified load balancer.
The instance must be a running instance in the same network as the load balancer (EC2-Classic or the same VPC). If you have EC2-Classic instances and a load bala... | 5,305,996 |
def main(testsuite_list, project_repository, data_repository,
auto_defects=False, ts_parallel=True):
"""Executes the list of testcases in parallel
Computes and returns the testsuite status"""
try:
project_status = execute_parallel_testsuites(testsuite_list, project_repository,
... | 5,305,997 |
def find_function_def_nodes(node: ast.Module) -> List[ast.FunctionDef]:
"""Finds ast.FunctionDef nodes in the source code. ast.FunctionDef
represents `def function_name(....):` statement in the code.
Args:
node: a root node of the AST tree, this node should be a AST representation
of th... | 5,305,998 |
def test_str_list_types(option_value, expected):
"""
Some config settings have two types, str and list. In that case, list,
tuple, str, bool, int, float, and None should evaluate as True. All others
should return False.
master is a str, list type config option
"""
result = salt.config._valid... | 5,305,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.