content
stringlengths
22
815k
id
int64
0
4.91M
def weekly(): """The weekly status page.""" db = get_session(current_app) #select id, user_id, created, strftime('%Y%W', created), date(created, 'weekday 1'), content from status order by 4, 2, 3; return render_template( 'status/weekly.html', week=request.args.get('week', None), ...
39,300
def test_names_pattern_names_to_unequal_length(df_checks): """ Raise ValueError if `names_pattern` is a list/tuple and wrong number of items in `names_to`. """ with pytest.raises(ValueError): df_checks.pivot_longer( names_to=["variable"], names_pattern=["1", "rar"] )
39,301
def delete_cached_file(cache, filename): """Delete cached file if present. :param filename: filename to delete """ try: del cache[filename] except KeyError: pass
39,302
def parse_source_files( src_files: List[pathlib.Path], platform_overrides: Sequence[str], ) -> List[LockSpecification]: """ Parse a sequence of dependency specifications from source files Parameters ---------- src_files : Files to parse for dependencies platform_overrides : ...
39,303
def save_dataframe(df: pd.DataFrame, path: pathlib.Path) -> None: """Save the data to a csv file.""" filepath = get_data_filepath(path) df.to_csv(filepath, index=False)
39,304
def delete_registry( service_account_json, project_id, cloud_region, registry_id): """Deletes the specified registry.""" # [START iot_delete_registry] print('Delete registry') client = get_client(service_account_json) registry_name = 'projects/{}/locations/{}/registries/{}'.format( ...
39,305
def test_loop_signals(): """ test the signaling behavior usually SIGINT and SIGTERM lead to normal stop when set to 'ign', this signals will be ignored, causing the loop to continue running only SIGKILL helps now which does not allow the function to...
39,306
def test_link_unpublished_dataset_then_publish_project(driver: selenium.webdriver, *args, **kwargs): """ Test: 1. A dataset can be created and linked to a project 2. The dataset and project can be published together as private with a collaborator 3. The collaborator can import the project and vie...
39,307
def remove_file_or_dir(path): """Remove an existing file or directory.""" if os.path.exists(path): if os.path.isfile(path): os.remove(path) else: shutil.rmtree(path)
39,308
def bundle(cls: type) -> Bundle: """ # Bundle Definition Decorator Converts a class-body full of Bundle-storable attributes (Signals, other Bundles) to an `hdl21.Bundle`. Example Usage: ```python import hdl21 as h @h.bundle class Diff: p = h.Signal() n = h.Signal() ...
39,309
def previousMidnight(when): """Given a time_t 'when', return the greatest time_t <= when that falls on midnight, GMT.""" yyyy, MM, dd = time.gmtime(when)[0:3] return calendar.timegm((yyyy, MM, dd, 0, 0, 0, 0, 0, 0))
39,310
async def test_show_form(hass): """Test that the form is served with no input.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user"
39,311
def list_security_profiles_for_target(nextToken=None, maxResults=None, recursive=None, securityProfileTargetArn=None): """ Lists the Device Defender security profiles attached to a target (thing group). See also: AWS API Documentation Exceptions :example: response = client.list_security_pr...
39,312
def compute_net_results(net, archname, test_data, df): """ For a given network, test on appropriate test data and return dataframes with results and predictions (named obviously) """ pretrain_results = [] pretrain_predictions = [] tune_results = [] tune_predictions = [] for idx in r...
39,313
def _lock_file(f, dotlock=True): """Lock file f using lockf and dot locking.""" dotlock_done = False try: if fcntl: try: fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError as e: if e.errno in (errno.EAGAIN, errno.EACCES): ...
39,314
def save_dates_as_completed(start_date: datetime, end_date: datetime) -> None: """Record the selected dates as completed.""" dates = [(start_date + timedelta(days=i)).isoformat() for i in range((end_date - start_date).days + 1)] with open('completed_dates.txt', 'a') as file: file.write('\n'.join...
39,315
def _distance_along_line(start, end, distance, dist_func, tol): """Point at a distance from start on the segment from start to end. It doesn't matter which coordinate system start is given in, as long as dist_func takes points in that coordinate system. Parameters ---------- start : tuple ...
39,316
def top_level_cli(fragment, *pos_args, **kwargs): """ Runs a default CLI that assists in building and running gateware. If the user's options resulted in the board being programmed, this returns the fragment that was programmed onto the board. Otherwise, it returns None. """ name = fragmen...
39,317
def init_enforcer(policy_file=None, rules=None, default_rule=None, use_conf=True): """Synchronously initializes the policy enforcer :param policy_file: Custom policy file to use, if none is specified, `CONF.oslo_policy.policy_file` will be used. :param rul...
39,318
def exploits_listing(request,option=None): """ Generate the Exploit listing page. :param request: Django request. :type request: :class:`django.http.HttpRequest` :param option: Action to take. :type option: str of either 'jtlist', 'jtdelete', 'csv', or 'inline'. :returns: :class:`django.htt...
39,319
def find_command(tokens: Sequence[str]) -> Tuple[Command, Sequence[str]]: """Looks up a command based on tokens and returns the command if it was found or None if it wasn't..""" if len(tokens) >= 3 and tokens[1] == '=': var_name = tokens[0] command_string = tokens[2:] rvalue, args2 =...
39,320
def clean(df: pd.DataFrame, completelyInsideOtherBias: float = 0.7, filterCutoff: float = 0.65, algo: str = "jaccard", readFromFile: bool = True, writeToFile: bool = True, doBias: bool = True) -> pd.DataFrame: """Main function to completely clean a restaurant dataset. Args: df: a pa...
39,321
def create_list(value, sublist_nb, sublist_size): """ Create a list of len sublist_size, filled with sublist_nb sublists. Each sublist is filled with the value value """ out = [] tmp = [] for i in range(sublist_nb): for j in range(sublist_size): tmp.append(value) out....
39,322
def test_shrink(numbers_1): """ Проверка уменьшения размеров """ s = MovingSum(window=4) for number in numbers_1: s.push(number) assert approx(s.sum) == 170.0 s.resize(3) assert approx(s.sum) == 161.0 reference_small = [82, 72, 58, 56, 47, 96, 98, 144, 89, 83, 50, 53, 60,...
39,323
async def mention_afk(mention): """ This function takes care of notifying the people who mention you that you are AFK.""" global COUNT_MSG global USERS global ISAFK global USER_AFK # pylint:disable=E0602 global afk_time # pylint:disable=E0602 global afk_start global afk_end back_al...
39,324
def before_folder_option(location): """location: folder full path""" if not os.path.exists(location): rpc.create_folder(location) # 如果不存在,通过RPC创建文件夹 rpc.chmod(location, '777', recursive=True) # 通过RPC更改文件夹权限 return True
39,325
def parse_time(date_str: str) -> datetime: """ Parses out a string-formatted date into a well-structured datetime in UTC. Supports any of the following formats: - hh:mm In this format, we treat the value of the hh section to be 24hr format. If a user types in 1:00, it will be interpr...
39,326
def gen_r_cr(): """ Generate the R-Cr table. """ r_cr = [0] * 256 for i in range(256): r_cr[i] = int(1.40199 * (i - 128)) return r_cr
39,327
def fallible_to_exec_result_or_raise( fallible_result: FallibleProcessResult, description: ProductDescription ) -> ProcessResult: """Converts a FallibleProcessResult to a ProcessResult or raises an error.""" if fallible_result.exit_code == 0: return ProcessResult( stdout=fallible_result...
39,328
def combine_phrases_in_corpus(corpus_df, column, min_count=75, n = 1): """ Use gensim phrases to find phrases in the corpus. Args: corpus_df (pandas.DataFrame): the input corpus column (str): the name of the column to be processed min_count (int): min_count hyperparameter of gensim mod...
39,329
def tf_pose_to_coords(tf_pose): """Convert TransformStamped to Coordinates Parameters ---------- tf_pose : geometry_msgs.msg.Transform or geometry_msgs.msg.TransformStamped transform pose. Returns ------- ret : skrobot.coordinates.Coordinates converted coordinates. """ ...
39,330
def make_graph_indep_graphnet_functions(units, node_or_core_input_size, node_or_core_output_size = None, edge_input_size = None, edge_output_size = None, global_input_size = None, global_output_size = None, aggregation_function = 'mean', **kwargs): "...
39,331
def test_brightness_logging_invalid_value(caplog): """Test log messages for invalid brightness value""" init_log(logging.INFO, log_path=None, log_color=False) with tempfile.TemporaryDirectory() as tempdir: with open(os.path.join(tempdir, "brightness"), "w") as f: f.write("INVALID") ...
39,332
def is_generic(t): """ Checks if t is a subclass of typing.Generic. The implementation is done per Python version, as the typing module has changed over time. Args: t (type): Returns: bool """ # Python 3.6, 3.5 if hasattr(typing, "GenericMeta"): if isinstance(t,...
39,333
def getGpsTime(dt): """_getGpsTime returns gps time (seconds since midnight Sat/Sun) for a datetime """ total = 0 days = (dt.weekday()+ 1) % 7 # this makes Sunday = 0, Monday = 1, etc. total += days*3600*24 total += dt.hour * 3600 total += dt.minute * 60 total += dt.second return(tot...
39,334
def test_scraper_output_not_empty(): """ Test to confirm the output dataframe is not empty """ assert data.empty is False
39,335
def make_support_transforms(): """ Transforms for support images during inference stage. For transforms of support images during training, please visit dataset.py and dataset_fewshot.py """ normalize = T.Compose([ T.ToTensor(), T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225...
39,336
def convert_split_ijc(input_files, train_csv, dev_csv): """ Randomly splits the given list of input files into a train/dev with 85/15 split The original datasets only have train & test """ random.seed(1234) train_files = [] dev_files = [] for filename in input_files: if random.r...
39,337
def single_label_normal_score(y_pred, y_gold): """ this function will computer the score by simple compare exact or not Example 1: y_pred=[1,2,3] y_gold=[2,2,3] score is 2/3 Example 2: it can also compute the score same way but for each label y_pred=[1,2,3,2,3] y_gold=[2,2,3,1,3...
39,338
def get_tuning_curves( spike_times: np.ndarray, variable_values: np.ndarray, bins: np.ndarray, n_frames_sample=10000, n_repeats: int = 10, sample_frac: float = 0.4, ) -> dict: """ Get tuning curves of firing rate wrt variables. Spike times and variable values are both in mill...
39,339
def test_continuous_mdr_transform(): """Ensure that the ContinuousMDR 'transform' function maps a new set of feature instances to the desired labels""" features = np.array([ [2, 0], [0, 0], [0, 1], [0, 0], ...
39,340
def writeAtomTypes(atomTypes, out): """ Parameters ---------- atomTypes out Returns ------- """ for a in atomTypes: out.write_out_energy_trajs("{0:>9} {1:>7} {2:>14} {3:>14} {4:>13} {5:>13}\n" .format(a.atomNum, a.atomName, a.sqrtC06, a.sqrtC12_1, a.sqrtC12_2, a.sqrtC12_...
39,341
def plot_18gep(): """ Plot the bolometric LC of 2018gep """ dt, lum, llum, ulum = load_lc() plt.errorbar( dt, lum, yerr=[llum,ulum], fmt='o', c='#140b34', mfc='#140b34', mec='#140b34', lw=0.5, label="SN2018gep")
39,342
def _accelerate_update_fn(forward_and_backward_fn, optimizer, n_devices, accelerate=True): """Accelerate the given forward_and_backward_fn function.""" if n_devices == 1: def single_device_update_fn( weights_and_slots, step, o...
39,343
def test_recursive_update(): """Tests test_recursive_update""" from accelpy._common import recursive_update to_update = {'root1': {'key1': 1, 'key2': 2}, 'key3': 3} update = {'root1': {'key1': 1.0, 'key4': 4.0}, 'key5': 5.0, 'key6': {}} expected = {'root1': {'key1': 1.0, 'key2': 2, 'key4': 4.0}, ...
39,344
def get_custom_feeds_ip_list(client: PrismaCloudComputeClient) -> CommandResults: """ Get all the BlackListed IP addresses in the system. Implement the command 'prisma-cloud-compute-custom-feeds-ip-list' Args: client (PrismaCloudComputeClient): prisma-cloud-compute client. Returns: ...
39,345
def get_dist_egg_link(dist: Distribution) -> Optional[str]: """Is distribution an editable install?""" for path_item in sys.path: egg_link = os.path.join(path_item, dist.project_name + '.egg-link') if os.path.isfile(egg_link): egg_link return None
39,346
def setup_new_file_handler(logger_name, log_level, log_filename, formatter, filter=None): """ Sets up new file handler for given logger :param logger_name: name of logger to which filelogger is added :param log_level: logging level :param log_filename: path to log file :param formatter: formatte...
39,347
def _gen_version(fields): """Looks at BotGroupConfig fields and derives a digest that summarizes them. This digest is going to be sent to the bot in /handshake, and bot would include it in its state (and thus send it with each /poll). If server detects that the bot is using older version of the config, it woul...
39,348
def server_factory(device, count): """ Generate a virtusb server """ controller = VirtualController() controller.devices = [device() for _ in range(count)] server = UsbIpServer(controller) if os.getuid() == 0: #pylint: disable=line-too-long LOGGER.warning('Super user permissions req...
39,349
def get_callee_account(global_state, callee_address, dynamic_loader): """ Gets the callees account from the global_state :param global_state: state to look in :param callee_address: address of the callee :param dynamic_loader: dynamic loader to use :return: Account belonging to callee """ ...
39,350
def get_products_with_summaries() -> Iterable[ProductWithSummary]: """ The list of products that we have generated reports for. """ index_products = {p.name: p for p in STORE.all_dataset_types()} products = [ (index_products[product_name], get_product_summary(product_name)) for produ...
39,351
async def events_handler(value: str) -> None: """Consume scan complete events and mark the execution status as FINISHED.""" try: event = json.loads(value) if event["eventId"] != EventId.SCAN_COMPLETE: return None network_name = event["topologyName"] event_details = js...
39,352
def spotNodes(*args): """spotNodes(*args) : Set the dials spotfinding nodes. You must give 8 nodes. Example: spotNodes(4,5,7,8,12,13,14,15)""" if (len(args) != 8): logger.error("C'mon, I need 8 nodes. No change. Try again.") else: for i in range (0,len(args)): setBlConfig("spotNode"+str(i+1),"cpu-%0...
39,353
def _round_to_4(v): """Rounds up for aligning to the 4-byte word boundary.""" return (v + 3) & ~3
39,354
def cli(dry_run, force, find_links, index_url, extra_index_url, no_index, quiet, user_only, src_files): """Synchronize virtual environment with requirements.txt.""" if not src_files: if os.path.exists(DEFAULT_REQUIREMENTS_FILE): src_files = (DEFAULT_REQUIREMENTS_FILE,) else: ...
39,355
def bool_like(value, name, optional=False, strict=False): """ Convert to bool or raise if not bool_like Parameters ---------- value : object Value to verify name : str Variable name for exceptions optional : bool Flag indicating whether None is allowed strict : b...
39,356
def process_2d_sawtooth(data, period, samplerate, resolution, width, verbose=0, start_zero=True, fig=None): """ Extract a 2D image from a double sawtooth signal Args: data (numpy array): measured trace period (float): period of the full signal samplerate (float): sample rate of the acqu...
39,357
def lower_threshold_projection(projection, thresh=1e3): """ An ugly but effective work around to get a higher-resolution curvature of the great-circle paths. This is useful when plotting the great-circle paths in a relatively small region. Parameters ---------- projection : class ...
39,358
def post_benchmark(name, kwargs=None): """ Postprocess benchmark """ if kwargs is None: kwargs = {} post = benchmarks[name].post return post(**kwargs)
39,359
def test_daterange_attr_vals(): """attribute values""" start_inclusive = datetime.datetime(2020, 4, 1) start_exclusive = datetime.datetime(2020, 3, 31) end_inclusive = datetime.datetime(2020, 4, 30) end_exclusive = datetime.datetime(2020, 5, 1) length = 30 dr = utils.DateRange(start_inclusiv...
39,360
def mark_booked(host_labid, lab_username, booked=True): """ Mark a host as booked/unbooked @host_labid is usually of the form `hpe3` or similar, is the labid of the Server (subtype of Resource) object @lab_username: param of the form `unh_iol` or similar @working: bool, whether by the end of exec...
39,361
def tag_view_pagination_counts(request,hc,urls,tag_with_items): """ retrieve the pagination counts for a tag """ hc.browser.get(urls['https_authority']) try: po = hc.catalog.load_pageobject('TagsPage') po.goto_page() po.search_for_content([tag_with_items]) po = hc....
39,362
def arts_docserver_role(name, rawtext, text, lineno, inliner, options=None, content=None): """Create a link to ARTS docserver. Parameters: name (str): The role name used in the document. rawtext (str): The entire markup snippet, with role. text (str): The text ma...
39,363
def create_central_swhp(standard_parameters): """ todo docstring """ # swhp elec bus create_standard_parameter_bus(label="central_swhp_elec_bus", bus_type="central_swhp_electricity_bus", standard_parameters=standard_p...
39,364
def arima_model(splits, arima_order, graph=False): """ Evaluate an ARIMA model for a given order (p,d,q) and also forecast the next one time step. Split data in train and test. Train the model using t = (1, ..., t) and predict next time step (t+1). Then add (t+1) value from test dataset to history a...
39,365
def srfscc(srfstr, bodyid): """ Translate a surface string, together with a body ID code, to the corresponding surface ID code. The input surface string may contain a name or an integer ID code. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/srfscc_c.html :param srfstr: Su...
39,366
def pr_comment( message: str, repo: str = None, issue: int = None, token=None, server=None, gitlab=False, ): """push comment message to Git system PR/issue :param message: test message :param repo: repo name (org/repo) :param issue: pull-request/issue number :param t...
39,367
def save_input(content, dest_dir, count): """Saves a new input to a file where AFL can find it. File will be named id:XXXXXX,driller (where XXXXXX is the current value of count) and placed in dest_dir. """ name = 'id:%06d,driller' % count with open(os.path.join(dest_dir, name), 'w') as destfile...
39,368
def check_output(command, catch_errors=True): """Execute a command and return the output as a stripped string. """ try: return subprocess.check_output( command, shell=True, stderr=subprocess.STDOUT).decode('utf-8').strip() except subprocess.CalledProcessError as suberror: if catch_errors: ...
39,369
def list_kickstart_profiles(name): """ returns the list of profile name matching the name of kickstart file e.g. http://host:port/cm/v1/cobbler/kickstarts/default.ks/profile """ cp = CobblerProvision() method = request.method if method == "GET": # MUST know how to get user token,...
39,370
def rotate_horizontal_to_vertical(): """ This function checks the height and width of an img to see if it is oriented horizontally. If yes, it will rotate the image 90 degrees counter clockwise. """ dir_images_list = os.listdir(ORIGINAL_IMAGES_PATH) for item in dir_images_list: if item...
39,371
def restart_ssl(rmq_home, env=None): """ Runs rabbitmqctl eval "ssl:stop(), ssl:start()." to make rmq reload ssl certificates. Client connection will get dropped and client should reconnect. :param rmq_home: :param env: Environment to run the RabbitMQ command. :return: """ cmd = [os.path...
39,372
def _install_service(workon=None, level=''): """ install on the service server, need to specify env and level """ if not (workon and level): print red('please specify a environment:\nuseage: fab install:env_name,level') sys.exit(0) pwd = local('pwd', capture=True) localpath, proj...
39,373
def download(model, direct=False, *pip_args): """ Download compatible model from default download path using pip. Model can be shortcut, model name or, if --direct flag is set, full model name with version. """ if direct: dl = download_model('{m}/{m}.tar.gz#egg={m}'.format(m=model), pip_...
39,374
def send_domain_config_updates(event: dict, es_conn, config: dict) -> None: """Updates the Elasticsearch Domain configuration :type: dict :param: event: aws cloudformation custom resource event :type: dict :param: es_conn: Boto3 Elasticsearch client :type: dict :param: config: Complete El...
39,375
def windowed_run_count_1d(arr: Sequence[bool], window: int) -> int: """Return the number of consecutive true values in array for runs at least as long as given duration. Parameters ---------- arr : Sequence[bool] Input array (bool). window : int Minimum duration of consecutive run to ac...
39,376
def archived_attendance_overview(): """ Show archived attendance view """ this_year = 2019 last_year = 2018 attendance = CommitteeMeetingAttendance.annual_attendance_trends( period='historical') # index by year and cte id years = { year: { cte_id: list(cte_gro...
39,377
def start_daemon(args: list) -> int: """Starts daemon process. Arguments: args: Arguments for `subprocess.Popen` (first item must be the daemon filename) Returns: PID for started daemon, or None if start failed. Note: Gracefull shutdown on Windows is tricky. To allow shutdown ...
39,378
def sortbam(args): """ %prog in_dir out_dir in_dir: bam files folder out_dir: sorted bam files folder sort bam files using samtools/0.1 sort function. """ p = OptionParser(sortbam.__doc__) opts, args = p.parse_args(args) if len(args)==0: sys.exit(not p.print_help()) ...
39,379
def mk_event_duration_histograms(figures): """ Plot the events duration distribution per movie run, per data set. """ # do nothing if we don't want to plot if not figures: return datalad_get(op.join('data', 'studyforrest-data-eyemovementlabels')) datapath = op.join('data', ...
39,380
def _get_medical_image_blob(roidb): """ Builds an input blob from the medical image in the roidb """ num_images = len(roidb) processed_ims = [] pre_ims = [] post_ims = [] abdo_masks = [] for i in range(num_images): im = raw_reader(roidb[i]["image"], cfg.MET_TYPE, [roidb[i]["heigh...
39,381
def update_page_fields(page, field_content, *radio_btn_groups): """ Sets the fields in the given PdfFileWriter page to the values contained in argument field_content. Every key in this dictionary must be the name of a field in page. Text fields can be set to any object, which will be converted to a string. Checkbo...
39,382
def test_gca(): """Ensure, that gca returns always an axes instance.""" fig, ax = plt.subplots() assert isinstance(prettypyplot.tools.gca(None), mpl.axes.Axes) assert isinstance(prettypyplot.tools.gca(plt.gca()), mpl.axes.Axes)
39,383
def is_weak(key: object) -> bool: """ Check whether key is weak or not. Key is weak if it is a basic key - not an action and not a modifier. """ return not is_action(key) and not is_mod(key)
39,384
def mock_cei_get_trades(mocker: MockerFixture) -> MockerFixture: """Fixture for mocking report_reader.get_trades.""" return mocker.patch("irpf_investidor.report_reader.get_trades")
39,385
def pql_breakpoint(state: State): """Creates a Python breakpoint. For a Preql breakpoint, use debug() instead """ breakpoint() return objects.null
39,386
def test_no_time(db): """Test an event with no start time set in the YAML""" query = db.query(Event) query = query.filter(Event.year == 2013) query = query.filter(Event.month == 12) query = query.filter(Event.day == 4) event = query.one() assert event.start_time.hour == 19 assert event.s...
39,387
def _normalize(op1, op2, prec = 0): """Normalizes op1, op2 to have the same exp and length of coefficient. Done during addition. """ if op1.exp < op2.exp: tmp = op2 other = op1 else: tmp = op1 other = op2 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision -...
39,388
def change_tags(project_id): """Change the list of tags on a project.""" project = Project.query.get_or_404(project_id) if project.lifetime_stage not in (LifetimeStage.ongoing, LifetimeStage.finalizing): abort(400, {'message': 'Tags can only be modified in ongoing and finalizing stages.'}) if ...
39,389
def sort_db_results(results: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Deterministically sort DB results. Args: results: List[Dict], results from a DB. Returns: List[Dict], sorted DB results. """ sort_order: List[str] = [] if len(results) > 0: sort_order = sorte...
39,390
def classify_one(models, cooccurence_csv): """ Args: cooccurence_csv (str): the CSV file path for the co-occurrence feautres Output: dx (int): the class for diagnosis dx_name (str): the name for diagnosis class """ # Get the features from the CSV file cooc_featur...
39,391
def discretize_q(q, tol=None, lat_range=(-math.pi / 2, math.pi / 2), points=None): """ simulate feature database by giving closest lat & roll with given tolerance and set lon to zero as feature detectors are rotation invariant (in opengl coords) """ if tol is not None and points is not None or tol ...
39,392
def downgrade(): """schema downgrade migrations go here.""" # ### commands auto generated by Alembic - please adjust! ### op.drop_table("events") # ### end Alembic commands ###
39,393
def constant_time_compare(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. """ if len(val1) != len(val2): return False result = 0 if sys.version_info >= (3, 0, 0): # bytes are numbers ...
39,394
def cli( file, task_set, task, ): """Read general settings file and execute specified task.""" # read general settings file and assign content to global settings object shdw.config.settings.get_settings(file) # get the specified task and imort it as module task_module =...
39,395
def generate_testdata( pars: dataclass, ntrials: int = 1, baseclass: Union[object, None] = None, func: Union[object, None] = None, exp_test_set: bool=True, ): """ meanrate is in Hz(events/second) maxt is in seconds - duration of trace bigevent is a dict {'t': delayinsec, ...
39,396
def has_param(param): """ Generate function, which will check `param` is in html element. This function can be used as parameter for .find() method in HTMLElement. """ def has_param_closure(element): """ Look for `param` in `element`. """ if element.params.get(param,...
39,397
def neg_log_likeDUN(output, target, sigma, cat): """ function to compute expected loss across different network depths inputs: - preds_list, list of predictions for different depths - targets, single set of targets - noise, aleatoric noise (length 12) - cat, variational categorical distribut...
39,398
def shoot(C, D, b, maxiter=1000, abs_tol=1e-7): """Return random equality set of P that projects on a projection facet. Returns randomly selected equality set E_0 of P such that the projection of the equality set is a facet of the projection. @param C: Matrix defining the polytope Cx+Dy <= b @para...
39,399