content
stringlengths
22
815k
id
int64
0
4.91M
def det_cont_fct_accum(err, pred, obs): """Accumulate the forecast error in the verification error object. Parameters ---------- err: dict A verification error object initialized with :py:func:`pysteps.verification.detcontscores.det_cont_fct_init`. pred: array_like Array of ...
70,400
def main(req: func.HttpRequest) -> func.HttpResponse: """main function""" logging.info("Getting table data") datatype = req.route_params.get("datatype") if not datatype: logging.error("No datatype provided") return func.HttpResponse( body='{"status": "Please pass a name on ...
70,401
async def test_get_public_photos_empty(mocker): """It should return an empty list when the object returned is empty.""" get = create_session_get_callable({}) mocker.patch.object(flickr.session, 'get', new_callable=get) assert await flickr.get_public_photos('abcd', 1, 10) == []
70,402
def test_alif(Simulator, plt): """Test ALIF and ALIFRate by comparing them to each other""" n = 100 max_rates = 50 * np.ones(n) intercepts = np.linspace(-0.99, 0.99, n) encoders = np.ones((n, 1)) nparams = dict(tau_n=1, inc_n=10e-3) eparams = dict( n_neurons=n, max_rates=max_rates, ...
70,403
def parse_message_timestamp(date_str) -> Optional[dt.datetime]: """Parses the message timestamp string and converts to a python datetime object. If the string cannot be parsed then None is returned.""" timestamp: Optional[dt.datetime] = None try: timestamp = dt.datetime.strptime(date_str, MAIL...
70,404
def norm(x: List[List[int]], ord: int, axis: int): """ usage.scipy: 1 """ ...
70,405
def test_pattern_matching(gallery_conf, log_collector): """Test if only examples matching pattern are executed.""" gallery_conf.update(filename_pattern=re.escape(os.sep) + 'plot_0') code_output = ('\n Out:\n\n .. code-block:: none\n' '\n' ' Óscar output\n' ...
70,406
def expectation_values_to_real(expectation_values: ExpectationValues) -> ExpectationValues: """Remove the imaginary parts of the expectation values Args: expectation_values (zquantum.core.measurement.ExpectationValues object) Returns: expectation_values (zquantum.core.measurement.Expectatio...
70,407
def dbpool(): """ Returns the unique database pool for this process. Most often there is only a single pool per-process, so we provide this function as a global starting point for getting connections. Use it like this: from antipool import dbpool ... conn = dbpool().connection() ...
70,408
def view_group_email(group_name): """View for email form to members""" if request.method == "GET": # Get group information group = get_group_info(group_name, session) # Get User's Group Status unix_name = session["unix_name"] user_status = get_user_group_status(unix_name,...
70,409
def run_ghub(): """Run GHub""" colorama.init() print("Welcome to GHub - Browse GitHub like it is UNIX") print("Starting initial setup...") ghub = GHub() interpreter = Interpreter() print("Setup done.") while True: print( "ghub:{} {}>".format( colored(g...
70,410
def vgg_net(inputs, num_classes=1000, spatial_squeeze=True, name='vgg_a', global_pool=True, pruning_method='baseline', init_method='baseline', data_format='channels_last', width=1., prune_last_layer=True, ...
70,411
def get_articles(url): """Returns article links, images, and titles as a list of dictionaries""" page = requests.get(url) page_content = page.content soup = BeautifulSoup(page_content, features="html.parser") posts = soup.find_all("div", {"class": "td-block-span6"}) articles = [] # Scrap...
70,412
def test_estimate_board_posture(): """Test the estimate_board_posture function.""" c = camera_fusion.CameraCorrected(0, 11) shutil.rmtree('data') shutil.copytree('./tests/test_CameraCorrected', 'data') c.calibrate_camera_correction() real_captured_frame = np.load('./data/real_captured_frame.npy'...
70,413
def is_raster_directory_three_bands(directory_name, new_directory_name): """ Sorts through entire directory and moves one banded images into another directory """ for filename in os.listdir(directory_name): if is_raster_three_bands(filename) is False: move_file(filename, new_dire...
70,414
def present_species(species): """Given a vector of species of atoms, compute the unique species present. Arguments: species (:class:`torch.Tensor`): 1D vector of shape ``(atoms,)`` Returns: :class:`torch.Tensor`: 1D vector storing present atom types sorted. """ present_species = sp...
70,415
def linkcheck_status_filter(status_message): """ Due to a long status entry for a single kind of faulty link, this filter reduced the output when display in list view :param status_message: error description :type status_message: str :return: a concise message :rtype: str """ if not...
70,416
def complex_pad_simple(xfft, fft_size): """ >>> # Typical use case. >>> xfft = tensor([[[1.0, 2.0], [3.0, 4.0], [4.0, 5.0]]]) >>> expected_xfft_pad = tensor([[[1.0, 2.0], [3.0, 4.0], [4.0, 5.0], ... [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]]]) >>> half_fft_size = xfft.shape[-2] + 3 >>> fft_size = (...
70,417
def update_parameters(updates): """ Takes a list of strings and values for updating parameters in the parameter dictionary Example: updates = [(key, val), (key, val)] """ print('Updating parameters...') for key, val in updates.items(): par[key] = val print('Updating ', key) ...
70,418
def extract_result(log): """Extracts the name of each test condition run""" module_name = log['testInfo']["testName"] str="" for d in log['results']: src = d['src'] if src == 'WebRunner' or src == 'BROWSER' or src == module_name: # these are asyncronous and the order isn't pr...
70,419
def prepare_y_train(add_noise_trajectory: Traj) -> np.ndarray: """ Prepare y values for training, which are (cy, cx) of data points in noise-added trajectory. :param add_noise_trajectory: the trajectory with noise added :return: x values for training, of size n x 1 """ return prepare_y_values(a...
70,420
def doPredictionStatic(ui: UtopiaDataInterface, clsfr: BaseSequence2Sequence, model_apply_type:str='trial', timeout_ms:float=None, block_step_ms:float=100, maxDecisLen_ms:float=8000): """ do the prediction stage = basically extract data/msgs from trial start and generate a prediction from them ''' Args: ...
70,421
def extract_barrier_polygons(gdb_path, target_crs): """Extract NHDArea records that are barrier types. Parameters ---------- gdb_path : str path to the NHD HUC4 Geodatabase target_crs: GeoPandas CRS object target CRS to project NHD to for analysis, like length calculations. ...
70,422
def p2pv(p): """ Extend a p-vector to a pv-vector by appending a zero velocity. :param p: p-vector to extend. :type p: array-like of shape (1,3) :returns: pv-vector as a numpy.matrix of shape 2x3. .. seealso:: |MANUAL| page 142 """ pv = _np.asmatrix(_np.zeros(shape=(2,3), dtype=float, ord...
70,423
def create_experiment( database_session: Session, experiment: schema_experiment.ExperimentBase ): """Add Experiment to DB""" db_experiment = models.Experiment(**experiment.dict()) database_session.add(db_experiment) database_session.commit() database_session.refresh(db_experiment) return db_...
70,424
def apply_filter(signal, window): """Apply filter window to a signal. for now datatype should be using numpy types such as 'np.int16' the entire file is read assuming datatype so header length should be specified in words of the same bit length filter_frequency should be supplied in units of sampling rate fil...
70,425
def call_bash_command(param): """ Sample :param param: Sample param """ print("My param: {}, current dir: {}".format(param, os.curdir)) # result = 1 result = execute(param) print("Result of '{param}' was {result}".format(param=param, result=result))
70,426
def compute_affinity_matrix(X): """Compute the affinity matrix from data. Note that the range of affinity is [0,1]. Args: X: numpy array of shape (n_samples, n_features) Returns: affinity: numpy array of shape (n_samples, n_samples) """ # Normalize the data. l2_norms = np....
70,427
def delete_rtbs(ec2, args, dryrun): """ Delete the route tables """ try: rtbs = ec2.describe_route_tables(**args)['RouteTables'] except ClientError as e: print(e.response['Error']['Message']) if rtbs: for rtb in rtbs: main = 'false' for assoc in rtb['Associations']: main = as...
70,428
def auto_add(repo, autooptions, files): """ Cleanup the paths and add """ # Get the mappings and keys. mapping = { ".": "" } if (('import' in autooptions) and ('directory-mapping' in autooptions['import'])): mapping = autooptions['import']['directory-mapping'] # Apply the lo...
70,429
def trace_fn(current_state, kernel_results, summary_freq=10, callbacks=()): """ Can be passed to the HMC kernel to obtain a trace of intermediate kernel results and histograms of the network parameters in Tensorboard. """ # step = kernel_results.step # with tf.summary.record_if(tf.equal(step % s...
70,430
def test_list_eq(): """Check List equal method.""" float_list = List(Float()) int_list = List(Int()) assert float_list == List(Float()) assert int_list == List(Int()) assert float_list != [1.0, 2.0] assert float_list != 1.3 assert float_list != int_list assert float_list != Int() ...
70,431
def pyramid_settings(): """Return the default app settings.""" return {"sqlalchemy.url": TEST_DATABASE_URL}
70,432
def train(action_set, level_names): """Train.""" if is_single_machine(): local_job_device = '' shared_job_device = '' is_actor_fn = lambda i: True is_learner = True global_variable_device = '/gpu' server = tf.train.Server.create_local_server() server_target = FLAGS.master filters = ...
70,433
def get_uniqueid(scan, x_grid, y_grid): """Reads the student's ID from the form. """ uniqueid = [] for char_num in range(8): bubble_intensities = [read_bubble(scan, x_grid[UNIQUEID_X+char_num], y_grid[UNIQUEID_Y+y]) for y in range(36)]...
70,434
def _init_redis(app): """Initializes Redis client from app config.""" app.config.setdefault('REDIS_HOST', 'localhost') app.config.setdefault('REDIS_PORT', 6379) app.config.setdefault('REDIS_DB', 0) app.config.setdefault('REDIS_PASSWORD', None) return redis.Redis(host=app.config['REDIS_HOST'], ...
70,435
def _add_cmdline_quotes(cmd_str: str) -> str: """Add extra quotes to command line string containing SQL variables. DB_PATH='C:\\temp\\crdm\\data\\BD:mdf' => DB_PATH="'C:\\temp\\crdm\\data\\BD:mdf'" Arguments --------- cmd_str Command line string containing SQL variables. Returns -...
70,436
def _log_unnormalized_prob_logits(logits, counts, total_count): """Log unnormalized probability from logits.""" logits = tf.convert_to_tensor(logits) return (-tf.math.multiply_no_nan(tf.math.softplus(-logits), counts) - tf.math.multiply_no_nan( tf.math.softplus(logits), total_count - count...
70,437
def eom_spfs(nel,nmodes,nspfs,npbfs,spfstart,spfend,uopspfs,copspfs,copips, huelterms,hcelterms,spfovs,A,spfs,mfs=None,rhos=None,projs=None): """Evaluates the equation of motion for the mctdh single particle funcitons. """ # create output array spfsout = np.zeros(nel, dtype=np.ndarray) ...
70,438
def state_view(decoy: Decoy) -> StateView: """Get a mocked out StateView.""" return decoy.mock(cls=StateView)
70,439
def _tweet_for_template(tweet, https=False): """Return the dict needed for tweets.html to render a tweet + replies.""" data = json.loads(tweet.raw_json) parsed_date = parsedate(data['created_at']) date = datetime(*parsed_date[0:6]) # Recursively fetch replies. if settings.CC_SHOW_REPLIES: ...
70,440
def create_inventory(options, inventory_path): """Create Ansible inventory.yml file in the specified ceek directory""" hosts = options.hosts.split(',') cfgyaml = {} #Set flavor cfgyaml["all"] = {} cfgyaml["all"]["vars"] = {} cfgyaml["all"]["vars"]["cluster_name"] = "_".join(["ceek", optio...
70,441
def catalog_collection( context, resource, name, inventory, chassis_id, workaround ): """ Catalogs a collection of resources for the inventory list Args: context: The Redfish client object with an open session resource: The resource with the array name: The name of the property of t...
70,442
def add_mask( adata: AnnData, imgpath: Union[Path, str], key: str = "mask", copy: bool = False, ) -> Optional[AnnData]: """\ Adding binary mask image to the Anndata object Parameters ---------- adata Anndata object. imgpath Image mask path. key Label ...
70,443
def response_page(): """Fixture to response page.""" txt = read_file(str(Path(__file__).parent / "data/page.txt")) resp = Response() resp.status_code = 200 resp._content = str.encode(txt) return resp
70,444
def main(): """main function""" score = round(Run([DIRECTORY_TO_LINT], exit=False).linter.stats["global_note"], 2) # pylint: disable=line-too-long template = '<svg xmlns="http://www.w3.org/2000/svg" width="85" height="20"><linearGradient id="a" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-...
70,445
def create_list_of_mass_balances_engine( list_species, element_list, idx_control, feed_list, closing_equation_type, initial_feed_mass_balance, fixed_elements, ): """ Gives the list of mass balances Possible equations (besides reactions and charge): - Mass balance Cations ...
70,446
def get_module_root(path): """ Get closest module's root beginning from path # Given: # /foo/bar/module_dir/static/src/... get_module_root('/foo/bar/module_dir/static/') # returns '/foo/bar/module_dir' get_module_root('/foo/bar/module_dir/') # returns '/foo/bar...
70,447
def decode_text(payload, charset, default_charset): """ Try to decode text content by trying multiple charset until success. First try I{charset}, else try I{default_charset} finally try popular charsets in order : ascii, utf-8, utf-16, windows-1252, cp850 If all fail then use I{default_charset} and...
70,448
def pql_import_json(state: State, table_name: T.string, uri: T.string): """Imports a json file into a new table. Returns the newly created table. Parameters: table_name: The name of the table to create uri: A path or URI to the JSON file Note: This function requires the `panda...
70,449
def read_dataset(train_batch_size: int = 32, eval_batch_size: int = 128, train_mode: str = 'pretrain', strategy: tf.distribute.Strategy = None, topology=None, dataset: str = 'cifar10', train_split: str = 'train', eval_split: str = 'test', data_dir: str = None, image_si...
70,450
def load(dirpath): """Load a saved python model.""" file_path = os.path.join(dirpath, _CONFIG_FILE) with tf.io.gfile.GFile(file_path, 'r') as f: config_json = f.read() config_dict = json_utils.decode(config_json) return deserialize_keras_object(config_dict)
70,451
def _get_stock_yfinance_names(stocks_ibkr_csv_p): """Convert IBKR short names to YF names and check if actually valid.""" with open(stocks_ibkr_csv_p, 'r') as f: r = csv.reader(f) symbol_col = exch_col = None symbols_yf = {} for row in r: if not row or row[0] != 'Financial Instrument Informati...
70,452
def image_to_ndarray(filename, convert_grey=True, cmap=None, debug=False): """ Convert an image to a numpy array using pillow. Matplotlib only supports the PNG format. :param filename: absolute path of the image to open :param convert_grey: if True and the number of layers is 3, it will be convert...
70,453
def test_graph_to_paths_length(): """test if output has correct length""" num_branches = 179 assert len(paths) == num_branches
70,454
def GetAverageNewRunTime(finished_seq_file, window=100):#{{{ """Get average running time of the newrun tasks for the last x number of sequences """ logger = logging.getLogger(__name__) avg_newrun_time = -1.0 if not os.path.exists(finished_seq_file): return avg_newrun_time else: i...
70,455
def profile_main(size=200): """" Main with profiler. """ with cProfile.Profile() as pr: init_prefixes() sum_sg(size) s = io.StringIO() sort_by = pstats.SortKey.CUMULATIVE ps = pstats.Stats(pr, stream=s).sort_stats('tottime') ps.print_stats() print(s.getvalue())
70,456
def test_run_dry_multiple_packages(murlopen, tmpfile, capsys): """dry run should edit the requirements.txt file and print hashes and package name in the console """ def mocked_get(url, **options): if url == "https://pypi.org/pypi/hashin/json": return _Response( { ...
70,457
def get_scaled_cutout_wdhtdp_view(shp, p1, p2, new_dims): """ Like get_scaled_cutout_wdht, but returns the view/slice to extract from an image instead of the extraction itself. """ x1, y1, z1 = p1 x2, y2, z2 = p2 new_wd, new_ht, new_dp = new_dims x1, y1, x2, y2 = int(x1), int(y1), int(x...
70,458
def cron_expression(trigger): """Get a cron expression from the given trigger""" _LOGGER.debug('trigger.fields: %r', trigger.fields) # Need to loop through, as it is an array and not in the same Cron # expression order, thus we need to insert into the proper order. fields = ['*'] * len(_FIELD_NAMES)...
70,459
def get_tp(gold, guess): """ Args: gold (Iterable[T]): guess (Iterable[T]): Returns: Set[T] """ return get_correct(gold, guess)
70,460
def delete_secret(ctx, secret_id, prod=False): """ Deletes a secret from aws secrets manager. """ region = get_env_region(prod) full_secret_id = get_secret_id(secret_id) command = DELETE_SECRET_COMMAND.format(aws_region=region, secret_name=full_secret_id) print(f'Deleting secret {full_secret_id}...'...
70,461
def insert(container, key_path, item): """ >>> insert({}, ['a', '1', '2', 'world'], 'hello') {'a': {'1': {'2': {'world': 'hello'}}}} """ if isinstance(container, collections.OrderedDict): gen = collections.OrderedDict update = lambda i, k, v: i.update({k: v}) else: gen = ...
70,462
def complementary_sequence(seq: str) -> str: """ >>> complementary_sequence('ATCG') 'TAGC' """ # TODO (gdingle): refactor with fastqs reverse_complement seq_map = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'} return ''.join([seq_map[c] for c in seq.upper()])
70,463
def construct_edge_feature_gather(feature, knn_inds): """Construct edge feature for each point (or regarded as a node) using torch.gather Args: feature (torch.Tensor): point features, (batch_size, channels, num_nodes), knn_inds (torch.Tensor): indices of k-nearest neighbour, (batch_size, nu...
70,464
def _prepare_data_fn(features, target='label', flatten=True, return_batch_as_tuple=True, seed=None): """ Resize image to expected dimensions, and opt. apply some random transformations. :param features: Data :param target Target/ground-truth data to be r...
70,465
def _get_sentinel_event(): """Generate a sentinel event for terminating worker.""" return Event()
70,466
def _process_pip_requirements( default_pip_requirements, pip_requirements=None, extra_pip_requirements=None ): """ Processes `pip_requirements` and `extra_pip_requirements` passed to `mlflow.*.save_model` or `mlflow.*.log_model`, and returns a tuple of (conda_env, pip_requirements, pip_constraints). ...
70,467
def _parse_standings(d): """ Used to parse the standings of a competition. """ standings = [] for o in d.get("teams", []): info = CompetitionStanding(o) standings.append(info) return standings
70,468
def dev(): """Internal command""" pass
70,469
def _convert_internal(parsed_ctds, **kwargs): """ parse all input files into models using CTDopts (via utils) @param parsed_ctds the ctds @param kwargs skip_tools, required_tools, and additional parameters for expand_macros, create_command, create_inputs, create_outputs @return a tuple cont...
70,470
def bind_prop( prop_name: str, prop_type: Type[Variable], default: T, doc: Optional[str] = None, doc_add_type=True, objtype=False, ) -> property: """Define getters and setters for a named property backed by the map's var mapping. :meta private: """ # Removed "-> T" type ann...
70,471
def get_vpip_players(hand: Hand) -> Indications: """ Return an indication of the players that were VPIP for the hand. Voluntary Put In Pot (VPIP) means the player volunteered to put money into the pot pre-flop. """ return _get_players_making_actions(hand.preflop, (Bet, Raise, Call))
70,472
def find_version(*file_paths): """Find version information in file.""" path = os.path.join(os.path.dirname(__file__), *file_paths) version_file = open(path).read() version_pattern = r"^__version__ = ['\"]([^'\"]*)['\"]" version_match = re.search(version_pattern, version_file, re.M) if version_ma...
70,473
def canonicalize_name(name: str) -> str: """ Normalize the name strings from certificates and emails so that they hopefully match. """ name = name.upper() for c in "-.,<> ": name = name.replace(c, "") return name
70,474
def test_game_play_diagonal() -> None: """RED should be able to fill the diagonal while YELLOW does nothing but help.""" moves = [0, 1, 1, 2, 2, 3, 2, 3, 3, 5, 3] def mock_input(s: str) -> int: return moves.pop(0) game = Game() with patch("connect_four.game.input", mock_input): gam...
70,475
def get_exec_time(total_execs=1, _repeat=1): """ basically here we calculate the average time it takes to run this function or block of code """ def inner_wrapper(_function, *args, **kwargs): computational_times = timeit.repeat( lambda: _function(*args, **kwargs), number=total_execs, repeat=_repeat ...
70,476
def find_in_map(obj, *args): """ It accepts the dict object and nested keys and return the value of last key if present in nested key is present in object. Args: obj (dict): dict object Returns: Value of last nested key """ if not isinstance(obj, dict): # raise InvalidReque...
70,477
def generate_index_page(albums: List[Album]) -> None: """ Generate the main site's index.html page. :param albums: list of Album objects :type albums: List[Album] :returns: None :rtype: None """ html = Tag(name="html") # Add in head element html.append(make_head_element(0...
70,478
async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up scene platform from Hue group scenes.""" bridge: HueBridge = hass.data[DOMAIN][config_entry.entry_id] api: HueBridgeV2 = bridge.api if bridge.api_versio...
70,479
def get_trace_xml_filename(config, absolute=False): """Get the trace XML filename to put XML data into""" trace_dir = get_trace_dir(config, absolute) xml_filename = "%s.twx" % config["top_module"] xml_filename = os.path.join(trace_dir, xml_filename) return xml_filename
70,480
def parse_from_file_msg(fp): """ Parsing email from file Outlook msg. Args: fp (string): file path of raw Outlook email Returns: Instance of MailParser with raw email parsed """ return MailParser.from_file_msg(fp)
70,481
def simple_5reciprocal(x, a, b): """ reciprocal function to fit convergence data """ c = 0.5 if isinstance(x, list): y_l = [] for x_v in x: y_l.append(a + b / x_v ** c) y = np.array(y_l) else: y = a + b / x ** c return y
70,482
def get_user_group(user: User, user_group_id: int) -> UserGroup: """ Get a user group. :param user :param user_group_id: :return: """ user_group = UserGroup.query.filter_by(id=user_group_id).first() if user_group is None: raise NotFoundException(f'No user group with id {user_grou...
70,483
def test_accuracy(backend, shape, ndim, axes, dtype, inplace, norm, use_lut, r2c=False, dct=False, gpu_name=None, stream=None, queue=None, return_array=False, init_array=None, verbose=False, colour_output=False, ref_long_double=True): """ Measure the :param backend: eithe...
70,484
def negate_value(func): """negate value decorator.""" def do_negation(name, value): print("decorate: we can change return values by negating value") return -value return do_negation
70,485
def validate_twilio_request(f): """Validates that incoming requests genuinely originated from Twilio""" @wraps(f) def decorated_function(request, *args, **kwargs): # Create an instance of the RequestValidator class validator = RequestValidator(settings.TWILIO_AUTH_TOKEN) url = reque...
70,486
def ignored_nicks(): """A generator of nicks from which notifications should be ignored.""" for nick in split_option_value('ignore_nicks'): yield nick
70,487
def test_average_radial_intensity(): """ Basic tests of angular averaging. """ R = 50 # image radius n, ones, cos2, sin2 = make_images(R) def check(name, ref, atol, IM, **kwargs): with catch_warnings(): simplefilter('ignore', category=DeprecationWarning) r, inte...
70,488
def setup_logging(): """ Logging Function. Creates a global log object and sets its level. """ global log log = logging.getLogger() log_levels = {'INFO': 20, 'WARNING': 30, 'ERROR': 40} if 'logging_level' in os.environ: log_level = os.environ['logging_level'].upper() if...
70,489
def readable_memory_size(bytes_): """Convert number of bytes into human readable form, eg '1.2 Kb'. """ return _readable_units(bytes_, memory_divs)
70,490
def get_labels (num, ltype='twoclass'): """Return labels used for classification. @param num Number of labels @param ltype Type of labels, either twoclass or series. @return Tuple to contain the labels as numbers in a tuple and labels as objects digestable for Shogun. """ labels=[] if ltype=='twoclass': labe...
70,491
def main(): """ Command-line interface for Lookup and Store Tweets utility. """ parser = argparse.ArgumentParser( description="""Lookup and Store Tweets utility. Fetches a tweet from the Twitter API given its GUID. Stores or updates the author Profile and Tweet in the db....
70,492
def read_msg(buf:bytes) -> tuple: """ first the size prefix and then the corresponding msg payload """ if len(buf) < 4: return (0, "", buf) size = struct.unpack("!I", buf[0:4])[0] logger.debug("read_msg: size: %d", size) if len(buf) - 4 >= size: text = struct.unpack("!%ds" % size, bu...
70,493
def conv3x3(x,K): """3x3 convolution with padding""" return F.conv2d(x, K, stride=1, padding=1)
70,494
def test_TaurusValueCombobox(): """Check that the TaurusValueComboBox is started with the right display See https://github.com/taurus-org/taurus/pull/1032 """ # TODO: Parameterize this test app = TaurusApplication.instance() if app is None: app = TaurusApplication(cmd_line_parser=None) ...
70,495
def alert_factory(site, rule, data_point): """ Creating an alert object """ # Getting the last alert for rule point = rule.alert_point.last() alert_obj = None # If the last alert exists does not exist if point is None: alert_obj = create_alert_instance(site, rule, data_point) # i...
70,496
def _get_average_time(callable_name): """Returns the average_time in seconds for the passed-in callable name. :param str callable_name: The name of the callable. :returns: The average_time in seconds for the passed-in callable name. :rtype: float """ return _ProfilingStatCollection.get_stats_...
70,497
def rolling_integral(x0, periods, function=None): """ Integrate a function over a rolling window ending in the interval. :param x0: Variable or Parameter; the interval under consideration :param periods: the width of the rolling window :param function: a function from float to float to be integrate...
70,498
def test_build_has_cosmic_ids( adapter, case_obj, ): """Test building query to retrieve all variants with cosmic IDs""" case_id = case_obj["_id"] query = {"cosmic_tag": True} mongo_query = adapter.build_query(case_id, query=query) assert {"cosmic_ids": {"$exists": True}} in mongo_query["$a...
70,499