content
stringlengths
22
815k
id
int64
0
4.91M
def get_test_subprocess(cmd=None, **kwds): """Return a subprocess.Popen object to use in tests. By default stdout and stderr are redirected to /dev/null and the python interpreter is used as test process. It also attemps to make sure the process is in a reasonably initialized state. """ kwds...
5,343,400
def make_response(code: int, body: Union[Dict, List]) -> Dict[str, Any]: """Build a response. Args: code: HTTP response code. body: Python dictionary or list to jsonify. Returns: Response object compatible with AWS Lambda Proxy Integration """ return { "statusCode"...
5,343,401
def show_release_details(rel): """Print some details about a release dictionary to stdout. """ # "artist-credit-phrase" is a flat string of the credited artists # joined with " + " or whatever is given by the server. # You can also work with the "artist-credit" list manually. print("{}, by {}".f...
5,343,402
def log_matches(path_log, levels=("Error", "Warning")): """Log all matches Parameters ---------- path_log : str or path-like Path to a log file with gfortran compilation output levels : iterable of str Should by a subset of `{"Error", "Warning"}` """ text = Path(path_log).re...
5,343,403
def sql2dict(queryset): """Return a SQL alchemy style query result into a list of dicts. Args: queryset (object): The SQL alchemy result. Returns: result (list): The converted query set. """ if queryset is None: return [] return [record.__dict__ for record in queryset]
5,343,404
def build_DNN(input_dim, hidden_dim, num_hidden, embedding_dim=1, vocab_size=20,output_dim=1 ,activation_func=nn.Sigmoid): """ Function that automates the generation of a DNN by providing a template for pytorch's nn.Sequential class Parameters ---------- input_dim : int Number of dimensio...
5,343,405
def float_to_bin(x, m_digits:int): """ Convert a number x in range [0,1] to a binary string truncated to length m_digits arguments: x: float m_digits: integer return: x_bin: string The decimal representation of digits AFTER '0.' Ex: Input 0.75...
5,343,406
def apply(func: Callable, args: List): """Call `func` expanding `args`. Example: >>> def add(a, b): >>> return a + b >>> apply(add, [1, 2]) 3 """ return func(*args)
5,343,407
def random_energy_model_create(db: Session) -> EnergyModelCreate: """ Generate a random energy model create request. """ dataset = fixed_existing_dataset(db) component_1 = fixed_existing_energy_source(db) return EnergyModelCreate(name=f"EnergyModel-{dataset.id}-" + random_lower_string(), ...
5,343,408
def example_one(): """ >>> fibonacci_one((1,), {}) -> 1 fibonacci_one((0,), {}) -> 0 fibonacci_one((1,), {}) -> 1 fibonacci_one((2,), {}) -> 1 fibonacci_one((3,), {}) -> 2 """ fibonacci_one(3)
5,343,409
def remove(name: str): """ Remove a task by name. Args: name (str): The name of the task to remove. """ click.echo(f"Task removed '{name}'") for task in repository.list(): if task.name == name: repository.remove(task) return click.echo(f"Task '{name}' not found")
5,343,410
def sbatch_set_cores(params: AllocationParameters, args: Dict[str, str]): """Sets the core count by setting `cpus-per-task`. A single task is run per node, which makes this parameter in control of the core count. :param params: Allocation params. :param args: A...
5,343,411
def _indices_3d(f, y, x, py, px, t, nt, interp=True): """Compute time and space indices of parametric line in ``f`` function Parameters ---------- f : :obj:`func` Function computing values of parametric line for stacking y : :obj:`np.ndarray` Slow spatial axis (must be symmetrical a...
5,343,412
def indicators_listing(request,option=None): """ Generate Indicator Listing template. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param option: Whether or not we should generate a CSV (yes if option is "csv") :type option: str :returns: ...
5,343,413
def parse_sensor(csv): """ Ideally, the output from the sensors would be standardized and a simple list to dict conversion would be possible. However, there are differences between the sensors that need to be accommodated. """ lst = csv.split(";") sensor = lst[SENSOR_QUANTITY] if sen...
5,343,414
def samiljeol(year=None): """ :parm year: int :return: Independence Movement Day of Korea """ year = year if year else _year return datetime.date(int(year), 3, 1)
5,343,415
def test_tester_message_output(qtbot, _send_test_msg, _main_ui): """Send a test message and check output log text.""" def check_status(): """Wait for the status to register the transfer.""" assert "Hello from Test Client" in _main_ui.log_widgets.output_text qtbot.waitUntil(check_status)
5,343,416
def get_entries(xml_file): """Get every entry from a given XML file: the words, their roots and their definitions. """ tree = get_tree(xml_file) # each <drv> is one entry entries = [] for drv_node in tree.iter('drv'): node_words = get_words_from_kap(drv_node.find('kap')) ro...
5,343,417
def delete_image(filename): """Delete an item image file from the filesystem. Args: filename (str): Name of file to be deleted. """ try: os.remove(os.path.join(app.config['UPLOAD_FOLDER'], filename)) except OSError as e: print ("Error deleting image file %s") % filename
5,343,418
def comoving_radial_distance(cosmo, a, status): """comoving_radial_distance(cosmology cosmo, double a, int * status) -> double""" return _ccllib.comoving_radial_distance(cosmo, a, status)
5,343,419
def make_legacy_date(date_str): """ Converts a date from the UTC format (used in api v3) to the form in api v2. :param date_str: :return: """ date_obj = dateutil.parser.parse(date_str) try: return date_obj.strftime('%Y%m%d') except: return None
5,343,420
def l2_mat(b1, b2): """b1 has size B x M x D, b2 has size b2 B x N x D, res has size P x M x N Args: b1: b2: Returns: """ b1_norm = b1.pow(2).sum(dim=-1, keepdim=True) b2_norm = b2.pow(2).sum(dim=-1, keepdim=True) res = torch.addmm(b2_norm.transpose(-2, -1), b1, b2.transpo...
5,343,421
def find_files(base, pattern): """Return list of files matching pattern in base folder.""" return [n for n in fnmatch.filter(os.listdir(base), pattern) if os.path.isfile(os.path.join(base, n))]
5,343,422
def SyncDirectory(dir_path): """Flush and sync directory on file system. Python 2.7 does not support os.sync() so this is the closest way to flush file system meta data changes. """ try: dir_fd = os.open(dir_path, os.O_DIRECTORY) os.fsync(dir_fd) except Exception: logging.exception('Failed sync...
5,343,423
def take_rich(frame, n, offset=0, columns=None): """ A take operation which also returns the schema, offset and count of the data. Not part of the "public" API, but used by other operations like inspect """ if n is None: data = frame.collect(columns) else: data = frame.take(n, of...
5,343,424
async def event_response_callback(ven_id, event_id, opt_type): """ Callback that receives the response from a VEN to an Event. """ print(f"VEN {ven_id} responded to Event {event_id} with: {opt_type}")
5,343,425
def default_name(class_or_fn): """Default name for a class or function. This is the naming function by default for registries expecting classes or functions. Args: class_or_fn: class or function to be named. Returns: Default name for registration. """ return camelcase_to_s...
5,343,426
def main(config_file: str, log_level: int) -> int: """Main function Parameters ---------- TODO """ coloredlogs.install( level=log_level * 10, logger=LOG, milliseconds=True, ) # Parse config file config_file = pathlib.Path(config_file).resolve() config = ...
5,343,427
def get_ip_result_by_input_method( set_input_method, module_input_method, var_ip_selector, username, bk_biz_id, bk_supplier_account, filter_set, filter_service_template, produce_method, var_module_name="", ): """ @summary 根据输入方式获取ip @param var_module_name: 模块属性名 @...
5,343,428
def function_size(container: Result) -> Result: """ The size() function applied to a Value. Delegate to Python's :py:func:`len`. (string) -> int string length (bytes) -> int bytes length (list(A)) -> int list size (map(A, B)) -> int map size For other types, this will raise a Python :exc:`...
5,343,429
def cluster_from_metis_config(config): """ Construct a Cluster from a metis-flavored object. Args: config (dict): Metis data. Returns: Cluster """ curie_settings = curie_server_state_pb2.CurieSettings() cluster = curie_settings.Cluster() cluster.cluster_name = config["cluster.name"] log.info...
5,343,430
def test_md041_bad_configuration_front_matter_title_bad(): """ Test to verify that a configuration error is thrown when supplying the front_matter_title value with a bad string. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "--set", "plugins.md041.front_ma...
5,343,431
def _single_style_loss(a, g): """ Calculate the style loss at a certain layer Inputs: a is the feature representation of the real image g is the feature representation of the generated image Output: the style loss at a certain layer (which is E_l in the paper) """ N = a.shape...
5,343,432
def hyp_dist_o(x): """ Computes hyperbolic distance between x and the origin. """ x_norm = x.norm(dim=-1, p=2, keepdim=True) return 2 * arctanh(x_norm)
5,343,433
def is_alive(img, dt): """ This method checks if that server is alive and updates image shown on given widget accordingly. :param img: It is image widget updated according to status of server communication. :param dt: It is for handling callback input. :return: """ try: if database_...
5,343,434
def check_image(url): """A little wrapper for the :func:`get_image_info` function. If the image doesn't match the ``flaskbb_config`` settings it will return a tuple with a the first value is the custom error message and the second value ``False`` for not passing the check. If the check is successful...
5,343,435
def run(x_train, y_train, x_test, y_test, clf): """Train and test""" s = time.time() clf.fit(x_train, y_train) tallies = tally_predictions(clf, x_test, y_test) bmetrics = basic_metrics(tallies) ametrics = advanced_metrics(tallies, bmetrics) pp(tallies, bmetrics, ametrics)
5,343,436
def preprocess(dataset_file_path, len_bound, num_examples = None, reverse = False): """ It reads the required files, creates input output pairs. """ min_sentence_length = len_bound[0] max_sentence_length = len_bound[1] lines = open(str(dataset_file_path), encoding='utf-8', errors = '...
5,343,437
def validate_password_changed(editable): """Get the new password value and validate it""" stager.pages.username_input.PASSWORD = editable.get_text() if ( stager.pages.username_input.PASSWORD is None or stager.pages.username_input.PASSWORD == "" ): stager.utils.BUILDER.get_objec...
5,343,438
def read_transcriptome(transcriptome): """ Parse transcriptome as a dictionary. """ result_dict = {} for sequence in SeqIO.parse(transcriptome, 'fasta'): result_dict[sequence.name] = sequence.seq return result_dict
5,343,439
async def test_validate_tags(hass, mock_nextbus, mock_nextbus_lists): """Test that additional validation against the API is successful.""" # with self.subTest('Valid everything'): assert nextbus.validate_tags(mock_nextbus(), VALID_AGENCY, VALID_ROUTE, VALID_STOP) # with self.subTest('Invalid agency'): ...
5,343,440
def test_zoom2(): """Test the zoom function with invalid values. Zoom should generate an exception""" # create a plane tp = jp.JuliaPlane( 100, 200, -100, 0 ) try: tp.zoom( "one", 100, -1, 3) message = 'Test Failed, zoom did not catch use of an invalid parameter' success = Fals...
5,343,441
def magnus(w, n): """ The 'Magnus' map """ expr = w.subs(x,1+eps*X).subs(y,1+eps*Y) - 1 return limit(expr / eps**n, eps, 0)
5,343,442
def initCmdLineParser(): """ Initiate the optparse object, add all the groups and general command line flags and returns the optparse object """ # Init parser and all general flags logging.debug("initiating command line option parser") usage = "usage: %prog [options]" parser = OptionPar...
5,343,443
def check_regions_and_camera_pairs(regions_dict, camera_pairs_dict): """ Check the regions and camera pairs dictionaries. """ if not regions_dict.keys() == camera_pairs_dict.keys(): raise ValueError, 'regions and camera_pairs dictionaries must have the save region names' for region_cameras i...
5,343,444
def translate_node_coordinates(wn, offset_x, offset_y): """ Translate node coordinates Parameters ----------- wn: wntr WaterNetworkModel A WaterNetworkModel object offset_x: tuple Translation in the x direction, in meters offset_y: float Translation in ...
5,343,445
def get_demo_board(): """Get a demo board""" demo_board_id = 1 query = Board.query.filter(Board.id == demo_board_id) query = query.options(joinedload(Board.tasks)).options(raiseload('*')) board = query.one() return BoardDetailsSchema().dump(board).data
5,343,446
def cool_KI(n, T): """ Returns Koyama & Inutsuka (2002) cooling function """ return 2e-19*n*n*(np.exp(-1.184e5/(T + 1e3)) + 1.4e-9*T**0.5*np.exp(-92.0/T))
5,343,447
def savefig_check(name, path='None'): """ Save a matplotlib figure as sanity check :param name:name of figure """ if not path: path = os.path.join('Figure', 'checks') if not os.path.exists(path): os.makedirs(path) plt.savefig(os.path.join(path, "%s.png" % name))
5,343,448
async def message_deleted(event: Message, app: SirBot): """ Logs all message deletions not made by a bot. """ if not_bot_delete(event): try: logger.info( f'CHANGE_LOGGING: deleted: {event["ts"]} for user: {event["previous_message"]["user"]}\n{event}') except ...
5,343,449
def main(**args): """The main routine.""" if args is None: args = sys.argv[1:]
5,343,450
def main(args): """ main entry point for the manifest CLI """ if len(args) < 2: return usage("Command expected") command = args[1] rest = args[2:] if "create".startswith(command): return cli_create(rest) elif "query".startswith(command): return cli_query(rest) ...
5,343,451
def compute_correlations(states): """compute_correlations. Calculate the average correlation of spin 0 and every other spin. Parameters ---------- states : list of states. ``len(states)`` must be >= 1! Returns ------- correlations : list of floats. """ return [ ...
5,343,452
def parse_sample_str(elems: Sequence[Any]) -> AOList[str]: """ Choose n floats from a distribution. Examples: >>> c = parse_sample_str([4, ["choose", ["one", "two"]]]) >>> c Sample(4, ChooseS([StrConst('one'), StrConst('two')])) """ str_func = "sample" check_n_params(["n", "dist"], e...
5,343,453
def test_load_records(): """Test if loaded records match.""" report = darshan.DarshanReport("tests/input/sample.darshan") report.mod_read_all_records("POSIX") assert 1 == len(report.data['records']['POSIX'])
5,343,454
def htlc(TMPL_RCV, TMPL_OWN, TMPL_FEE, TMPL_HASHIMG, TMPL_HASHFN, TMPL_TIMEOUT): """This contract implements a "hash time lock". The contract will approve transactions spending algos from itself under two circumstances: - If an argument arg_0 is passed to the script ...
5,343,455
def parse(*args, is_flag=False, **kwargs): """alias of parser.parse""" return _parser.parse(*args, is_flag=is_flag, **kwargs)
5,343,456
def check_attrs(res_cls, dset): """ Check dataset attributes extraction """ truth = res_cls.get_attrs(dset=dset) test = res_cls.attrs[dset] msg = "{} attributes do not match!".format(dset) assert truth == test, msg truth = res_cls.get_scale_factor(dset) test = res_cls.scale_factors...
5,343,457
def oauth_callback(): """ return: str """ auth = tweepy.OAuthHandler(env.TWITTER_API_KEY, env.TWITTER_API_SECRET) try: auth.request_token = session['REQUEST_TOKEN'] verifier = request.args.get('oauth_verifier') auth.get_access_token(verifier) session['AUTH_TOKEN'],ses...
5,343,458
def generate_random_instance(n_instants: int, cost_dim: int, items_per_instant: int = 1) -> \ Tuple[List[List[float]], List[List[List[float]]], float, float]: """Generates random values, costs and capacity for a Packing Problem instance. Instances generated here may not respect guarantees constraints. ...
5,343,459
def recommend_tags_questions(professional_id, threshold=0.01, top=5): """ Recommends tags for an professional depending on answered questions. :param professional_id: ID of the professional :param threshold: Minimum percentage of questions with the tags. :param top: Top N recommende...
5,343,460
def simulationtable(request): """ called when the simulation page starts to get used """ from .tools import make_simulationtable from .model import reservoirs from .app import Embalses as App # convert to the right name syntax so you can get the COM ids from the database selected_reserv...
5,343,461
def get_rate_limits(response): """Returns a list of rate limit information from a given response's headers.""" periods = response.headers['X-RateLimit-Period'] if not periods: return [] rate_limits = [] periods = periods.split(',') limits = response.headers['X-RateLimit-Limit'].split('...
5,343,462
def plot_breakdown_percents(runs, event_labels=[], title=None, colors=None): """ Plots a bar chart with the percent of the total wall-time of all events for multiple runs. Parameters ---------- runs: Run object or list of Run objects The list of runs to display...
5,343,463
def test_geometry_get_edges(mk_creoson_post_dict, mk_getactivefile): """Test get_edges.""" c = creopyson.Client() result = c.geometry_get_edges(["12", "34"], file_="file") assert isinstance(result, (list)) result = c.geometry_get_edges(["12", "34"]) assert isinstance(result, (list))
5,343,464
def get_zarr_objs(path: Path): """Find subdir which are zarr obj roots.""" zio = ZarrIO() for r in path.iterdir(): if next(r.glob(".zgroup"), None) is not None: root_group = zarr.group(zio.get_root(r.as_uri())) for g in get_groups_with_arrays(root_group): yiel...
5,343,465
def watcher(event_source, wiki_filter, namespaces_filter, callback): """Watcher captures and filters evens from mediawiki. Args: event_source: an interable source of streaming sse events. wiki_filter: string for filtering 'wiki' class. namespaces_filter: a set() of namespaces to keep. callback: A m...
5,343,466
def main(): """Main method Args: none Returns: void """ htk = Gui.get_instance() htk.mainloop()
5,343,467
def gen3_file(mock_gen3_auth): """ Mock Gen3File with auth """ return Gen3File(endpoint=mock_gen3_auth.endpoint, auth_provider=mock_gen3_auth)
5,343,468
def rhs_of_rule(rule): """ This function takes a grammatical rule, and returns its RHS """ return rule[0]
5,343,469
def smiles_to_antechamber(smiles_string, gaff_mol2_filename, frcmod_filename, residue_name="MOL", strictStereo=False, protonation=False): """Build a molecule from a smiles string and run antechamber, generating GAFF mol2 and frcmod files from a smiles string. Charges will be generated using the OpenEye Qua...
5,343,470
def main(): """Unsubscribe from unwanted newsletters as someone else.""" options = parse_arguments() message = create_message(options) if not options.dry_run: send_mail(message)
5,343,471
def flow_duration_curve( x: Union[np.ndarray, pd.Series], log: bool = True, plot: bool = True, non_exceeding:bool = True, ax: Optional[Union[SubplotBase, Any]] = None, **kwargs ) -> Union[np.ndarray, Figure]: """Calculate a flow duration curve Calculate ...
5,343,472
def filterEndRender(): """Perform actions just after the image has been rendered.""" _logger.debug("filterEndRender") _PYFILTER_MANAGER.run_operations_for_stage("filter_end_render")
5,343,473
def test_ap_hs20_release_number_1(dev, apdev): """Hotspot 2.0 with AP claiming support for Release 1""" run_ap_hs20_release_number(dev, apdev, 1)
5,343,474
def get_fields(filters): """ Return sql fields ready to be used on query """ fields = ( ("(SELECT p.posting_date FROM `tabPurchase Invoice` p Join `tabPurchase Invoice Item` i On p.name = i.parent WHERE i.item_code = `tabItem`.item_code And p.docstatus = 1 limit 1) as pinv_date"), ("CONCAT(`tabItem`._default_...
5,343,475
def timeit_pipeline(rc, num): """ Time how long it takes to run a number of set/get:s inside a cluster pipeline """ for i in range(0, num//2): # noqa s = "foo{0}".format(i) p = rc.pipeline() p.set(s, i) p.get(s) p.execute()
5,343,476
def count_POS_tag(df_pos): """Count how often each POS tag occurs Args: df_pos ([dataframe]): dataframe, where the entries are list of tuples (token, POS tag) Returns: df_pos_stats ([dataframe]): dataframe containing POS tag statistics """ # POS tag list tag_lst = ['CC', 'CD'...
5,343,477
def catch_all(path): """ Gets dummy message. """ return json.dumps({ 'message': 'no one was here', 'ms': get_epochtime_ms() })
5,343,478
def make_archive_obj(filepath, fileobj=None, inmemory_processing=True, allow_unsafe_extraction=False): """This method allows for smart opening of an archive file. Currently this method can handle tar and zip archives. For the tar files, if the python library has issues, the file is attempted to be processed by using...
5,343,479
def fixture_set_log_level_info(caplog): """Set the log-level capture to info for all tests""" caplog.set_level(logging.INFO)
5,343,480
def dimensions_to_space_time_index(dims, t_idx = (), t_len = (), s_idx = (), s_len = (), next_idx_valid = 0, invalid = False, min_port_width = 0, max_port_width = 0, total_time = 0, first_call = True) -> typing.Tupl...
5,343,481
def AtomEditorComponents_Material_AddedToEntity(): """ Summary: Tests the Material component can be added to an entity and has the expected functionality. Test setup: - Wait for Editor idle loop. - Open the "Base" level. Expected Behavior: The component can be added, used in game mode,...
5,343,482
def unparse(input_dict, output=None, encoding='utf-8', **kwargs): """Emit an XML document for the given `input_dict` (reverse of `parse`). The resulting XML document is returned as a string, but if `output` (a file-like object) is specified, it is written there instead. Dictionary keys prefixed with `attr_prefix`...
5,343,483
def test_svgp_vs_gpr_means(with_tf_random_seed, output_dim): """ Test that the SVGP with Gaussian Likelihood and number of inducing points equal to number of data-points gives the same results as GPR. Tested with a mean function. """ svgp, gpr = _svgp_gpr_setup(tuple(), output_dim, LinearMeanFu...
5,343,484
def create_callbacks(model, data, ARGS): """Create keras custom callback with checkpoint and logging""" # Create callbacks if not os.path.exists(ARGS.out_directory): os.makedirs(ARGS.out_directory) # log to Model/log.txt as specified by ARGS.out_directory checkpoint_cb = ModelCheckpoint(fil...
5,343,485
def customization_data(client=None): """ Returns a Generator of ImportDefinitions (Customizations). Install them using `resilient-circuits customize` Contents: - Message Destinations: - fn_ioc_parser_v2 - Functions: - func_ioc_parser_v2 - Workflows: - example_parse_i...
5,343,486
def fetch_or_use_cached(temp_dir, file_name, url): # type: (str, str, str) -> str """ Check for a cached copy of the indicated file in our temp directory. If a copy doesn't exist, download the file. Arg: temp_dir: Local temporary dir file_name: Name of the file within the temp dir, not including the...
5,343,487
def to_bin(val): """ Receive int and return a string in binary. Padded by 32 bits considering 2's complement for negative values """ COMMON_DIGITS = 32 val_str = "{:b}".format(val) # Count '-' in negative case padded_len = len(val_str) + ((COMMON_DIGITS - (len(val_str) % COMMON_DIGITS)) % COMMON...
5,343,488
def PSingle (refLamb2, lamb2, qflux, qsigma, uflux, usigma, err, nterm=2): """ Fit RM, EVPA0 to Q, U flux measurements Also does error analysis Returns array of fitter parameters, errors for each and Chi Squares of fit refLamb2 = Reference lambda^2 for fit (m^2) lamb2 = Array of lambda^2 f...
5,343,489
def exec_waveform_function(wf_func: str, t: np.ndarray, pulse_info: dict) -> np.ndarray: """ Returns the result of the pulse's waveform function. If the wf_func is defined outside quantify-scheduler then the wf_func is dynamically loaded and executed using :func:`~quantify_scheduler.helpers.wavefor...
5,343,490
def generate_straight_pipeline(): """ Simple linear pipeline """ node_scaling = PrimaryNode('scaling') node_ridge = SecondaryNode('ridge', nodes_from=[node_scaling]) node_linear = SecondaryNode('linear', nodes_from=[node_ridge]) pipeline = Pipeline(node_linear) return pipeline
5,343,491
def get_socialnetwork_image_path(instance, filename): """ Builds a dynamic path for SocialNetwork images. This method takes an instance an builds the path like the next pattern: /simplesite/socialnetwork/PAGE_SLUG/slugified-path.ext """ return '{0}/{1}/{2}/{3}'.format(instance._meta.app_label, ...
5,343,492
def policy_gradient(agent, environ, explore=None, *, batch_size, mc, epsilon, baseline): """Training generator under reinforcement learning framework, The rewoard is only the final reward given by environment (predictor). agent (model.Generator): the exploitation network for SMILES string generation en...
5,343,493
def openReadBytesFile(path: str): """ 以只读模式打开二进制文件 :param path: 文件路径 :return: IO文件对象 """ return openFile(path, "rb")
5,343,494
def diff_time(a:datetime.time,b:datetime.time): """ a-b in seconds """ return 3600 * (a.hour -b.hour) + 60*(a.minute-b.minute) + (a.second-b.second) + (a.microsecond-b.microsecond)/1000000
5,343,495
def pytest_after_base_config(base_config, request): """ called after base_config has been initted successfully (and ssh has connected) """
5,343,496
def _create_pseudo_names(tensors, prefix): """Creates pseudo {input | output} names for subclassed Models. Warning: this function should only be used to define default names for `Metics` and `SavedModel`. No other use cases should rely on a `Model`'s input or output names. Example with dict: `{'a': [x1, ...
5,343,497
def search_for_breakpoint(db_name, ids): """ Function will retrieve ID of last caluclated grid node to continue interrupted grid caclulation. :param db_name: str; :param ids: numpy.array; list of grid node ids to calculate in this batch :return: int; grid node from which start the calculation "...
5,343,498
def reddit_client_secret() -> str: """Client secret of the reddit app.""" value = os.getenv("REDDIT_CLIENT_SECRET") if not value: raise ValueError("REDDIT_CLIENT_SECRET environment variable not set") return value
5,343,499