content
stringlengths
22
815k
id
int64
0
4.91M
def trace_sqrt_product_tf(cov1, cov2): """ This function calculates trace(sqrt(cov1 * cov2)) This code is inspired from: https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/contrib/gan/python/eval/python/classifier_metrics_impl.py :param cov1: :param cov2: :return: """ ...
48,200
def opennem_serialize(obj: Any, indent: Optional[int] = None) -> str: """Use custom OpenNEM serializer which supports custom types and GeoJSON""" obj_deserialized = None if not obj_deserialized: obj_deserialized = json.dumps(obj, cls=OpenNEMGeoJSONEncoder, indent=indent) return obj_deserialize...
48,201
def min_vector(first_atom, second_atom, cell=None): """Helper to find mimimum image criterion distance.""" if cell is None: cell = first_atom._parent.cell.cell return min_vect(first_atom.pos, first_atom.fractional, second_atom.pos, second_a...
48,202
def dice_coeff_2label(pred, target): """This definition generalize to real valued pred and target vector. This should be differentiable. pred: tensor with first dimension as batch target: tensor with first dimension as batch """ target = target.data.cpu() # pred = torch.sigmoid(pred) # ...
48,203
def cost_arrhenius(p, T, rate): """ Sum of absolute deviations of obs and arrhenius function. Parameters ---------- p : iterable of floats `p[0]` is activation energy [J] x : float or array_like of floats independent variable y : float or array_like of floats depende...
48,204
def get_ou_accounts_by_ou_name(ou_name, accounts_list=None, parent=None): """ Returns the account of an OU by itsname Args: ou_name: name of the OU accounts_list: list of accounts from a previous call due to the recursive next_token: the token for the call in case a recursive occurs ...
48,205
def test_backward_for_remote_unary_cmd_local_autograd(workers, cmd): """ Test .backward() on unary methods on remote tensors using implicit wrapping """ alice = workers["alice"] a = torch.tensor([0.3, 0.2, 0], requires_grad=True) a = a.send(alice, local_autograd=True) a_torch = torch.t...
48,206
def split_result_of_axis_func_pandas(axis, num_splits, result, length_list=None): """Split the Pandas result evenly based on the provided number of splits. Args: axis: The axis to split across. num_splits: The number of even splits to create. result: The result of the computation. This ...
48,207
def is_icypaw_scalar_type_annotation(obj): """Return if the object is usable as an icypaw scalar type annotation.""" if isinstance(obj, type) and issubclass(obj, IcypawScalarType): return True return False
48,208
def gcs_batched_data(request, gcs_bucket, dest_dataset, dest_table) -> List[storage.blob.Blob]: """ upload two batches of data """ data_objs = [] for batch in ["batch0", "batch1"]: for test_file in ["part-m-00000", "part-m-00001", "_SUCCESS"]: data_obj: storage.b...
48,209
def pair_is_inward(read, regionlength): """Determine if pair is pointing inward""" return read_is_inward(read, regionlength) and mate_is_inward(read, regionlength)
48,210
def lambda_handler(event, context): """ Call the main function """ print(event) # check if it's the original invokation or not. if is_the_original_invokation(event): # original invocation. Go on as usual ugetter = UrlsGetter() domains = ugetter.get_domains_list() ...
48,211
async def test_climate(hass: HomeAssistant): """Test setup and state change of a climate device.""" entry = configure_integration(hass) test_gateway = HomeControlMockClimate() test_gateway.devices["Test"].value = 20 with patch( "homeassistant.components.devolo_home_control.HomeControl", ...
48,212
def tpf(args): """ %prog tpf agpfile Print out a list of ids, one per line. Also known as the Tiling Path. AC225490.9 chr6 Can optionally output scaffold gaps. """ p = OptionParser(tpf.__doc__) p.add_option("--noversion", default=False, action="store_true", help="Remove t...
48,213
def download_from_scihub(entry): """Try to download PDF from sci-hub""" doi = entry["doi"] scihub_url = "https://sci-hub.tw/" scihub_request = requests.get(f"{scihub_url}{doi}") for line in scihub_request.iter_lines(): if b"iframe" in line and b"pdf" in line: pdflink = line...
48,214
def send_request(url, payload): """ Send http request. :param url: The url to access. :param payload: The payload to send. :return: None if request failed, Response content if request ok. """ logging.debug(f'Request {url} with payload:\n{payload}') retries = Retry( total=10, ...
48,215
def sort_by_game(game_walker, from_locale, pack): """Sort a pack by the order in which strings appears in the game files. This is one of the slowest sorting method. If the pack contains strings that are not present in the game, they are sorted alphabetically at the end and a message is logged.""" ...
48,216
def main(args: Sequence[str]) -> int: """ Entry for the program. """ try: user_args = parse_args(args) bus = bootstrap_petronia(user_args) return run_petronia(bus, user_args) except BaseException as err: # pylint: disable=broad-except if isinstance(err, SystemExit): ...
48,217
def to_query_str(params): """Converts a dict of params to a query string. Args: params (dict): A dictionary of parameters, where each key is a parameter name, and each value is either a string or something that can be converted into a string. If `params` is a list, i...
48,218
def histogram(backend, qureg): """ Make a measurement outcome probability histogram for the given qubits. Args: backend (BasicEngine): A ProjectQ backend qureg (list of qubits and/or quregs): The qubits, for which to make the histogram Returns: A tuple (fig, axes, p...
48,219
def crop(sequence, minimum, maximum, key=None, extend=False): """ Calculates crop indices for given sequence and range. Optionally the range can be extended by adding additional adjacent points to each side. Such extension might be useful to display zoomed lines etc. Note that this method assumes th...
48,220
def main(argv: typing.List[str]): """Main entry point.""" options = [ f"--NotebookApp.port={FLAGS.port}", f"--NotebookApp.open_browser={FLAGS.browser}", ] # Optionally enable server to be used as a local runtime for Google # Colaboratory. if FLAGS.with_colaboratory: options += [ "--Notebo...
48,221
def reverse_dict(dict_obj): """Reverse a dict, so each value in it maps to a sorted list of its keys. Parameters ---------- dict_obj : dict A key-value dict. Returns ------- dict A dict where each value maps to a sorted list of all the unique keys that mapped to it....
48,222
def chunks(iterator, n): """ Yield the next chunk if an iterable object. A chunk consists of maximum n elements. """ for first in iterator: rest_of_chunk = itertools.islice(iterator, 0, n - 1) yield itertools.chain([first], rest_of_chunk)
48,223
def assert_equal(actual: numpy.ndarray, desired: numpy.ndarray, err_msg: int): """ usage.scipy: 4 """ ...
48,224
def remote_error_known(): """Return a remote "error" code.""" return {"errorType": 1}
48,225
def orga(ctx): """ Every registered user can belong to one or multiple organisations and can get authorized for the projects of that organisation. This command group manages information about your organisations. You can see all organizations you belong to with the :ref:`list command<reference/orga:list>...
48,226
def get_throttling_plan(js: str): """Extract the "throttling plan". The "throttling plan" is a list of tuples used for calling functions in the c array. The first element of the tuple is the index of the function to call, and any remaining elements of the tuple are arguments to pass to that functio...
48,227
def gcs_download(bucket_name, output_dir, prefix): """ Downloads files from Google Cloud Storage bucket, allows one to specify a prefix """ logger = logging.getLogger("get_raw -- {}".format("gcs_download")) logger.info('Getting Conntents of bucket {} with prefix {}.'.format(bucket_name, prefix)) if ...
48,228
def parse_home(): """Extract links from news, and create dir with today's date.""" try: response = get(HOME_URL) if response.status_code == 200: home = response.content.decode('utf-8') parsed = html.fromstring(home) links_to_notices = parsed.xpath(XPATH_LINK_T...
48,229
def list_agg(object_list, func): """Aggregation function for a list of objects.""" ret = [] for elm in object_list: ret.append(func(elm)) return ret
48,230
def job_metadata_api(**kwargs: dict) -> Callable[[dict], str]: """ Job Metadata API route. Arguments: kwargs: required keyword arguments Returns: JSON response """ return job_resource.job_metadata_api(**kwargs)
48,231
def parse_word(word: str) -> str: """Compile a word of uppercase letters as numeric digits. Non-uppercase letter words are returned unchanged.""" if not word.isupper(): return word compiled_word = " + ".join([letter + "*" + str(10**index) for index, letter in enumerate(word[:: -1])]) return "(" ...
48,232
def rayleigh(gamma, M0, TtR): """ Function that takes in a input (output) Mach number and a stagnation temperature ratio and yields an output (input) Mach number, according to the Rayleigh flow equation. The function also outputs the stagnation pressure ratio Inputs: M [dimension...
48,233
def attack(N, e, c, oracle): """ Recovers the plaintext from the ciphertext using the LSB oracle attack. :param N: the modulus :param e: the public exponent :param c: the encrypted message :param oracle: a function which returns the last bit of a plaintext for a given ciphertext :return: the...
48,234
def setup_wandb_logging( trainer: Engine, optimizers: Optional[Union[Optimizer, Dict[str, Optimizer]]] = None, evaluators: Optional[Union[Engine, Dict[str, Engine]]] = None, log_every_iters: int = 100, **kwargs: Any ): """Method to setup WandB logging on trainer and a list of evaluators. Logged ...
48,235
def _norm(X, y): """Scales data to [0..1] interval""" X = X.astype(np.float32) / (X.max() - X.min()) return X, y
48,236
def check_directory(directory, verbose): """ Inputs: graph_directory- the directory for the graphs to be place verbose- the verbose flag Checks to see if the graph directory exists. If it doesn't exit, the folder is created. """ cwd = os.getcwd() + '/' if not os.pa...
48,237
def compute_single_lesson_score( lesson_metadata: Dict[str, Any], df: pd.DataFrame, slide_columns: List[str], due_date: datetime.datetime, ) -> pd.Series: """Takes a DataFrame from an Ed export of completions and a str representing the due date and returns a Series (indexed by email) of the stud...
48,238
def test_list_deployment_table(): """Simple sanity check for listing deployments with a table output. The more specific testing is done in unit tests. """ with _zero_instance_app(): _start_app('zero-instance-app', _ZERO_INSTANCE_APP_INSTANCES) assert_lines(['dcos', 'marathon', 'deploym...
48,239
async def delete_layer(location_id, layer_id): """ Delete layer --- delete: summary: Delete layer tags: - layers parameters: - name: id in: path required: true description: ID of the object to be deleted responses: ...
48,240
def fit_and_save_model(params, data, targets): """Fit xgb classifier pipeline with params parameters and save it to disk""" pipe = make_pipeline(StandardScaler(), XGBClassifier(learning_rate=params['learning_rate'], max_depth=int(params['m...
48,241
def relu_backward(dout, cache): """ Backward pass for the ReLU function layer. Arguments: dout: numpy array of gradient of output passed from next layer with any shape cache: tuple (x) Output: x: numpy array of gradient for input with same shape of dout ...
48,242
def main(ctx, nosync, verbose, config, key): """ Run the NextClound Note Command Line Interface. No COMMAND means to open the console GUI. """ ctx.obj = Nncli(not nosync, verbose, config) if ctx.invoked_subcommand is None: ctx.obj.gui(key) elif not nosync: ctx.obj.ndb.sync_no...
48,243
def test_mg_l009_mg_l009_v(mode, save_output, output_format): """ TEST :model groups (ALL) : choice: with 5 elements, 1 element in the instant XML doc """ assert_bindings( schema="msData/modelGroups/mgL009.xsd", instance="msData/modelGroups/mgL009.xml", class_name="Doc", ...
48,244
def test_label_match(do, neuroblastoma, pediatric_liposarcoma, compare_records): """Test that label searches resolve to correct records.""" response = do.search('pediatric liposarcoma') assert response['match_type'] == MatchType.ALIAS assert len(response['records']) == 1 actual_...
48,245
def visualize(**images): """PLot images in one row.""" n = len(images) plt.figure(figsize=(160, 50)) # print(images.items()) for i, (name, image) in enumerate(images.items()): plt.subplot(1, n, i + 1) plt.xticks([]) plt.yticks([]) plt.title(' '.join(name.spli...
48,246
def run_decopath(request): """Process file submission page.""" # Get current user current_user = request.user user_email = current_user.email # Check if user submits pathway analysis results if 'submit_results' in request.POST: # Populate form with data from the request results...
48,247
def load_abs_pos_sighan_plus(dataset=None, path_head=""): """ Temporary deprecation ! for abs pos bert """ print("Loading Expanded Abs_Pos Bert SigHan Dataset ...") train_pkg, valid_pkg, test_pkg = load_raw_lattice(path_head=path_head) tokenizer_model_name_path="hfl/chinese-roberta-wwm-e...
48,248
def _train_on_tpu_system(model_fn_wrapper, dequeue_fn): """Executes `model_fn_wrapper` multiple times on all TPU shards.""" config = model_fn_wrapper.config.tpu_config iterations_per_loop = config.iterations_per_loop num_shards = config.num_shards single_tpu_train_step = model_fn_wrapper.convert_to_single_tp...
48,249
def inject_app_defaults(application): """Inject an application's default settings""" try: __import__('%s.settings' % application) import sys # Import our defaults, project defaults, and project settings _app_settings = sys.modules['%s.settings' % application] _def_settin...
48,250
def get_docs_url(model): """ Return the documentation URL for the specified model. """ return f'{settings.STATIC_URL}docs/models/{model._meta.app_label}/{model._meta.model_name}/'
48,251
def _fetch_random_words(n=1000): """Generate a random list of words""" # Ensure the same words each run random.seed(42) # Download the corpus if not present nltk.download('words') word_list = nltk.corpus.words.words() random.shuffle(word_list) random_words = word_list[:n] retur...
48,252
def cache_pdf(pdf, document_number, metadata_url): """Update submission metadata and cache comment PDF.""" url = SignedUrl.generate() content_disposition = generate_content_disposition(document_number, draft=False) s3_client.put_object( Body...
48,253
def get_tile_list(geom, zoom=17): """Generate the Tile List for The Tasking List Parameters ---------- geom: shapely geometry of area. zoom : int Zoom Level for Tiles One or more zoom levels. Yields ------ list of tiles that intersect with """ west,...
48,254
def test_get_hw_info(test_host_with_build, fake_request): """ Tests for functioning of collect_hw_info function """ expected = { "arches": ["ppc", "ppc64le"], "CPU(s)": 8, "Ram": 24050560, "Disk": "198G", "Kernel": "4.18.0-193.28.1.el8_2.ppc64le", "Operati...
48,255
def findTolerableError(log, file='data/psf4x.fits', oversample=4.0, psfs=10000, iterations=7, sigma=0.75): """ Calculate ellipticity and size for PSFs of different scaling when there is a residual pixel-to-pixel variations. """ #read in PSF and renormalize it data = pf.getdata(file) data /= ...
48,256
async def remove(context: 'Context', game: str, yes: bool = False): """Command to remove a game from the guild.""" discord_context = context.obj["discord_context"] game_config = await sync_to_async(GameConfig.get_by_game_alias)( game, discord_context.guild.id ) if game_config is None...
48,257
def squeeze_labels(labels): """Set labels to range(0, objects+1)""" label_ids = np.unique([r.label for r in measure.regionprops(labels)]) for new_label, label_id in zip(range(1, label_ids.size), label_ids[1:]): labels[labels == label_id] == new_label return labels
48,258
def orient_edges_gs2(edge_dict, Mb, data, alpha): """ Similar algorithm as above, but slightly modified for speed? Need to test. """ d_edge_dict = dict([(rv,[]) for rv in edge_dict]) for X in edge_dict.keys(): for Y in edge_dict[X]: nxy = set(edge_dict[X]) - set(edge_dict[Y]) - {Y} for Z in nxy: if Y ...
48,259
def _divide_evenly(start, end, max_width): """ Evenly divides the interval between ``start`` and ``end`` into intervals that are at most ``max_width`` wide. Arguments --------- start : float Start of the interval end : float End of the interval max_width : float ...
48,260
def render_gup(): """GuP のアプリケーションを処理する関数""" character_and_quotes = { 'Miho Nishizumi': 'パンツァーフォー', 'Saori Takebe': 'やだもー', 'Hana Isuzu': '私この試合絶対勝ちたいです', 'Yukari Akiyama': '最高だぜ!', 'Mako Reizen': '以上だ', } selected_items = st.multiselect('What are your favorite ch...
48,261
def uncompress_pubkey(pubkey): """ Convert compressed public key to uncompressed public key. Args: pubkey (str): Hex encoded 33Byte compressed public key Return: str: Hex encoded uncompressed 65byte public key (4 + x + y). """ public_pair = encoding.sec_to_public_pair(h2b(pubkey)) ...
48,262
def make_celery(main_flask_app): """Generates the celery object and ties it to the main Flask app object""" celery = Celery(main_flask_app.import_name, include=["feed.celery_periodic.tasks"]) celery.config_from_object(envs.get(main_flask_app.config.get("ENV"), "config.DevConfig")) task_base = celery.T...
48,263
def remove_bucket_iam_binding(iam_policy, role): """Remove existing binding matching the role.""" iam_policy['bindings'] = [ binding for binding in iam_policy['bindings'] if binding['role'] != role ]
48,264
def adjustForWeekdays(dateIn): """ Returns a date based on whether or not the input date is on a weekend. If the input date falls on a Saturday or Sunday, the return is the date on the following Monday. If not, it returns the original date. """ #If Saturday, return the following Monday. if dat...
48,265
def composed_model_input_classes(cls): """ This function returns a list of the possible models that can be accepted as inputs. TODO: lru_cache this """ if issubclass(cls, ModelSimple) or cls in PRIMITIVE_TYPES: return [cls] elif issubclass(cls, ModelNormal): if cls.discrimina...
48,266
def via_sudo(): """ Return `True` if Blueprint was invoked via `sudo`(8), which indicates that privileges must be dropped when writing to the filesystem. """ return 'SUDO_UID' in os.environ \ and 'SUDO_GID' in os.environ \ and 'blueprint' in os.environ.get('SUDO_COMMAND', '')
48,267
def validate_file_destination(namespace): """Validate the destination path for a file download.""" try: path = namespace.destination except AttributeError: return else: # TODO: Need to confirm this logic... file_path = path file_dir = os.path.dirname(path) ...
48,268
async def main(host, port, username, password, params, events): """Main function.""" LOGGER.info("Connecting to Axis device") device = await axis_device(host, port, username, password) if not device: LOGGER.error("Couldn't connect to Axis device") return if params: loop = ...
48,269
def get_user_or_add_user(spotify_id, display_name, display_image=None, token=None): """Fetch an existing user or create a user""" user = User.query.filter(User.spotify_id == spotify_id).first() if user is None: spotify_id = spotify_id spotify_display_name = display_name spotify_im...
48,270
def get_daily_data(y, m, d, icao): """ grab daily weather data for an airport from wunderground.com parameter --------- y: year m: month d: day ICAO: ICAO identification number for an airport return ------ a dictionary containing ...
48,271
def add_special_tokens(vocab): """Processing the vocab, add special tokens Args: vocab: list of words, string """ assert not PAD_TOKEN in vocab assert not UNKNOWN_TOKEN in vocab assert not START_DECODING in vocab assert not STOP_DECODING in vocab assert not NUMBER in vocab ...
48,272
def create_CIM_object(cimpath): """This function aims to speed up other bits of this and ``cgrid`` modules, by returning a ``casacore.images.image.image`` object. The trick is, that the ``cimpath`` argument can be either a string i.e. the path to the CASAImage wich will be read in and returned, **or** ...
48,273
def image_tag_create(context, image_id, value, session=None): """Create an image tag.""" session = session or get_session() tag_ref = models.ImageTag(image_id=image_id, value=value) tag_ref.save(session=session) return tag_ref['value']
48,274
def compile_model(model, loss, optimizer, metrics): """Compile model for training. Args: model : Model to compile loss : Loss function optimizer : Optimizer of training metrics : target metric """ model.compile(loss=loss, optimizer=optimizer, metrics=[...
48,275
def test_branch_same_shape(): """ Feature: control flow function. Description: Two branch must return the same shape. Expectation: Null. """ class Net(Cell): def __init__(self): super().__init__() self.a = 1 def construct(self, x, y): for k i...
48,276
def turn_blocks_to_diamonds(): """Listens for any block events (right-clicks on blocks while holding the sword) and converts any such block to a diamond block.""" while True: # Each time this is called, it will return a list of all the events # that happened since the last time you called it. ...
48,277
def potential(__func__=None, **kwds): """ Decorator function instantiating potentials. Usage: @potential def B(parent_name = ., ...) return baz(parent_name, ...) where baz returns the deterministic B's value conditional on its parents. :SeeAlso: Deterministic, deterministic,...
48,278
def numBytes(qimage): """Compatibility function btw. PyQt4 and PyQt5""" try: return qimage.numBytes() except AttributeError: return qimage.byteCount()
48,279
def _dt_to_decimal_time(datetime): """Convert a datetime.datetime object into a fraction of a day float. Take the decimal part of the date converted to number of days from 01/01/0001 and return it. It gives fraction of way through day: the time.""" datetime_decimal = date2num(datetime) time_d...
48,280
def connect_text_edit_pushbutton_apply_abstract(scene): """Be an abstract pushButton callback function for applying text edit.""" scene.edit.add_undo_item(scene)
48,281
def poll_create(event, context): """ Return true if the resource has been created and false otherwise so CloudFormation polls again. """ endpoint_name = get_endpoint_name(event) logger.info("Polling for update of endpoint: %s", endpoint_name) return is_endpoint_ready(endpoint_name)
48,282
def outsatstats_all(percent, Reads_per_CB, counts, inputbcs): """Take input from downsampled bam stats and returns df of genes, UMIs and reads for each bc. Args: percent (int): The percent the bamfile was downsampled. Reads_per_CB (file path): Space delimited file of the barcodes and # of reads...
48,283
def relative_uri(source, target): """ Make a relative URI from source to target. """ su = patched_urllib_parse.urlparse(source) tu = patched_urllib_parse.urlparse(target) extra = list(tu[3:]) relative = None if tu[0] == '' and tu[1] == '': if tu[2] == su[2]: relative ...
48,284
def Rename_Field(filename, OldFieldName, NewFieldName, Type): """renames field of file""" arcpy.AddField_management(filename, NewFieldName, Type, '#', '#', '#', '#', 'NULLABLE', 'NON_REQUIRED', '#') arcpy.management.CalculateField(filename, NewFieldName, "!{}!".format(OldFieldName), "PYTHON_9.3", None) ...
48,285
def fill_gaps_batch(slice_list, acq_datelist, training_data_path, cluster_model_path, outDir=None, cpu=20, reg_kws=None): """ This function fills gaps for a slice of time series. Parameters ---------- slice_list: list Specification of list of slice time series file. ...
48,286
def generate_sums( n: int, min_terms: int, max_terms: int, *, seed=12345, fold=False, choose_from=None ) -> Optional[List[ExprWithEnv]]: """ Generate the specified number of example expressions (with no duplicates). The constants used in the expressions will normally have a maximum value of 2, b...
48,287
def rename_and_grant_session12(dbobj): """ Getting admindb object """ sessionid = ObjectId("4ed62213114d971078000000") conn = dbobj.connection db = conn["bev1"] sessionobj = db["sessions"].find_one({"_id" : sessionid}) print "Before Session Label: ", sessionobj["label"] newname = "...
48,288
def convert_from_string(str_input_xml): """Convert a string into a Python data structure type. > *Input arguments* * `str_input_xml` (*type:* `str`): Input string > *Returns* `bool`, `int`, `float`, list of `float` or `str`. """ import string if str_input_xml is None: return ...
48,289
def arr2pil(frame: npt.NDArray[np.uint8]) -> Image.Image: """Convert from ``frame`` (BGR ``npt.NDArray``) to ``image`` (RGB ``Image.Image``) Args: frame (npt.NDArray[np.uint8]) : A BGR ``npt.NDArray``. Returns: Image.Image: A RGB ``Image.Image`` """ return Image.fromarray(cv2.cvtCo...
48,290
def test_add_writer_after_closing(loop, sock_pair): """Verify that we can remove a reader callback from an event loop.""" client_sock, srv_sock = sock_pair loop.close() with pytest.raises(RuntimeError): loop.add_writer(client_sock.fileno(), lambda: None)
48,291
def parallel_worker(params): """ @param params: a bunch of parameter packed into a sequence """ # unpack the params user_params, hmm_params = params f_in, d_out, niterations = user_params letter_to_emission, trans, emiss = hmm_params trans = np.array(trans) emiss = np.array(emiss) ...
48,292
def sophos_firewall_app_category_update_command(client: Client, params: dict) -> CommandResults: """Update an existing object Args: client (Client): Sophos XG Firewall Client params (dict): params to update the object with Returns: CommandResults: Command results object """ ...
48,293
def make_dicts(): """ Grabs the RSS data and makes a dictionary out of the wanted information """ print('*** NPR ***') print('Fetching NPR Front Page feed...') for article in front_feed['entries']: front.append({ "title": article.title, "description": article.summary, ...
48,294
def rerender_on_view_change(node: View, context: RenderingContext): """Subscribes to name change and renders new view""" node.observe('name', lambda _, __: _rerender_view(node, context))
48,295
def find_identities(l): """ Takes in a list and returns a dictionary with seqs as keys and positions of identical elements in list as values. argvs: l = list, e.g. mat[:,x] """ # the number of items in the list will be the number of unique types uniq = [item for item, count in collections.Coun...
48,296
def decode_event_to_internal2(event): """ Enforce the binary encoding of address for internal usage. """ data = event.event_data # Note: All addresses inside the event_data must be decoded. if data['event'] == EVENT_TOKEN_ADDED2: data['token_network_address'] = to_canonical_address(data['args']...
48,297
def _repeated_features(n, n_informative, X): """Randomly select and copy n features from X, from the col range [0 ... n_informative]. """ Xrep = np.zeros((X.shape[0], n)) for jj in range(n): rand_info_col = np.random.random_integers(0, n_informative - 1) Xrep[:, jj] = X[:, rand_info...
48,298
def test_list_events_command(requests_mock) -> None: """ Scenario: List events. Given: - User has provided valid credentials. - Headers and JWT token have been set. When: - list_events_command is called. Then: - Ensure number of items is correct. - Ensure outputs prefix is c...
48,299