content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def less_or_equal(a, b, *args):
"""Implements the '<=' operator with JS-style type coertion."""
return (
less(a, b) or soft_equals(a, b)
) and (not args or less_or_equal(b, *args)) | 5,298,800 |
def load_env_file(candidate_path_list=ENV_PATHS):
"""Load configuration from environment file.
Keyword arguments:
candidate_path_list: List of paths to try to read configuration from;
first readable will be used.
If none exists, a warning will be issued.
"""
for candida... | 5,298,801 |
def test_hadolint_tool_plugin_scan_docker_duplicate_format():
"""Integration test: Make sure the plugin handles json errors."""
plugin = setup_hadolint_tool_plugin(use_docker=True, package_dir="duplicate_format")
if not plugin.command_exists("docker"):
pytest.skip("Missing docker executable, skippin... | 5,298,802 |
def survey_getQuestionFromCode(code, series_id=None):
"""
Function to return the question for the given series
with the code that matches the one passed in
"""
s3db = current.s3db
sertable = s3db.survey_series
q_ltable = s3db.survey_question_list
qsntable = s3db.survey_question
... | 5,298,803 |
def init_args():
"""
:return:
"""
parser = argparse.ArgumentParser()
parser.add_argument('--imgs_pth', type=str, help='The images path',
default='../m2nist/combined.npy')
parser.add_argument('--weights_pth', type=str, help='The model weights path',
... | 5,298,804 |
def write_clusters_for_all_samples(samplelist):
"""
Writes a summary file of clustering for a large set of samples.
Arguments:
sampleList (list of strings): A list of samples to cluster.
"""
f = open("all_sample_clusters.txt", 'w')
f.write("#length\tmeanRD\tmeanBAF\tclassification\n")
for sample in samplelis... | 5,298,805 |
def get_cityscapes_file_pairs(split='train', city='*', sequence='*',
frame='*', ext='.*', gt_type='labelTrainIds', type='leftImg8bit',
root_folder=CITYSCAPES_FOLDER, file_template=CITYSCAPES_FILE_TEMPLATE):
"""
Fetch pairs of filenames for the Citysca... | 5,298,806 |
def test_CRAM16():
"""Test 16-term CRAM."""
x = np.array([1.0, 1.0])
mat = sp.csr_matrix([[-1.0, 0.0], [-2.0, -3.0]])
dt = 0.1
z = CRAM16(mat, x, dt)
# Solution from mathematica
z0 = np.array((0.904837418035960, 0.576799023327476))
assert z == approx(z0) | 5,298,807 |
def OT_retrieve_optfile(filename, mode='rsync-ssh', keyfile='', args='', sshargs=''):
"""
retrieve_optfile(...) is identical to retrieve_file(...), except
that it returns a tuple that can be passed to optfile(...) that
contains both the temporary file and ``filename``, thus indicating
``filename`` ... | 5,298,808 |
def vcf_to_sparse(outDir, inFeaID, inFeaBed, inVcf, featureID):
"""
convert the vcf to a feature matrix, `matrix.mtx`
:param outDir: output directory
:param inFeaID: `13885fea_exon_cut_100bp_2sample.txt` in dependency_data
:param inFeaBed: `tcga_13885fea_exon_cut_100bp.bed` in dependency_data
:p... | 5,298,809 |
def test_bounds_optional():
"""Test that each object template can have passthrough bounds for any of its attributes."""
def link():
return LinkByUID(id=str(uuid4()), scope=str(uuid4()))
for template_type, attribute_args in [
(MaterialTemplate, [
('properties', PropertyTemplate),
... | 5,298,810 |
def manage_filebeat_logstash_ssl():
"""Manage the ssl cert/key that filebeat uses to connect to logstash.
Create the cert/key files when both logstash_ssl options have been set;
update when either config option changes; remove if either gets unset.
"""
logstash_ssl_cert = config().get('logstash_ssl... | 5,298,811 |
def is_session_active_api(request):
"""
API endpoint that tells if user has active session.
"""
user_id = request.user.id if request.user.is_authenticated else None
return HttpResponse(json.dumps({'success': request.user.is_authenticated,
'user_id': user_id}),
... | 5,298,812 |
def high_precision_keyword_read(hdr, keyword):
"""Read FITS header keywords, also if split in two.
In the case where the keyword is split in two, like
MJDREF = MJDREFI + MJDREFF
in some missions, this function returns the summed value. Otherwise, the
content of the single keyword
Paramet... | 5,298,813 |
def build_assign_term_to_entities_request(
term_guid, # type: str
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Assign the given term to the provided list of related objects.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder into your code f... | 5,298,814 |
def calc_skier_position(skierposition,userinput):
"""
"""
if userinput == "j":
skierposition = skierposition - 1
if userinput == "k":
skierposition = skierposition + 1
return skierposition | 5,298,815 |
def SetMacroAlias(aliasname: str, obj):
"""
Sets the value of the given alias name, alias is valid only in the current macro.
:param aliasname: Alias name.
:param obj: An entity serial in integer or hex format, or an alias string such as "self".
"""
pass | 5,298,816 |
def main():
""" add_nodes main loop """
cfgs = defaultdict(str)
# handle parser option
options = get_options()
if not options.nodes:
err_m('Must specifiy the node names using \'--nodes\' option')
# get node list from user input
new_nodes = expNumRe(options.nodes)
if not new_nod... | 5,298,817 |
def intersect_plane_with_box(tshape, plane_def):
"""For each 'unknown' dimension, let the knowns be the other dimensions.
The known ones define the edges of the box.
Then find the unknown by the plane-equation.
But this gives also out-of-box points, so filter them out.
"""
normal,d = plane... | 5,298,818 |
def _get_command_powershell_script(command):
"""Return a valid CMD command that runs a powershell script."""
return "powershell -NonInteractive -NoLogo -File {}".format(command) | 5,298,819 |
def _getProductPath(product_name):
""" Return the absolute path of the product's directory.
"""
try:
# BBB: for GenericSetup 1.1 style product names
product = __import__('Products.%s' % product_name, globals(), {},
['initialize'])
except ImportError:
... | 5,298,820 |
def get_commit_sheet(
access_key: str,
url: str,
owner: str,
dataset: str,
*,
commit_id: str,
sheet: str,
with_record_count: Optional[bool] = None,
schema_format: Optional[str] = None,
) -> Dict[str, Any]:
"""Execute the OpenAPI `GET /v2/datasets/{owner}/{dataset}/commits/{commit... | 5,298,821 |
def _run_upload(client, options, args):
"""Upload a sites page.
Really, we read the file and pass the contents up in the call.
Yuck, but that's the API. We draft the doc parameters:
title: page title. Used to create page_name. Default: filename.
src: File to read from.
format: Site's "... | 5,298,822 |
def get_transport_and_path_from_url(url, config=None, **kwargs):
"""Obtain a git client from a URL.
:param url: URL to open (a unicode string)
:param config: Optional config object
:param thin_packs: Whether or not thin packs should be retrieved
:param report_activity: Optional callback for reporti... | 5,298,823 |
def fix_owner_and_timestamp(path, uid, t):
"""
:param str path:
:param int uid:
:param int | float t:
:return:
"""
os.chown(path, uid, -1)
os.utime(path, (t, t)) | 5,298,824 |
def getModelSupportTypes(data):
"""
获取模型支持的分类
:return:
"""
temp = ''
for i in data:
temp = temp + ' ' + i
return temp | 5,298,825 |
async def test_action(opp, calls, enable_custom_integrations):
"""Test for turn_on and turn_off actions."""
platform = getattr(opp.components, f"test.{DOMAIN}")
platform.init()
assert await async_setup_component(opp, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await opp.async_block_till_done()
... | 5,298,826 |
def get_function_argument_names_from_source_code(source_code: str) -> List[str]:
"""
Gets the names of the function arguments found in a particular line of source code.
Specifically, it retrieves the names of the arguments in the first function call found in the source code string.
If the source code ... | 5,298,827 |
def load_image(addr, resizeSize=None, imgType=np.float32):
"""Read an image and make sure it is of the correct type. Optionally resize it"""
try:
img = imread(addr, mode='F')
except:
img = 0.5*np.ones((512,512))
print("Image read failed")
if resizeSize:
im... | 5,298,828 |
def queue_count(queue_name: str = QUEUE_NAME) -> int:
""" Display the number of messages in SQS queue """
logger.info("Getting queue messages count...")
try:
sqs = boto3.client("sqs")
queues = sqs.list_queues(QueueNamePrefix=queue_name)
queue_url = queues["QueueUrls"][0]
re... | 5,298,829 |
def check_monit(dut):
"""
@summary: Check whether the Monit is running and whether the services which were monitored by Monit are
in the correct status or not.
@return: A dictionary contains the testing result (failed or not failed) and the status of each service.
"""
logger.info("Che... | 5,298,830 |
def generator(T):
"""Mark a class as a generator"""
class generator_interposer(T):
def __init__(self, *args, **kwargs):
gen_i = self._get_int()
# Capture the instantiation location
frame = inspect.stack()[1]
gen_i.srcinfo_inst = ... | 5,298,831 |
def hausdorff_distance(polyline1,polyline2):
"""
Compute the hausdorff distance from `polyline1` to `polyline2`
:Inputs:
`polyline1`:
a (k,n1) array for the n1 points of the 1st polyline in k-dimension
`polyline2`:
a (k,n2) array for the n2 points of the 2nd polyline in k... | 5,298,832 |
def combine_two_nets(N_1,N_2):
""" combines two networks and returns the new network and its POs
For the moment each net can have only a single PO """
if N_1 == []:
return N_2
if N_2 == 0:
return N_1
N, (xlat_1, xlat_2) = pyzz.combine_cones(N_1, N_2)
POs_N1 = list(N_1.get_POs())
... | 5,298,833 |
def merge_collected_sets(a: Column, b: Column):
"""Merge 2 collected sets keeping only unique items"""
def merge_col(list_a, list_b):
set_a = set()
set_b = set()
if isinstance(list_a, list):
set_a = set(list_a)
if isinstance(list_b, list):
set_b = set(li... | 5,298,834 |
async def test_login_fails_both_properly(opp, mock_remote, camera_v320):
"""Test if login fails properly."""
camera_v320.return_value.login.side_effect = OSError
config = {"platform": "uvc", "nvr": "foo", "key": "secret"}
assert await async_setup_component(opp, "camera", {"camera": config})
await op... | 5,298,835 |
def rank(accessing_obj, accessed_obj, *args, **kwargs):
"""
Use rank in an organization to see if we pass. If orgname
is not specified, the org is assumed to be the accessed
object. If rank is called incorrectly, we'll try to call the
organization permission instead as a fallback.
Usage:
... | 5,298,836 |
def test_pubished_date_failure(database):
""" Test invalid. For (ActionType = B, C, or D), the CFDA_Number need NOT be active as of the ActionDate.
Not apply to those with CorrectionLateDeleteIndicator = C.
Active date: publish_date <= action_date <= archive_date (Fails validation if active).
... | 5,298,837 |
def replacement_test_batch(
model, batch_dict, c, verbose=False, sweep_vals=None):
"""Replacem inputs of single target element, see if pred changes accord."""
col = batch_dict['target_cols']
if len(col) > 1:
raise ValueError('Multi-col tests not implemented!')
col = col[0]
if col i... | 5,298,838 |
def _add_implied_job_id(d):
"""If *d* has *task_id* or *application_id* but not *job_id*,
add it.
(We don't infer application_id from job_id because application_id
only exists on YARN)
.. note::
Don't use this with Spark, where job and application IDs don't
necessarily match.
""... | 5,298,839 |
def _transform_retexpr(tree, known_ecs, call_cb=None, data_cb=None):
"""Analyze and TCO a return-value expression or a lambda body.
This performs a tail-position analysis on the given ``tree``, recursively
handling the builtins ``a if p else b``, ``and``, ``or``; and from
``unpythonic.syntax``, ``do[]`... | 5,298,840 |
def translate_text_with_glossary(
text="YOUR_TEXT_TO_TRANSLATE",
project_id="YOUR_PROJECT_ID",
glossary_id="YOUR_GLOSSARY_ID",
):
"""Translates a given text using a glossary."""
client = translate.TranslationServiceClient()
location = "us-central1"
parent = f"projects/{project_id}/locations... | 5,298,841 |
def invalid_datetime_redirects():
"""
Generate invalid iterable test data.
Test data returned as a series of invalid date URL paths.
"""
# A list of n-tuples of lists to generate invalid dates
invalid_datetime_lists = (
(INVALID_YEARS, VALID_MONTHS),
(VALID_YEARS, INVALID_MONTHS... | 5,298,842 |
def setup(bot):
"""Cog setup method."""
bot.add_cog(Ping(bot)) | 5,298,843 |
def test_daily_timestamp():
"""Does the daily timestamp algo return a deferred."""
bot = basicbot(None, None, xml_log_path="/tmp")
assert botutil.daily_timestamp(bot) is not None | 5,298,844 |
def migrate_1_to_2(self):
"""
Migrate from schema 1 to 2.
"""
if self.schema_version < 1:
migrate_0_to_1(self)
if self.schema_version == 1:
old_analysis = getattr(self.unsupported_attrs, 'old_analysis', None)
self.activity = []
self.campaign = []
if old_anal... | 5,298,845 |
def after_new_channel_start_healthcheck(
raiden: "RaidenService", channelnew: ContractReceiveChannelNew
) -> None:
"""Start connection healthcheck once a new channel is opened."""
partner_address = channelnew.channel_state.partner_state.address
if ConnectionManager.BOOTSTRAP_ADDR != partner_address:
... | 5,298,846 |
def cloud2cloud(source_msh, source_val, target_msh, unroll_axis=None, verbose=False, **kwargs):
"""
Interpolate source_val between source_msh and target_msh.
:param source: ndarray(\*shape_sce, dim_msh)
:param target: ndarray(\*shape_tgt, dim_msh)
:param values: ndarray(\*shape_sce, \*shape_val)
:param verbose: ... | 5,298,847 |
def add(dxm_state, driver_name, driver_class, driver_file):
"""
Add JDBC driver to Delphix Engine
"""
exit(driver_add(dxm_state.engine, dxm_state.engineuser, driver_name, driver_class, driver_file)) | 5,298,848 |
def parse_record(pymyo, record):
"""
Pretty print the record data
"""
for key, value in record.items():
pymyo.output("%s :\t%s"%(key, value)) | 5,298,849 |
def dVhatdYTrans(dcdVhat, U, s, VT):
"""
Apply action of [d(Vhat^{T})/d(Y)]^{T} to the array of derivatives
[d(c)/d(Vhat^{T})]^{T} to obtain the derivatives d(c)/d(Y)
Parameters
----------
dcdVhat : numpy.ndarray
array of derivatives d(c)/d(Vhat)
U : numpy.ndarray
left singu... | 5,298,850 |
def latest_checkpoint(model_dir, model_name):
"""return path of latest checkpoint in a model_dir
Args:
model_dir: string, indicate your model dir(save ckpts, summarys,
logs, etc).
model_name: name of your model. we find ckpts by name
Returns:
path: None if isn't exist or ... | 5,298,851 |
def user_key(username):
"""
Returns user auth key, used to access feed and user settings
Args:
username (str): registered user
Returns:
key (str): user key
"""
config = db.user_config(username)
return config['CONFIG']['key'] | 5,298,852 |
def write_multiple_files( extmodule, dir_path, files_sum_repository=None, encoding='ascii' ):
"""writes extmodule to multiple files"""
mfs = multiple_files_t( extmodule, dir_path, files_sum_repository=files_sum_repository, encoding=encoding )
mfs.write()
return mfs.written_files | 5,298,853 |
async def upload_zarr(sas_url=None, src_folder=None, dst_blob_name=None, timeout=30*60):
"""
Asyn upload a folder to Azure blob
:param sas_url: str, the SAS url
:param src_folder: str, full abs path to the folder
:param dst_blob_name: str, relative (to container) timeout of the
:param timeout:
... | 5,298,854 |
def line_coordinates(image_data, centroid_x, centroid_y, angle_vector_rad, \
step_division = 1, radius_approx = None, radius_approx_interval = 20):
"""Get the coordinates along each radial line of each specified angle
For all angles specified in angle_vector_rad, the coordinates (x,y) ... | 5,298,855 |
def as_batch(img, shape, as_list=False):
"""Convert an image block group to a list
After chop_to_blocks, the data has a structure like
(jx, ix, 1, 400, 400, 3)
convert this to:
obj_detection : (ix*jx, 400, 400, 3)
patch_identification : (ix*jx, 200, 200, 3)
Args
----
img ( np.... | 5,298,856 |
def dtw_sakoechiba(x=None, y=None, dist='square', window_size=0.1,
precomputed_cost=None, return_cost=False,
return_accumulated=False, return_path=False):
"""Dynamic Time Warping (DTW) distance with Sakoe-Chiba band constraint.
.. deprecated:: 0.11
This function is... | 5,298,857 |
def test_4_1_14_audit_rule_file_exists(host):
"""
CIS Ubuntu 20.04 v1.0.0 - Rule # 4.1.14
Tests if /etc/audit/rules.d/4.1.14.rules file exists
"""
host.file(RULE_FILE_4114).exists | 5,298,858 |
def node_from_manifest(manifest):
"""Create V1Node object from a YAML manifest."""
manifest = yaml.safe_load(manifest)
manifest['api_version'] = manifest.pop('apiVersion')
return k8s.client.V1Node(**manifest) | 5,298,859 |
def _OverrideBinaryOperatorHelper(func, op_name, clazz_object=ops.Tensor):
"""Register operators with different tensor and scalar versions.
If `clazz_object` is `SparseTensor`, assumes `func` takes `(sp_indices,
sp_values, sp_shape, dense)` and outputs `(new_sp_values)`.
Args:
func: the operator
op_na... | 5,298,860 |
def generate_freenas_snapshot_name(name, iqn_prefix):
"""Create FREENAS snapshot / iscsitarget name from Cinder name."""
backend_snap = 'snap-' + name.split('-')[1]
backend_target = 'target-' + name.split('-')[1]
backend_iqn = iqn_prefix + backend_target
return {'name': backend_snap,
'ta... | 5,298,861 |
def test_parse_lattice_spec():
"""The lattice specification should be a string such as "-5,10,5/0.5,2,2",
which defines a two dimensional lattice where the x coordinate goes
from -5 to 10 in 5 steps, while the y coordinate goes from 0.5 to 2 in 2
steps. Another example is "-5,10,5/1.23,1.23,1", which de... | 5,298,862 |
def GetTestPoint(name):
"""
Factory method to return a TestPoint object.
@params name: Desired name of the object.
"""
global GLOBAL_TOGGLE
# Only return a real object if
# TestPoints are enabled
if(GLOBAL_TOGGLE is True):
return TestPoint(name)
else:
return DummyPo... | 5,298,863 |
def main():
"""
Junks Lab Command Main Method.
:return: Me.
"""
print('Hello World!') | 5,298,864 |
def select_massive_subhalos_with_redshift(mpi, path, data):
"""
Loop through snapshots reading subfind tables and extracting most massive subhalos
"""
if not mpi.Rank:
print(" > Extracting subhalo masses", flush=True)
masses = data["M200crit"]
snaps = data["Snapshots"]
indices = dat... | 5,298,865 |
def output_kimera_configs(output, left_camera_config, right_camera_config, imu_config):
"""Write configurations to disk."""
env = get_jinja_env()
imu_template = env.get_template("imu.yaml")
camera_template = env.get_template("camera.yaml")
if output is not None:
output_path = pathlib.Path(o... | 5,298,866 |
def train_classifier(model, optimizer, scheduler,dataloaders,device,kwargs):
"""This funcion performs training of classifier HEAD. It can be wrapped into the DNN
module as a class function
"""
num_epochs=kwargs['ep']
writer=kwargs['writer']
best_loss=kwargs['best_loss']
t_board=kwa... | 5,298,867 |
def get_token_list(text):
"""Returns a list of tokens.
This function expects that the tokens in the text are separated by space
character(s). Example: "ca n't , touch". This is the case at least for the
public DiscoFuse and WikiSplit datasets.
Args:
text: String to be split into tokens.
"""
return t... | 5,298,868 |
def _search_children(statespace, node, expression, taint_result=None, constraint=[], index=0, depth=0, max_depth=64):
"""
Checks the statespace for children states, with JUMPI or SSTORE instuctions,
for dependency on expression
:param statespace: The statespace to explore
:param node: Current node t... | 5,298,869 |
def pythagorean_triples(upper: int, lower: int = 3) -> Iterator[Tuple[int, int, int]]:
"""Pythagorean triples where no side is longer than `upper` bound."""
for a in range(lower, upper):
for b in range(lower, upper):
for c in range(lower, upper):
if a < b < c and a * a + b * ... | 5,298,870 |
def cut_string(string, limit=30):
"""Shorten the length of longer strings."""
if len(string) <= limit:
return string
else:
return string[:limit-3] + '...' | 5,298,871 |
def dxp(u):
"""Backward finite differences in x direction.
Args:
u (ndarray): 2D input array.
Returns:
ndarray: Finite difference.
"""
u = np.mat(u)
dx = np.hstack((u[:, 1:], u[:, -1])) - u
return np.array(dx) | 5,298,872 |
def prepare(ctx, resource_config, **_):
"""Prepares an AWS S3 Bucket Object"""
# Save the parameters
ctx.instance.runtime_properties['resource_config'] = resource_config | 5,298,873 |
def is_unique_dist_mat_energy(geo, ene, geo_list, ene_list):
""" compare given geo with list of geos all to see if any have the same
distance matrix and energy
"""
unique = True
for idx, geoi in enumerate(geo_list):
enei = ene_list[idx]
etol = 2.e-5
if abs(ene-enei) < etol:
... | 5,298,874 |
def SeismogramEnsemble2Stream(sge):
"""
Convert a seismogram ensemble to stream
:param sge: seismogram ensemble input
:return: stream
"""
# This uses the same approach as TimeSeriesEnsemblet2Stream to handle
# ensemble metadata. See comments there for potential maintenanc issues
md = sg... | 5,298,875 |
def hrm_training_job_title(row):
"""
Which Job Titles(s) the person is active with
"""
try:
person_id = row.hrm_training.person_id
except AttributeError:
# not available
person_id = None
if person_id:
s3db = current.s3db
table = s3db.hrm_human_resour... | 5,298,876 |
def get_dataset(dataset, data_path, size, download=False):
"""
Loads a dataset
:param dataset: String. Name of dataset. Currently supports ['test', 'cifar10', 'cifar100', 'imagenet'].
Note that 'test' loads the 'cifar10'
:param data_path: String. Path to directory where the dataset is / will be sav... | 5,298,877 |
def dct_N(x, perm=None, expk=None):
""" Batch Discrete Cosine Transformation without normalization to coefficients.
Compute y_u = \sum_i x_i cos(pi*(2i+1)*u/(2N)),
Impelements the N permuting trick to solve DCT with FFT in the following link,
https://dsp.stackexchange.com/questions/2807/fast-cosine-tra... | 5,298,878 |
def portal(driver):
"""Return the 'portal' function, and the hint-annotator policy.
The portal is the function that gets patched with a call to the JIT
compiler.
"""
return tiny2.interpret, MyHintAnnotatorPolicy() | 5,298,879 |
def run_cli():
"""main method for fakeme cli"""
parser = create_cli_parser()
args = parser.parse_args()
config_path = os.path.expanduser(args.config)
if not os.getcwd() in config_path:
config_path = os.path.join(os.getcwd(), config_path)
if not os.path.isfile(config_path):
print(... | 5,298,880 |
def format_results_for_suggestion(search_res: dict) -> list:
"""Format search movie results for `show_movie_suggestions()`
Parameters
----------
search_res : dict
result of `search_movie_from_query()`
Returns
-------
list
List of formated tuple for displays.
1st ele... | 5,298,881 |
def main():
""" Traverse the galleries """
try:
with open(Files.OPTIONS.value) as options_file:
options = json.load(options_file)
creawler = GalleryCrawler(options)
creawler.run()
except FileNotFoundError:
logging.error(
"You should create your... | 5,298,882 |
def test_displacements_field2(tmp_path, data_path, sw_tool):
"""Check a translation-only field on one or more axes, different image orientations."""
os.chdir(str(tmp_path))
img_fname = data_path / 'tpl-OASIS30ANTs_T1w.nii.gz'
xfm_fname = data_path / 'ds-005_sub-01_from-OASIS_to-T1_warp_{}.nii.gz'.format... | 5,298,883 |
def recommended_from_views(request):
""" get product recommendations based on products that the customer has viewed;
gets list of tracking IDs of other customers who have viewed the products in the current customer's
viewed products, and gets products that these other customers also viewed.
"""
t_i... | 5,298,884 |
def heading(heading_string, underline='='):
"""
Takes a raw string and underlines it with the given underline char
"""
return '%s\n%s' % (heading_string, underline * len(heading_string)) | 5,298,885 |
def cvx_kron(
expr_1: Union[np.ndarray, Expression], expr_2: Union[np.ndarray, Expression]
) -> Expression:
"""
Compute Kronecker product between CVXPY objects.
By default, CVXPY does not support taking the Kronecker product when the argument on the left is
equal to a CVXPY object and the object on... | 5,298,886 |
def run_batch():
"""[Runs batch of 2D parameter scans]
Returns:
None
"""
for gr_Sfission in gr_Sfission_Vec:
for par0 in par0Vec:
if gr_Sfission == 0:
K_tot = K_tot_def * 6
else:
K_tot = K_tot_def
s... | 5,298,887 |
def capture():
"""Wrapper that replaces system stdout/stderr an provides the streams."""
oldout = sys.stdout
olderr = sys.stderr
try:
stdout=StringIO()
stderr=StringIO()
sys.stdout = stdout
sys.stderr = stderr
yield stdout, stderr
finally:
sys.stdout = oldout
sys.stderr = olderr | 5,298,888 |
def optionally_resample(key: RandomKey, log_weights: Array, samples: Array,
resample_threshold: Array) -> Tuple[Array, Array]:
"""Call simple_resampling on log_weights/samples if ESS is below threshold.
The resample_threshold is interpretted as a fraction of the total number of
samples. S... | 5,298,889 |
def composed_measurement(ec_measurement):
"""Fixture that returns a composed measurement"""
measurement1 = ec_measurement.select(cycle=1)
measurement2 = ec_measurement.select(cycle=3)
return measurement1 + measurement2 | 5,298,890 |
def foo():
"""This docstring defines the foo subcommand of the Kluge CLI."""
pass | 5,298,891 |
def filter_vcf(recordsA, recordsB):
"""Remove records in B from A."""
currB = next(recordsB)
for record in recordsA:
# While A is lagging, all variants are OK
if record.pos < currB.pos:
yield record
else:
# Skip until B matches or is ahead
wh... | 5,298,892 |
def acquisition_start(image_numbers):
"""Start imitng system after all subsystem are initialized"""
if len(image_numbers) > 0:
if not "linear stage" in translate.mode:
filenames = [filename(i) for i in image_numbers]
xdet_on = timing_sequencer.xdet_on
progress("X-ray... | 5,298,893 |
def construct_trace_net(trace, trace_name_key=xes_util.DEFAULT_NAME_KEY, activity_key=xes_util.DEFAULT_NAME_KEY):
"""
Creates a trace net, i.e. a trace in Petri net form.
Parameters
----------
trace: :class:`list` input trace, assumed to be a list of events
trace_name_key: :class:`str` key of t... | 5,298,894 |
def MurtyPartition(N, a, type):
"""
MurtyPartition partitioin node N with its minimum assignment a
input:
N - in Murty's original paper, N is a "node", i.e. a non empty
subset of A, which contains all assignment schemes.
a - a nMeas*1 vector containing one assignment scheme.
type -... | 5,298,895 |
def notify_sns(message):
"""Send results to SNS for further processing."""
client = boto3.client('sns', "eu-west-1")
response = client.publish(
TargetArn=os.environ['SNS_topic'],
Message=json.dumps({'default': json.dumps(message)}),
MessageStructure='json'
)
print(response) | 5,298,896 |
def create_dataset(param):
"""
Create a dataset given the parameters.
"""
dataset_class = find_dataset_using_name(param.dataset_mode)
# Get an instance of this dataset class
dataset = dataset_class(param)
print("Dataset [%s] was created" % type(dataset).__name__)
return dataset | 5,298,897 |
def run(entry_workflow: Workflow,
workflow_id: Optional[str] = None,
overwrite: bool = True) -> ray.ObjectRef:
"""Run a workflow asynchronously.
# TODO(suquark): The current "run" always overwrite existing workflow.
# We need to fix this later.
"""
store = get_global_storage()
a... | 5,298,898 |
def fully_connected(inputs,
num_outputs,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
... | 5,298,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.