content
stringlengths
22
815k
id
int64
0
4.91M
def debug_mode(x): """ Enable debug mode. Use debug_mode(True) to show debug log events in the console and to save calling info in BedTool objects, and turn it off again with debug_mode(False). Note that `pybedtools.KEEP_TEMPFILES` will be set as well, so you will need to clean up the temp...
40,900
def mps_to_kmh(speed_in_mps): """Convert from kilometers per hour to meters per second Aguments: speed_in_mps: a speed to convert Returns: speed_in_kmh: a speed in m/s """ return speed_in_mps / 1000.0 * 3600.0
40,901
def tokenize_and_remove_stopwords(txt,additional_stopwords): """ Runs tokenization and removes stop words on the specified text Parameters ----------- txt: text to process additional_stopwords: path to file containing possible additional stopwords on each line Returns ------- Proce...
40,902
async def async_setup_entry(hass, config_entry, async_add_entities): """Add the Wiser System Switch entities.""" data = hass.data[DOMAIN][config_entry.entry_id][DATA] # Get Handler # Add Defined Switches wiser_switches = [] for switch in WISER_SWITCHES: if switch["type"] == "room": ...
40,903
def get_keep_dice_check(input_prompt): """ Enables returning a yes or no response to an input prompt. :param input_prompt: String yes no question. """ return pyip.inputYesNo(prompt=input_prompt)
40,904
def main(): """Comvert the numbers in an input string to there 'jump the 5' equivalents.""" args = get_args() str_arg = args.inputString jump_map:dict = {'1': '9', '2': '8', '3': '7', '4': '6', '5': '0', '6': '4', '7': '3', '8': '2', '9': '1', '0': '5'} new_str:str = '' f...
40,905
def get_pending_jobs(sort=True): """Obtains the list of currently pending (queued) jobs for the user.""" username = getusername() # see squeue man page for status code (%t specifier) listjob = sh.pipe_out(("squeue", "-u", username, "--noheader", "--format=%i %t"), split=True) rslt = [] # treat one of these ...
40,906
def getOverlapRange(rangeA, rangeB): """ Calculate the overlapping range between rangeA and rangeB. Args: rangeA (list, tuple): List or tuple containing start and end value in float. rangeB (list, tuple): List or tuple containing start and end value in float. Retu...
40,907
def multiply_values(dictionary: dict, num: int) -> dict: """Multiplies each value in `dictionary` by `num` Args: dictionary (dict): subject dictionary num (int): multiplier Returns: dict: mapping of keys to values multiplied by multiplier """ return ( {key: value * ...
40,908
def ls_stack( profile: Union[str, bool] = False, region: Union[str, bool] = False, resource: bool = False, name: bool = False, arn: bool = False, tag: bool = False, resource_type: bool = False, ) -> None: """Display stack/resource information. :param profile: use a different profile...
40,909
def send_alarm(address, email_type, template_data={}): """ Send an email message to the given email address immediately, bypassing any queues or database system. :param address: The email address to send this message to. :param email_type: str defining this email template e.g EMAIL_WELCOME. Defined in e...
40,910
def serialize_curve_point(p: Point) -> bytes: """ Serialize an elliptic curve point ``p`` in compressed form as described in SEC1v2 (https://secg.org/sec1-v2.pdf) section 2.3.3. Corresponds directly to the "ser_P(P)" function in BIP32 (https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#...
40,911
def gcom_so_config(revision=None): """ Create a shared object for linking. """ config = BuildConfig( project_label=f'gcom shared library {revision}', source_root=gcom_grab_config(revision=revision).source_root, steps=[ *common_build_steps(fpic=True), Link...
40,912
def babel(): """Perform translation tasks.""" pass
40,913
def func(command, description, link, params_string, returns="On success, the sent Message is returned.", return_type="Message"): """ Live template for pycharm: y = func(command="$cmd$", description="$desc$", link="$lnk$", params_string="$first_param$", returns="$returns$", return_type="$returntype$") "...
40,914
def recoverFile(name, revision, force): """ Adds a deleted file back to the repository. """ syncDoActionAndResolve(name, "add", int(revision), force)
40,915
def get_basic_details(args, item): """ :param args: { "item_code": "", "warehouse": None, "doctype": "", "name": "", "project": "", warehouse: "", update_stock: "", project: "", qty: "", stock_qty: "" } :param item: `item_code` of Item object :return: frappe._dict """ if not item:...
40,916
def translateThisNodeToPoints(): """None""" pass
40,917
def validate_standard_json(json_to_test: dict) -> bool: """ validate fixed json against schema """ valid_json_flag = False schema_to_use = get_standard_json_schema() valid_json_flag = validate_json(json_to_test, schema_to_use, True) return valid_json_flag
40,918
def test_adding_existent_rel_both_ways(lpg): """Ensure we get the proper key erro.""" lpg.add_node('Charlie') lpg.add_node('Unicorn') lpg.add_relationship('buddies', 'Charlie', 'Unicorn') with pytest.raises(ValueError): lpg.add_relationship('buddies', 'Charlie', 'Unicorn', both_ways=True)
40,919
def put_observation_field_values( observation_id: int, observation_field_id: int, value: Any, access_token: str, **kwargs, ) -> JsonResponse: # TODO: Also implement a put_or_update_observation_field_values() that deletes then recreates the field_value? # TODO: Return some meaningful exceptio...
40,920
def test_hypotest_return_expected_set(tmpdir, hypotest_args): """ Check that the return structure of pyhf.utils.hypotest with the additon of the return_expected_set keyword arg is as expected """ tb = pyhf.tensorlib kwargs = { 'return_tail_probs': True, 'return_expected': True, ...
40,921
def desg_to_prefix(desg: str) -> Any: """Convert small body designation to file prefix.""" return (desg.replace('/', '').replace(' ', '') .replace('(', '_').replace(')', '_'))
40,922
def get_logger(name=None, log=False, level=INFO, path=None): """ Returns the appropriate logger depending on the passed-in arguments. This is particularly useful in conjunction with command-line arguments when you won't know for sure what kind of logger the program will need. :param name: ...
40,923
def get_url_for_packages(provenance): """Return url for every package (versioned) as specified in provenance It traverses passes provenance ... Examples -------- >>> get_url_for_packages({'cmtk' : '3.2.2-1.4build1'}) {'cmtk': 'http://example.com/cmtk_3.2.2-1.4build1.deb'} Parameters ...
40,924
def stop_job(job_name: Text, execution_id: Text) -> JobInfo: """ Stop a job defined in the ai flow workflow. :param job_name: The job name which task defined in workflow. :param execution_id: The ai flow workflow execution identify. :return: The result of the action. """ return ...
40,925
def find_user(): """ Determines current user using the username value of the current session user and returns the current user as a dict. """ current_user = mongo.db.users.find_one({"username": session["user"]}) return current_user
40,926
def autosize_columns(sheet: Worksheet) -> None: """ Resizes the columns of the passed worksheet to fit the content inside the cells of the columns. :param sheet: the worksheet to autosize """ dim_holder = sheet.column_dimensions for column_cells in sheet.columns: width = max(len(st...
40,927
def field2nullable(field, **kwargs): """Return the dictionary of swagger field attributes for a nullable field. :param Field field: A marshmallow field. :rtype: dict """ attributes = {} if field.allow_none: omv = kwargs['openapi_major_version'] attributes['x-nullable' if omv < 3...
40,928
def zero_expand3d(inputs, stride=1): """Expand the inputs by zeros explain the expand operation: given stride = 1 [[[1, 2] --> [[[1, 0, 2] [3, 4]] [0, 0, 0] [3, 0, 4]] [[5, 6] [7, 8]]] [[0, 0, 0] [0, 0, 0] ...
40,929
def _load_setup_cfg(): """Load the setup configuration from the 'setup.json' file.""" try: with open(ROOT / 'setup.json') as setup_json_file: return json.load(setup_json_file) except json.decoder.JSONDecodeError as error: # pylint: disable=no-member raise DependencySpecification...
40,930
def toJSON(obj, opt_pretty=False, for_cloud_api=True): """Serialize an object to a JSON string appropriate for API calls. Args: obj: The object to serialize. opt_pretty: True to pretty-print the object. for_cloud_api: Whether the encoding should be done for the Cloud API or the legacy API. Ret...
40,931
def load_config_file_koe(filename): """ Loads in a config file for KOE to run Args: filename: Filename (can be absolute or relative path, or a URL) to read config file from. Returns: dict: Configuration file as a dict object. """ config_values = {} # First try to open things lo...
40,932
def select_by_type(transcripts, log): """Filter transcripts depending on different type""" # Difference types: UTR5_number and UTR5_boundary candidates, dtype, dcrit = analyse_difference_type_utr5_number_or_boundary(transcripts, log) if candidates is not None: return candidates, dtype, dcrit ...
40,933
def build_dashboards(product_urls, dasher_url, logger): """Trigger ltd-dasher's POST /build endpoint to build dashboards for one or more LTD products. This function is a no-op if the LTD_DASHER_URL app config is ``None``. Parameters ---------- product_urls : `list` or `tuple` of `str` ...
40,934
def create_excel_results(data_dic, out_loc): """ Takes the generated dictionary of output files and stores the files that can be represented as table in a excel file. Parameters: data_dic: dict, result files form feature_hyperparam_opt fnc out_loc: str, path to store the excel file """ ...
40,935
def lorentzian_distance(x, y): """Calculates the Lorentzian Distance. Args: x (np.array): N-dimensional array. y (np.array): N-dimensional array. Returns: The Lorentzian Distance between x and y. """ dist = np.log(1 + np.fabs(x - y)) return np.sum(dist)
40,936
def attendance(bot, job): """ Core function. Fetch attendance figures from Aldel's MIS. Runs AttendanceSpider for registered users and passes it their Student_ID(PID), Password, & ChatID (necessary for AttendancePipeline) AttendanceSpider creates a image file of the format: <Student_ID>_attendance....
40,937
def check_database_status(database_name, env): """This function looks for a DatabaseCreate task and returns a http response or the Database itself depeding on the context. If the DatabaseCreate task is still running of failed, a http response is returned, otherwise this functions tries to retrieve the D...
40,938
def get_flat_schema(schema_name=None): """Flatten the specified data model schema, defaulting to the core schema, useful for retrieving FITS keywords or valid value lists. """ return _schema_to_flat(_load_schema(schema_name))
40,939
def repeat3(img): """ Repeat an array 3 times along its last axis :param img: A numpy.ndarray :return: A numpy.ndarray with a shape of: img.shape + (3,) """ return np.repeat(img[..., np.newaxis], 3, axis=-1)
40,940
def debug_line(i_line, str_line): """ Print out the given line for debug. """ modlog.log( MODLOG_FILTER, modlog.DEBUG, " line[%d] = '%s'" % ( i_line, str_line.replace("\b", "\\b").replace("\r", "\\r").replace("\n", "\\n") ) )
40,941
def encode_strategies(strategies, batch_size=stg.JOBLIB_BATCH_SIZE, parallel=True): """ Encode strategies Parameters ---------- strategies : Strategies array Array of strategies to be encoded. Returns ------- numpy array Encodings for each strateg...
40,942
def worker(args): """ Driver Function for sending envelops input :: - args : envelope informations output :: send envelope """ args = update_args(args) api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"]) bulk_envelopes_api = BulkEnvelopesApi(ap...
40,943
def generate_authenticator(data, authenticator_key): """ This function will generate an authenticator for the data (provides authentication and integrity). :param data: The data over which to generate the authenticator. :type data: :class:`str` :param authenticator_key: The secret key to be used b...
40,944
def detection_target_layer(proposals, gt_class_ids, gt_boxes, gt_masks): """Subsamples proposals and generates target box refinement, class_ids, and masks for each. Inputs: proposals: [batch, N, (y1, x1, y2, x2)] in normalized coordinates. Might be zero padded if there are not enough pro...
40,945
def test_graph_filter_edges(default_plugin_resolver): """ 0 <--2-- 1 5 --10-> 6 | ^ | ^ ^ / | / | / | / 1 7 3 9 5 11 | / | / | / v v / v 3 --8--> 4 <--4-- 2 --6--> 7 """ dpr = default_plugin_resolver ebunch = [ ...
40,946
def notify_local_staff(proposal): """ Notifies local lab staff of the current Proposal via e-mail. :param proposal: the current Proposal """ # Change language to Dutch for this e-mail, but save the current language to reset it later current_language = get_language() activate('nl') secre...
40,947
def multi_recall(pred_y, true_y, labels): """ Calculate the recall of multi classification :param pred_y: predict result :param true_y: true result :param labels: label list :return: """ if isinstance(pred_y[0], list): pred_y = [item[0] for item in pred_y] recalls = [binary_...
40,948
def is_safe_range(expression): """ Return true if an expression is safe range. This function receives an expression in safe range normal form and returns true if all its free variables are range restricted. """ try: return extract_logic_free_variables( expression ...
40,949
def star_marker_level(prev, curr): """Allow markers to be on the same level as a preceding star""" return (prev.is_stars() and not curr.is_stars() and prev.depth == curr.depth)
40,950
def get_mail_addresses(ids: Optional[Sequence[str]] = None, key_word: Optional[str] = None, output_file: Optional[str] = None, sendtype: Optional[str] = None, status: Optional[str] = None, opts: Optional[p...
40,951
def set_cmake_var( var_name: str, value: str, post_out: tp.Callable[[str], None] = lambda x: None ) -> None: """Sets a cmake variable in the current cmake config.""" with ProcessManager.create_process( "cmake", ["-D" + var_name + "=" + value, "."] ) as proc: proc.setProcessChanne...
40,952
def repartition(ctx, num_physical_shards): """ Repartition DIRBS Core tables into a new number of physical IMEI shards. :param ctx: current cli context obj :param num_physical_shards: number of physical shards """ logger = logging.getLogger('dirbs.db') config = common.ensure_config(ctx) ...
40,953
def load_checkpoint( file, model: torch.nn.Module, optimizer: torch.optim.Optimizer = None, lr_scheduler: torch.optim.lr_scheduler._LRScheduler = None, strict: bool = True, ): """Loads training states from a checkpoint file. Args: file: a file-like object (has to implement read(), ...
40,954
def num_or_str(x): """The argument is a string; convert to a number if possible, or strip it. Ex: num_or_str('42') ==> 42; num_or_str(' 42x ') ==> '42x' """ try: return int(x) except ValueError: try: return float(x) except ValueError: return str(x...
40,955
def mac_timezone(): """Determine system timezone""" output = cmdmod['cmd.run']("/usr/sbin/systemsetup -gettimezone") return {'mac_timezone': output[11:]}
40,956
def full_writer(output, venue, start, end, writer_q): """Write all the names to the classifier.""" count = 0 for author in conf_authors(venue, start, end): output.write((author + '\n').encode('UTF-8')) count = count + 1 output.close() writer_q.put(count)
40,957
def count_files(directory, filters, extension, show_files=False, **kwargs): """counts the number of files in the first level of a directory Parameters ---------- directory : str path of directory to be checked filters : str filter present in file to be checked extension : str ...
40,958
def test_encode_type_1(): """ Verified using http://ais.tbsalling.dk/. """ data = { 'accuracy': 0, 'course': 219.3, 'heading': 1, 'lat': 37.80211833333333, 'lon': -122.34161833333333, 'maneuver': 0, 'mmsi': '366053209', 'radio': 2281, ...
40,959
def run_emcee_seeded(light_curve, transit_params, spot_parameters, n_steps, n_walkers, output_path, burnin=0.7, n_extra_spots=1, skip_priors=False): """ Fit for transit depth and spot parameters given initial guess informed by results from `peak_finder` Paramet...
40,960
def lookup_loc_carriers(model_run): """ loc_carriers, used in system_wide balance, are linked to loc_tech_carriers e.g. `X1::power` will be linked to `X1::chp::power` and `X1::battery::power` in a comma delimited string, e.g. `X1::chp::power,X1::battery::power` """ # get the technologies associa...
40,961
def test_atomic_decimal_min_inclusive_2_nistxml_sv_iv_atomic_decimal_min_inclusive_3_1(mode, save_output, output_format): """ Type atomic/decimal is restricted by facet minInclusive with value -785368448026986020. """ assert_bindings( schema="nistData/atomic/decimal/Schema+Instance/NISTSchem...
40,962
def filldown(table, *fields, **kwargs): """ Replace missing values with non-missing values from the row above. E.g.:: >>> from petl import filldown, look >>> look(table1) +-------+-------+-------+ | 'foo' | 'bar' | 'baz' | +=======+=======+=======+ ...
40,963
def realworld_bring_peg(fully_observable=True, time_limit=_TIME_LIMIT, random=None, log_output=None, environment_kwargs=None, safety_spec=None, delay_spec=None, ...
40,964
def schedule_gemm(cfg, s, A, B, C, batched=False, schedule_transforms=True): """Schedule GEMM, single and batched Parameters ---------- cfg : Config Schedule configuration s : tvm.te.schedule.Schedule Operator schedule A : tvm.te.Tensor 2D/3D Tensor, shape [n, k]/[b, n...
40,965
def distance(x1: float, y1: float, x2: float, y2: float) -> float: """Возвращает расстояние между двумя точками на плоскости""" return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
40,966
async def main5(): """ 将create_task拿到列表外面(变成了gather) 并且舍去列表推导式展开部分 :return: """ start_date = datetime.datetime.now() print(f'Start at {start_date:%Y-%m-%d %H:%M:%S}') await asyncio.gather(*[say_after(delay=delay, what=what) for delay, what in zip([1, 2, 3, 4],...
40,967
def print_job_info(job): """ This function prints the information about a particular job """ print_console() print_console(job.center(80, "=")) print_console() print_console(" last state: %s" % (jobs[job].state)) parse_submit_file(jobs[job]) # Handle subdag jobs from the dag file ...
40,968
def test_get_console_log_level_failure(): """ Test if console log level of file is not returned then it should throw KeyError. """ with pytest.raises(KeyError): config = CORTXS3Config() del config._config['logconfig']['console_log_level'] assert config.get_console_log_level()
40,969
def GitPush(git_repo, refspec, push_to, force=False, dry_run=False, capture_output=True, skip=False, **kwargs): """Wrapper for pushing to a branch. Args: git_repo: Git repository to act on. refspec: The local ref to push to the remote. push_to: A RemoteRef object representing the remote ref...
40,970
def update_2_79_light(light): """ Import Physical lights data from light.rpr_lamp""" convert = ( 'intensity', 'use_temperature', 'temperature', 'visible', 'cast_shadows', # 'ies_file_name', 'luminous_efficacy', 'intensity_normalization', ) ...
40,971
def main(stdscr): """Draw a simple TUI, grab keypresses and let the user play the sounds.""" stdscr.clear() stdscr.nodelay(True) # Create small visual display stdscr.addstr( "=========================\n" "Load From Memory Example.\n" "=========================\n" "\n...
40,972
def boxes_to_array(bound_boxes): """ # Args boxes : list of BoundBox instances # Returns centroid_boxes : (N, 4) probs : (N, nb_classes) """ temp_list = [] for box in bound_boxes: temp_list.append([np.argmax(box.classes), np.asarray([box.x, box.y, box.w, box....
40,973
def bam_to_junction_reads_table(bam_filename, ignore_multimapping=False): """Create a table of reads for this bam file""" uniquely, multi = _get_junction_reads(bam_filename) reads = _combine_uniquely_multi(uniquely, multi, ignore_multimapping) # Remove "junctions" with same start and stop reads = r...
40,974
def download_file(package, url, directory, extractor): """Downloads file from URL. Downloads file specified at URL and inserts into temporary folder. Args: package (str): The package to install url (str): The URL to scrape package source file directory (str): The temporary director...
40,975
def _scope_prepare(scope: str) -> Tuple[object, str]: """ Parse a scope string a return a tuple consisting of context manager for the assignation of the tf's scope and a string representing the summary name. The scope is of the form "<ident1>.<ident2>. ... .<ident3>", the righmost identifier is used as ...
40,976
def test_sanitize_msgpack_unpack_kwargs(version, exp_kwargs): """ Test helper function _sanitize_msgpack_unpack_kwargs """ kwargs = {"strict_map_key": True, "use_bin_type": True, "encoding": "utf-8"} with patch.object(salt.utils.msgpack, "version", version): assert ( salt.utils.m...
40,977
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): aftv = hass.data[DOMAIN][entry.entry_id][ANDROID_DEV] await aftv.adb_close() hass.data[DOMAIN].p...
40,978
def register_keras_tensor_specialization(cls, keras_tensor_subclass): """Register a specialized KerasTensor subclass for a Tensor type.""" # We always leave (object, KerasTensor) at the end as a generic fallback keras_tensor_classes.insert(-1, (cls, keras_tensor_subclass))
40,979
def render_wrapped_text(text: str, font: pygame.freetype.Font, color: Color, centered: bool, offset_y: int, max_width: int) -> Tuple[pygame.Surface, pygame.Rect]: """Return a surface & rectangle with text rendered over several lines. Parameter offset_y defines th...
40,980
def doctest_RestViewer_rest_to_html_strict_and_error_handling(): """Test for RestViewer.rest_to_html >>> stderr_patcher = patch('sys.stderr', StringIO()) >>> stderr = stderr_patcher.start() >>> viewer = RestViewer('.') >>> viewer.stylesheets = None >>> viewer.halt_level = 2...
40,981
def comp4(a1,a2,b1,b2): """两个区间交集,a1<a2; b1<b2""" if a2<b1 or b2<a1:#'空集' gtii = [] else: lst1 = sorted([a1,a2,b1,b2]) gtii = [lst1[1], lst1[2]] return gtii
40,982
def fixed_step_solver_template( take_step: Callable, rhs_func: Callable, t_span: Array, y0: Array, max_dt: float, t_eval: Optional[Union[Tuple, List, Array]] = None, ): """Helper function for implementing fixed-step solvers supporting both ``t_span`` and ``max_dt`` arguments. ``take_step...
40,983
def set_reference_ene(rxn_lst, spc_dct, pes_model_dct_i, spc_model_dct_i, run_prefix, save_prefix, ref_idx=0): """ Sets the reference species for the PES for which all energies are scaled relative to. """ # Set the index for the reference species, right n...
40,984
def check_create_dir(path): """ Checks a directory and creates it if it does not exist """ try: os.makedirs(path) # Try to make it, otherwise don't do anything except OSError as exception: if exception.errno != errno.EEXIST: raise
40,985
def adjustAdjacentRecords(records, index): """ Checks if a specific record overlaps with adjacent records and adjusts adjacent start/end times accordingly :param records: <list[recorder.Record]> list of records :param index: <int> index of the record to use as the base for adjusting """ # if the records lis...
40,986
def get_laf_center(LAF: torch.Tensor) -> torch.Tensor: """Returns a center (keypoint) of the LAFs. Args: LAF: tensor [BxNx2x3]. Returns: tensor BxNx2. Shape: - Input: :math: `(B, N, 2, 3)` - Output: :math: `(B, N, 2)` Example: >>> input = torch.ones(1, 5,...
40,987
def pgcli( ctx, app_name, ): """Opens pgcli to a remote DB""" print("making proxy") proxy_dsn, ctx = proxy(ctx, app_name, background=True) with ctx: print("Waiting for proxy to open") time.sleep(4) run(f"pgcli {proxy_dsn}", pty=True)
40,988
def add_jar(local_path, plugin_name, plugin_dir=REMOTE_PLUGIN_DIR): """ Deploy jar for the specified plugin to the plugin directory. Parameters: local_path - Local path to the jar to be deployed plugin_name - Name of the plugin subdirectory to deploy jars to plugin_dir - (Optional) ...
40,989
def get_all_vlan_bindings_by_logical_switch(context, record_dict): """Get Vlan bindings that match the supplied logical switch.""" query = context.session.query(models.VlanBindings) return query.filter_by( logical_switch_uuid=record_dict['logical_switch_id'], ovsdb_identifier=record_dict['ov...
40,990
def conv_input_length(output_length, filter_size, padding, stride): """Determines input length of a convolution given output length. Args: output_length: integer. filter_size: integer. padding: one of "same", "valid", "full". stride: integer. Returns: The input length (integer). ...
40,991
def convert_data_to_int(x, y): """ Convert the provided data to integers, given a set of data with fully populated values. """ # Create the new version of X x_classes = [] for i in xrange(x.shape[1]): x_classes.append({item:j for j, item in enumerate(set(x[:,i]))}) new_x = np.zeros(x.shape, dtype=...
40,992
def send_report(report_text, svc_info, now_str): """ Publish report to AWS SNS endpoint Note: publish takes a max of 256KB. """ overage = len(report_text) - MAX_SNS_MESSAGE if overage > 0: report_text = report_text[:-overage - 20] + '\n<message truncated/>' resp = SNS_C.publish(Topic...
40,993
def test_restricting_topics(request, volttron_instance, client_agent): """ Test subscription to custom topics. Test -- 1. add additional topics 2. restricting topics """ global alert_publishes historian = None try: identity = 'platform.historian' CUSTOM_TOPIC = 'devices...
40,994
def credential(): """Return credential.""" return Credential('test@example.com', 'test_password')
40,995
def get_ez_from_contacts(xlsx_file, contacts_file, label_volume_file): """Return list of indices of EZ regions given by the EZ contacts in the patient spreadsheet""" CONTACTS_IND = 6 EZ_IND = 7 df = pd.read_excel(xlsx_file, sheet_name="EZ hypothesis and EI", header=1) ez_contacts = [] contact...
40,996
def test_inquire_pkb_response(setup_http_response, generate_sepulsa_response, assert_pkb_details): """ simulate success inquire pkb from sepulsa """ sepulsa_response = generate_sepulsa_response("INQUIRE_PKB") mock_http_response = setup_http_response(200, sepulsa_response) ...
40,997
def mapfmt_str(fmt: str, size: int) -> str: """Same as mapfmt, but works on strings instead of bytes.""" if size == 4: return fmt return fmt.replace('i', 'q').replace('f', 'd')
40,998
def setup_platform(hass, config, add_devices, discovery_info=None): """Setup the Camera.""" # check for missing required configuration variable if config.get("file_path") is None: _LOGGER.error("Missing required variable: file_path") return False setup_config = ( { "...
40,999