content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_vocabulary(inputs, key_words=[]): """ Create a vocabulary object from a sentence or a list of sentence :param inputs: :param vocab_size: :param key_words: :return: """ vocab = Vocabulary() vocab.set_key_words(key_words) if isinstance(inputs[0], list): # inp...
72539c2300daf22f142c851d0d706a55014f7b3d
61,000
def playerScoresDict(tournament_num): """Get playerScores() in dictionary form.""" players_list = playerScores(tournament_num) players_dict = {str(player[0]): player for player in players_list} return players_dict
50c9301a8074bcb134684927ee6451fb82701927
61,001
def get_chem_names(particles): """ Create a list of chemical names for the dispersed phase particles Reads the composition attribute of each particle in a `particles` list and compiles a unique list of particle names. Parameters ---------- particles : list of `Particle` objects ...
7b1a462732b6bdd389fb0d9c2b80aab5a5f385d5
61,002
import requests def get_APOD(date): """This will do the request on the NASA api""" payload = 'https://api.nasa.gov/planetary/apod' params = {'api_key' : 'DEMO_KEY', 'date' : date} response = requests.get(payload, params = params) return response.json()
45cdbadd7c67a71033e506fdc8a2358e8f7d8c09
61,003
import sys def train_weak_signals(data, n_weak_functions): """ Trains weak signals :param data: dictionary of training, cross validation and test data :type data: dict :param n_weak_functions: number of weak signals to be trained :type n_weak_functions: int :return: dictionary containing ...
3efe8bcd493e6a4d256b6d92b3481ec490d60754
61,004
def test_no_args(capsys, flat_mode): """ Tests that the no-args example works in both modes """ if not flat_mode: @decorator def replace_with_hello(): """ Decorator to replace anything with the 'hello' string. """ def _apply_decorator(f): ...
02d9204dbf9984736bd4d3c806881a58a3972b5b
61,005
def validate_active_image(method): """The decorator to validate the active image to be not `None`.""" @wraps(method) def wrapper(self, *args): if not self.active_image: QMessageBox.warning(self, "There is no uploaded image", "Please, open an image using\n" ...
07139485879efc77678f9e08694531b9b7f815fe
61,006
def calc_out_size_1d_maxpool(in_size, ksize, stride, padding): """ Calculates output size on one dimension. :param in_size: [int] Input size. :param ksize: [int] Kernel size. :param stride: [int] Stride size. :param pad: [string] Padding method, `SAME` or `VALID`. :...
ace5e17f761db5cb32d1b88f8aafb7506f9842e6
61,007
import re def replace_with_dict( s, d ): """ replaces the substrings in the dictionary keys with their values Parameters ---------- s: string d: dict Returns ------- string Examples -------- >>>s1 = "asdf qwer" >>>d1 = { 'asdf', 'foo' } >>>d2 = { 'qwer', 'bar...
c7e185860eb3e13f65cdf614301c1a5afed894f9
61,008
from typing import Union import pathlib import io from typing import Optional from typing import Dict from typing import Any from typing import Tuple import zipfile import warnings import os def load_from_zip_file( load_path: Union[str, pathlib.Path, io.BufferedIOBase], load_data: bool = True, custom_obje...
fc1fb8137d47c3468b5d03898eee20146a14120c
61,009
import numpy as np def mape(predictions, actuals): """ Calcuate Mean Absoute Percentage Error (MAPE) Reported as percentage Parameters ---------- predictions: numpy array of predicted values actuals: numpy array of actual values Returns ------- Returns float of calculate...
560b5960cfdf870b2d9954419140d85d3d8a5a27
61,010
def completed_project_incidents(request): """ incident for specific project """ project_id = request.GET.get('project_id') template = loader.get_template('project_management/completed_incidents.html') project = Project.objects.get(id=project_id) state = True if ProjectTeam.objects...
d85c46ba1872ca3273aedc6af39be6ef70ec9a13
61,011
from typing import Set def uniq(a: Tensor) -> Set: """ return unique element of Tensor Use python Optimized mode to skip assert statement. :rtype set :param a: input tensor :return: Set(a_npized) """ return set([x.item() for x in a.unique()])
29bd1d63a2adeecfeb8a33439c5030c7fdaaf5ac
61,012
def env_cfg_path() -> str: """Get a L5 environment config file from artefacts. Note: the scope of this fixture is "session"-> one per test session :return: the L5Kit gym-compatible environment config python dict """ env_cfg_path = "./l5kit/tests/artefacts/gym_config.yaml" return env_cfg_path
d762e1ee39a54fab6cd3f00961a552801eeddcc6
61,013
def to_timestamp(value): """ Convert datetime to a timestamp string MediaWiki would understand. :type value: datetime :rtype str """ # datetime.isoformat() wouldn't work because it sometimes produces +00:00 # that MW does not support. # Also perform sanity check here to make sure this is...
4acb92d65060ada4e0d783c1eef5b108bd81f88f
61,014
from typing import Annotated def remove_completer( name: Annotated[str, Arg(completer=complete_completer_names)], ): """Removes a completer from xonsh Parameters ---------- name: NAME is a unique name of a completer (run "completer list" to see the current completers in order) ...
e439000162d7baad0f673416dec89e73791a02d9
61,015
def unhandled_intent_handler(handler_input): """Handler for all other unhandled requests.""" # type: (HandlerInput) -> Response speech = "Say yes to continue or no to end the game!!" handler_input.response_builder.speak(speech).ask(speech) return handler_input.response_builder.response
2ff305a4a70b45797fda5f89cd0accae23fc9a96
61,016
from typing import List import os from typing import Dict import tempfile from pathlib import Path def compute_semeval_2013_metrics( gold_labels: List, pred_labels: List, group_by: List[str], context_ids: List[str], gold_labels_path: os.PathLike = None, ) -> Dict[str, List[float]]: """ TOD...
bce365fd7cfd1d0dee84e97659506cbf9842634d
61,017
import ast def _find_all(self, node_type): """Finds all nodes defined by string node_type :param node_type: the string representing the "type" of node to look for :return: a list of Ast Nodes (easy_nodes) of self that are of the specified type (including self if self meets that criteria) ...
fb887a459cbf37b79da0b3fe8afd970f8b5bfd09
61,018
def stresslet_kernel_source_target_stkfmm(r_source, r_target, normal, density, eta=1.0, reg=5e-3, ...
29d64cec601d376b9d859363f202ce0a2d874486
61,019
def LSTNetModel(task, window, rnn_type, skip_rnn_type, continuous_columns, categorical_columns, cnn_filters, kernel_size, rnn_units, rnn_layers, skip_rnn_units, skip_rnn_layers, skip_period, ar_order, drop_rate=0., nb_outputs=1, nb_steps=1, out_activation='linear', **kwargs): """Long-and Short-term ...
75a4ba1d4a90e484f1c411cb0d172a5609061f3d
61,020
def provide_help(): """ send an api syntax error status and show the correct usage of the api Return: return a dictionary with keys 'syntax', 'status' , 'description' specifying error & help """ # reference syntax syntax_str = 'HOST:PORT/geocode?address=ADDRESS' # description of par...
cf76a136d6b7e64a06f8a740972a391d8945b03d
61,021
def rmask_byte(num_mask_bits,value): """ This function applies a right-justified mask of a specified number of bits to an unsigned integer representing a single byte value. >>> rmask_byte(3,list(b'\\xff')[0]) 7 >>> bin(7) '0b111' """ return ((1<<(num_mask_bits))-1) & value
156fe1797590c5418a28db13b1064dfdb4e7bc4c
61,022
def strip_predicate(predicate: Predicate) -> Predicate: """Remove classifier from predicate to make new Predicate.""" return Predicate(predicate.name, predicate.types, lambda s, o: False)
7c01cf2de85c11511af18f2538fe70e2d390750b
61,023
def convert_to_complex_spec( X, X_phase, decom, phase_type, add_dc=False, est_phase_opts=None): """ X/X_phase - matrix of shape (..., n_channel, n_time, n_frequency) decom - `mp`: magnitude (in dB) / phase (in rad) decomposition `ri`: real / imaginary decomposit...
4571efc21e7af29512ca69fb517f0234e004ff83
61,024
def json_str_to_compas_obj(json_str): # type: (str) -> compas.data.Data """Convert JSON string to object based on :class:`compas.data.Data`.""" return compas.data.json_loads(json_str)
63064dc6a777c799e97f90525f92c6e4faca8457
61,025
async def truth(_: Request) -> dict: """Get a random truth question.""" truth_resp = get_random_text_response("truths") return {"truth": truth_resp}
606666357bc1ae04ae4de8d7a543017ccc4d1ca7
61,026
def normalized_name(name): """Return normalized name with special chars like slash, colon, etc normalized to hyphen(-). This is important as otherwise these chars break local and cloud storage paths.""" return SPECIAL_CHARS_REGEX.sub('-', name).strip('-')
c311bdcc9b9d0541cce1b993853d054946df059f
61,027
def download_records(accessions, verbose=False, wait=5, retries=3, taxon_id=9606): """Download records for each UniProt accession via the UniProt API. The call will retry upon timeout up to the number specified by `retries`. Parameters ---------- accession : str UniPr...
705cc2fca39982ca6c91b19089035e2fae99781d
61,028
def split_tail(biggest_vertex: Vertex, original_vertex: Vertex) -> Vertex: """Get the split tail of the vertex Args: biggest_vertex: The vertex with the biggest id in the original graph original_vertex: Vertex in the original graph Returns: New split vertex that is a tail of all ar...
a60fab3c810635d14ad758d6e964609c2f1222c3
61,029
import os def generateKMeansPCA(filemanager): """ Generates a table of cluster_number and file name from the active files. Args: None Returns: kmeansIndex.tolist(): a list of index of the closest center of the file silttScore: a float of silhouette score based on KMeans algor...
d6a822bf83a3eb3cc8db0d2d940dde511bcba458
61,030
from datetime import datetime import uuid import random def plugin_poll(handle): """ Extracts data from the sensor and returns it in a JSON document as a Python dict. Available for poll mode only. Args: handle: handle returned by the plugin initialisation call Returns: returns a sens...
1b3afbef00324e0958f703462297d21695aad28a
61,031
def get_L(NO3): """ Fundamentally this gives the nutrient concentration that is part of the phytoplankton growth rate, but it involves the Michaelis-Menten functions for nutrient limitation. For zero nutrients L = 0. As the nutrients become large compared to their half-saturations L goes to 1....
586faba87d0a5e3b3e4bf57cac59da5b608ad259
61,032
def homepage(env, start): """WSGI app to show the home page""" global _cached start('200 OK' , _head('text/html')) if not _cached: _cached = open('blockbox.html').read() return _cached
106b9654200da642f12c98639489275a71f6cbdf
61,033
def cli_bindings(cli): """ Custom key bindings for cli. """ kb = KeyBindings() @kb.add('f2') def _(event): """ Enable/Disable SmartCompletion Mode. """ _logger.debug('Detected F2 key.') cli.completer.start_completion = not cli.completer.start_completion ...
044dbf0c2cf46d921ffcca36f263877ed6ff15ca
61,034
def build_sequence_mask(sequence_length, num_heads=None, maximum_length=None, dtype=tf.float32): """Builds the dot product mask. Args: sequence_length: The sequence length. num_heads: The number of heads. maximum_length: ...
d1d69f41c0443242514af95c52239025ab0fdd86
61,035
import sys def main(): """ Main function. """ opt = Options() opt.parse(sys.argv[1:]) test = CrcTests() if not test.run(opt): return 1 print('Test OK') return 0
7390e5b0ec4b4eea8058f4d0a94bcd01714cf6b2
61,036
def circle_locs(im, locs, inner_radius=3, outer_radius=4, fill_mode="nan"): """ Returns a copy of im with circles placed around the locs. Arguments im: The background image locs: Nx2 matrix of peak locations circle_radius: Radius of circle to draw fill_mode: "nan...
4b72dad7394cad8cc8d85b1038285a1098ed8bec
61,037
def run_program(intcodes): """run intcodes, which are stored as a dict of step: intcode pairs intcodes encode the operation as well as the parameter mode. The two least significant digits are the operation. The most significant digit(s) are the parameter mode, one digit per parameter, read right-to-lef...
8714ea4988b52db9cab332c74b601c198b7fb511
61,038
def verify_token(token: str) -> str: """ Mock google and fb auth. :param token: email :return: email """ return token.strip()
806a6e5cb65bf6919afda7cc13bc5fa8e521a750
61,039
def stacked_rnn(): """Stacked RNN model.""" inputs = keras.Input((None, 3)) layer = keras.layers.RNN([keras.layers.LSTMCell(2) for _ in range(3)]) x = layer(inputs) outputs = keras.layers.Dense(2)(x) model = keras.Model(inputs, outputs) return ModelFn(model, (None, 4, 3), (None, 2))
b3bacb649df5b96a95bfbcdb0c694ee15fd6d6d8
61,040
def dup_jacobi(n, a, b, K): """Low-level implementation of Jacobi polynomials.""" seq = [[K.one], [(a + b + K(2))/K(2), (a - b)/K(2)]] for i in range(2, n + 1): den = K(i)*(a + b + i)*(a + b + K(2)*i - K(2)) f0 = (a + b + K(2)*i - K.one) * (a*a - b*b) / (K(2)*den) f1 = (a + b + K(2)...
c3f30a412e796376545b202c550a3fb5a6734e00
61,041
def data_topology_get(): # noqa: E501 """data_topology_get returns topology.Topology # noqa: E501 :rtype: TopologyTopology """ return 'do some magic!'
3fecb83fcea17cc8c963d3c47dd69416a0455838
61,042
def state_resolver(state: str) -> str: """Given a state name, returns it's dcid.""" state_alpha_code = USSTATE_MAP_SPACE[state] geo_dcid = USSTATE_MAP[state_alpha_code] return geo_dcid
734a3c8d14ed8352c73bf4df7dfec59d98f0bad3
61,043
import func_search import os def func_check(token_struct, func, generics, config_options): """ FUNCTION: struct_comp_check(a(), b str) a: token's tupple b: string name of the design function c: dictionary containing design's generic parameters d: d...
f5f3683c6f1032cebe7fa7abf93e5d2087120c73
61,044
import argparse def parse_args(): """Training Options for Segmentation Experiments""" parser = argparse.ArgumentParser(description='MXNet Gluon \ Segmentation') # model and dataset parser.add_argument('--model', type=str, default='fcn', help...
43656dafe5547f38c50063cf32c78c40c08c164b
61,045
import time import os def get_new_database_name(): """ Get a timestamped name for the new database. """ timestamp = int(time.time()) db_name = f"inputs.{timestamp}.db" return os.path.join(constants.DATA_PATH, db_name)
88a00794b2ee4a9778f1e2d7a3e616bf3ed79f1f
61,046
def hash_to_action(a_hash): """Deciphering the hash to a game action.""" if a_hash == -1: raise ValueError('Invalid action hash') if a_hash < NUM_CARDS: return {'action_type': 'DISCARD', 'card_index': a_hash} if a_hash < NUM_CARDS + NUM_CARDS: return {'action_type': 'PLAY', 'card_index': a_hash - NU...
9a815ba452f2ef9953d89b6ea2053de0155d728b
61,047
import os import logging import shutil import pathlib def _copy_new_wheels(new_wheels, new_wheels_dir, app_dir, app_json, pip_dependencies_key): """ Copies new wheels to the wheels/ directory of the app dir. """ new_wheel_paths = [] def copy_wheel(wheel_name, dst_path): src_fp = os.path.j...
8ff8058b869b27f3bb4c459d8b302f7e64851ce8
61,048
import pdb def UL(tran): """Compute UL (Utility Loss) for record and middle. """ ul = 0 supp_sum = len(ATT_TREES[-1]['*']) for t in mid[-1]: try: supp = len(ATT_TREES[-1][t]) except: pdb.set_trace() ul += (2 ** supp) ul = ul / (2 ** supp_sum) * 1...
0645b8feea4dfb930e55774ee4d73f097cad6765
61,049
def decimal_day_to_unix_time(year: int, month: int, day: float): """A function to convert decimal day time formats to UNIX time. Parameters ---------- year : int The year of the time stamp to be converted. month : int The month of the time stamp to be converted. day : float ...
8a8e6e386a16eb186255c37f0c21e4bae0af2f02
61,050
def NewDockerClientNoCheck(**kwargs): """Factory method for building a docker.Client from environment variables. Args: **kwargs: Any kwargs will be passed to the docker.Client constructor and override any determined from the environment. Returns: A docker.Client instance. Raises: DockerDaem...
f9e532399c2f2fc8604307e7291a16d05daf931d
61,051
def list_ports(zone, permanent=True): """ List all ports in a zone. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewalld.list_ports """ cmd = "--zone={0} --list-ports".format(zone) if permanent: cmd += " --permanent" return __firewall_...
eb99f515809de167ffeefca0bf9c63aef2208ad9
61,052
def log_db(app): """Return mongo client mock for the log db""" return api.config.log_db
7ee7eb7012bfc808fa490bd85c06a7b1a8bb8ae2
61,053
def printif(string: str, pre_sep: str = " ", post_sep: str = " ") -> str: """Print `string` if `string` is not null.""" if string not in [None, ""]: return f"{pre_sep}{string}{post_sep}" return ""
cfd7272ae106fda7c0f4e6705875a3656d90d52c
61,054
from typing import List def get_immunity_strat( compartments: List[str], immunity_params: ImmunityStratification, ) -> Stratification: """ This stratification is intended to capture all the immunity consideration. This relates both to "cross" immunity between the strains being simulated (b...
b81a3b3704d9caed2fb15d48ef6ffabe60ef660e
61,055
def _irfft_grad_helper(rank, rfft_fn): """Returns a gradient function for an IRFFT of the provided rank.""" # Can't happen because we don't register a gradient for IRFFT3D. assert rank in (1, 2), "Gradient for IRFFT3D is not implemented." def _grad(op, grad): """A gradient function for IRFFT with the provi...
2284f9f3e06bd5bad196efb3e3f5d225f5b0922c
61,056
import os def get_valid_filename(s): """ like the regular get_valid_filename, but also slugifies away umlauts and stuff. """ if not s: return '' s = get_valid_filename_django(s) filename, ext = os.path.splitext(s) filename = slugify(filename) ext = slugify(ext) if ext: ...
e0a317507a02ac8d50710c30e6a0ca9fa44cd65e
61,057
import argparse def sliding_tokenize(article: str, tokenizer, args: argparse.Namespace, task=None) -> tuple: """Tokenization function for sliding window approach.""" sentences = tokenizer(article, max_length=args.max_seq_length, truncation=True, ...
425947c0a44f64c3bde0d3c725b015d636354df6
61,058
def api_enable_fusion(val: bool = True) -> None: """Whether or not allow fusion the operators Args: val (bool, optional): True or False. Defaults to True. """ return enable_if.unique([enable_fusion, do_nothing])(val=val)
40d4fdbee933487f9d02ff2df5023032c3c59e9f
61,059
def random_apply(transform_fn, image, p): """Randomly apply with probability p a transformation to an image""" if tf.random.uniform([]) < p: return transform_fn(image) else: return image
12d2ab0eae20333b6881d838bfbca8ab020eb0be
61,060
def get_incident_ids() -> list: """ Gets all the campaign incident ids. Returns: List of all the ids. """ incidents = demisto.get(demisto.context(), "EmailCampaign.incidents") return [incident["id"] for incident in incidents]
b4f8c089c93520da546bf7b00e0f8d1eed51b4c0
61,061
def normalize_genotypes(genotypes): """Normalize the genotypes. Args: genotypes (Genotypes): The genotypes to normalize. Returns: numpy.array: The normalized genotypes. """ genotypes = genotypes.genotypes return (genotypes - np.nanmean(genotypes)) / np.nanstd(genotypes)
367c6293f0a03c70d05f45916b7a191ba99fbb18
61,062
from io import StringIO def GetLines(data, strip=False): """Returns a list of all lines in data. Args: strip: If True, each line is stripped. """ ret = StringIO(data).readlines() if strip: ret = [x.strip() for x in ret] return ret
8ce3a3e829eed590ba0978a659ff1d3b063dc50d
61,063
def mannwhitneyu(a, b, sigLevel=.05): """ Determine if sample a and b are the same at given significance level. """ if len(a) <= 20 and len(b) <= 20: return mannwhitneyu_small(a, b, sigLevel) else: try: # MWU in SciPy is one-sided, multiply by 2 to get two-sided. ...
08ca7dcae3a5771047fa9700d545681977f0ae65
61,064
def _get_hyperparameters() -> kt.HyperParameters: """Returns hyperparameters for building a TFDF model.""" hp = kt.HyperParameters() # Defines search space. # For a complete list of configuration parameters of learners, please refer to # https://github.com/google/yggdrasil-decision-forests/blob/main/documenta...
1e9da47d8cbdc9e72f6fc44bf1791c26428c8a08
61,065
def _netmiko_connect(connection_dict): """ to handel netmiko connection :param connection_dict: netmiko connection dict :return: netmiko connection object """ try: connection = ConnectHandler(**connection_dict) except (NetMikoTimeoutException, NetmikoTimeoutError) as e: prin...
07fc7c6f97eb0bcde9690678ae2762c016286b7f
61,066
def polyphase_forward(x, hk, rearrange_filter=True): """ Polyphase implementation of the analysis process (fast) Parameters ---------- x: torch.Tensor signal to analyse ( B x 1 x T ) hk: torch.Tensor filter bank ( M x T ) """ x = rearrange(x, "b c (t m) -> b (c m) t"...
1df0cd727a83be86e5a355e196751c57952cea3c
61,067
from matplotlib import pyplot as plt def plot_cumulative_transactions(model, transactions, datetime_col, customer_id_col, t, t_cal, datetime_format=None, freq='D', set_index_date=False, title='Tracking Cumulative Transactions', ...
d9dd40afbcc320a2371279ea9826e7e24eb64f4d
61,068
def merge_config(user, default): """Merges a user configuration with the default one.""" if isinstance(user, dict) and isinstance(default, dict): for kk, vv in default.items(): if kk not in user: user[kk] = vv else: user[kk] = merge_config(user[kk...
7b4463f3e9c213782b6da5f25bcf64daa2c69d91
61,069
def _json_add_readers(json, filenames): """ Add merge Filter element and readers to a Writer element and return Filter element """ for f in filenames: _json_add_reader(json, f) if len(filenames) > 1: json['pipeline'].insert(0, { 'type': 'filters.merge' }) re...
9d35f44050464292c944176c98fa1ee62d026315
61,070
import math def bic(observations,variables,pred_vector,true_vector): """ Function that calculates the BIC value for a dataframe Args: observations variables pred_vector true_vector Returns: bic """ return math.log(sum((pred_vector-true_vector)**2)/observ...
b7747991b929d5151aba27e48018654277e61c52
61,071
def list_name(pat_id): """ Returns all of the Names for a patient """ app.logger.info("Request for Patient's Names...") pat = Pprofile.find_or_404(pat_id) results = [name_item.serialize() for name_item in pat.name] return make_response(jsonify(results), status.HTTP_200_OK)
92c70614f1f513358b7bf40010b1772dfdd48e14
61,072
def get_bilateral_specificity(C,lrd,left): """ Returns the bilateral (contralateral) specificity probabilities Parameters: ----------- C : Connecomte object lrd : dict Left/right dictionary left : list List of the left nodes Returns: spec : dict Keys are cell na...
d72ebaea472e753cd93b7bb7ab4c536d1a717b92
61,073
def reduce_nodelist(nodelist: template.NodeList) -> template.NodeList: """ A function which trims whitespaces and comment nodes from a nodelist. Notice that this function might remove a relevant regular html space ' ', so use with care. """ new_nodelist = template.NodeList() for node in ...
a2578f67636f7abc1090794d2425da219425089b
61,074
def GetNodeInfo(storage_units, hv_specs): """Gives back a hash with different information about the node. @type storage_units: list of tuples (string, string, list) @param storage_units: List of tuples (storage unit, identifier, parameters) to ask for disk space information. In case of lvm-vg, the identifier...
886065df101557ca49e879dc8f187028455142b2
61,075
from typing import Union from typing import TextIO from typing import Sequence from pathlib import Path import pandas import io def get_locations(files: Union[TextIO, Sequence[Path]]) -> pandas.DataFrame: """ retrieve locations of GNSS receivers Requires pymap3d.ecef2geodetic """ if isinstance(fi...
d9ab00c22f95945b54584a8c4d99a259cf667dd3
61,076
import numpy def createslicemeshes(grid, x=None, y=None, z=None, step=None, offset=None): """ Creates meshes for slices through the given data, using the current GR colormap. Use the parameters x, y or z to specify what slices should be drawn and at which positions they should go through the data. If ...
387a2b93c06a2f5bfba9b95c5ccf5b4604dd3e26
61,077
def create_transaction(): """ Input Payload: { "sender": "address_1" "recipient": "address_2", "amount": 3 } """ transaction_data = request.get_json() index = blockchain.create_new_transaction(**transaction_data) response = { 'message': 'Transaction has ...
be2876bf0c901d7176d521207522effff29a131c
61,078
def build_config(config): """ Determines the configuration of the metadata service. :type config: akanda.router.models.Configuration :param config: :rtype: akanda.router.models.Configuration """ config_data = {} for net in config.networks: if not net.is_tenant_network: ...
5ba48ee05e30b87ff331881d5ea511de79dee105
61,079
def has_an_update(page_data: dict, tracker_data: dict) -> bool: """Checks if there was an update comparing two story mappings of the same story. Arguments: page_data {dict} -- Requested story mapping, from `get_story_data`. tracker_data {dict} -- Story mapping from the tracked list. Re...
a7374a167c368f85bdab6ec68dbea044c801ef90
61,080
def meaning(of=None): """The meaning of life?""" if of == "life": return 42 return None
ee85e2cd0caa1c0780e11eb3759b8e0d74031209
61,081
def merge_explicit(matmul): """ Merge explicit MatrixBase arguments >>> from sympy import MatrixSymbol, Matrix, MatMul, pprint >>> from sympy.matrices.expressions.matmul import merge_explicit >>> A = MatrixSymbol('A', 2, 2) >>> B = Matrix([[1, 1], [1, 1]]) >>> C = Matrix([[1, 2], [3, 4]]) >...
536209c6c6f4ed121b496b06610234b6321ee351
61,082
import codecs import json from typing import OrderedDict def _load_json_result(result_file): """ Load the result file as utf-8 JSON and strip test_dir prefix from locations. Sort the results by location. """ with codecs.open(result_file, encoding='utf-8') as res: scan_result = json.loa...
c313a2bbf000cb3e3b48ea9314f48188243ecf9b
61,083
from typing import Optional import requests def _requestData(tag: str, station: Optional[str] = 'KPDX') -> str: """ Handles the retrieval of the data from NWS ADDS service, and gets the first entry in the list of responses (which always seems to be the most recent) """ global ...
5debee31d15809ed4bf2fdf66807a9a6126812a6
61,084
def get_total_contacts(res_pair_file, with_nnc=False): """ Take res pair file and extract the amount of native contacts for the dataset. Also option to use 'with nnc=True' which allows extraction of total nc and nnc values. Returns int: amount of nc, optionally: amount of nnc """ total_contacts ...
e1d061c5d4c76647f0c825165fd305e76f00c5f8
61,085
def bg_subtract(im, radius): """ Subtracts a gaussian blurred image from itself smoothing uneven illumination. Parameters ---------- im : 2d-array Image to be subtracted radius : int or float Radius of gaussian blur Returns ------- im_sub : 2d-array, float ...
bcaedb54a252adf88283a37e65c700f140590384
61,086
def named_param(argnames, argvalues): """ Improve pytest's native labeling of test case parameterization. This function thinly wraps the 'parametrize' mark from pytest, adding clearer labeling of each individual parameterized test case, overriding the index-based labeling that pytest uses by defaul...
a9055016bdd600eec5695f2a2a6e44460e2af12f
61,087
def apply(sliced, input_image, has_affine_term=True, name=None): """Applies a sliced affined model to the input image. Args: sliced: (Tensor) [batch_size, h, w, n_output, n_input+1] affine coefficients input_image: (Tensor) [batch_size, h, w, n_input] input data onto which to apply the affi...
8b68f0f02c7f6a52018c994f8c99b0ea76f8811b
61,088
import torch def propagate(T0, Sigma, Upsilon, Q, method, dt, g, cholQ=0): """ Propagate an extended pose and its uncertainty """ Gamma = f_Gamma(g, dt) Phi = f_flux(T0, dt) # compound the mean T = Gamma.mm(Phi).mm(Upsilon) # Jacobian for propagating prior along time F = torch.eye...
dd6acdad16d0d5287eba0d8b46e7261fbcbc1427
61,089
def shared_hive_instance(): """ This method will initialize ``SharedInstance.instance`` and return it. The purpose of this method is to have offer single default steem instance that can be reused by multiple classes. .. code-block:: python from beem.account import Account ...
f7e9a3ee09731370dab09649a417145772f53cf3
61,090
def aperture_fields(guide_width, horn_effective_length, frequency, x, y): """ Calculate the electric and magnetic fields at the aperture of the horn. Assuming that the fields of the feeding waveguide are those of the dominant TE10 mode. And that the horn length is large compared to the dimensions of the...
bf69e31adfd7e7b91b5b09103e57b0086c81a0d6
61,091
def get_greeting_2(): """Greets and optionally compliments(3 random compliments) a user""" username = request.args["username"] wants = request.args.get("wants_compliments") nice_things = sample(COMPLIMENTS, 3) return render_template("greet_2.html", username=username, wants_compliments=wants, complim...
bd1c248adb072f07cdd7a0552f9771a5e8873588
61,092
import requests def proxy(path): """ HTTP Proxy """ query = '' if request.query_string is not None: query = '?' + request.query_string.decode("utf-8") bokeh_url = BOKEH_URL.replace('$PORT', get_bokeh_port()) request_url = f"{bokeh_url}/{path}{query}" resp = requests.get(request_url) ...
16ad1b0c037238e4a55ac153d731c4dff4e9ac0a
61,093
def requires_auth(f): """Minimal implementation of authentication. Will be refactored.""" @wraps(f) def decorated_function(*args, **kws): if session.get('user', None) is None: return redirect(url_for('login')) else: return f(*args, **kws) return decorated_function
3d09db7ae3452101ad454073923f3dac279ff07f
61,094
import requests def dwCover(SONG_INFO, index): """Download the song cover img from itunes.""" # Try to download the cover art as cover.jpg in temp try: imgURL = SONG_INFO[index].artwork_url_100 try: # Try to get 512 cover art imgURL = imgURL.replace('100x100', '2048...
d76bdd3513b6b6f0d6256341e8e75ce4635106f8
61,095
def asMFnSkinCluster(obj): """ OpenMaya.MObject -> OpenMaya.MFnSkinCluster :param OpenMaya.MObject obj: :rtype: OpenMaya.MFnSkinCluster """ iter = OpenMaya.MItDependencyGraph( obj, OpenMaya.MFn.kSkinClusterFilter, OpenMaya.MItDependencyGraph.kUpstream ) wh...
efba63d2548ab7d6a00f460363577261a102ba0c
61,096
def before_lock(aqi_array: np.ndarray, datetime_index: np.ndarray, after_lock: np.ndarray, before_lock_date: str) -> np.ndarray: """Grab period before lock down.""" return aqi_array[np.where(datetime_index <= np.datetime64(before_lock_date))][-(after_lock.shape[0]...
764b70ce70ac53ff48867c5a53bf319cd524770d
61,097
def rdkitSubstrMatch(targetRdkitMol, refRdkitMol, *args, **kwargs): """ Matches two rdkit mol object graphs with each other. Outputs a single tuple of corresponding atoms indices. Arguments: ---------- targetRdkitMol : object target rdkit molecule object refRdkitMol : object ...
9978dce4381f2e49c6f2926594a0a5f58dd33368
61,098
import numpy as np def from_a_to_b(source="Munich, Germany", destination="Augsburg, Germany", resolution=50): """ Try to print the way from source to destination :param source: The starting place :param destination: The destination place :param resolution: (minimum) resolution of height results in...
94a6d309fe272432fe32778fe7503856f31758d0
61,099