content
stringlengths
22
815k
id
int64
0
4.91M
def yet_another_hash_table(): """Make a hash table with multiple values and keys.""" h = HashTable() h.set('koala', 'kool') h.set('dog', 'chihuahua') h.set('cat', 'fat') h.set('moose', 'bullwinkle') return h
78,400
def register_checkers(linter): """ Register checkers. """ linter.register_checker(FeatureToggleChecker(linter)) linter.register_checker(CodeAnnotationChecker(linter)) linter.register_checker(FeatureToggleAnnotationChecker(linter)) linter.register_checker(SettingAnnotationChecker(linter))
78,401
def test_ignores_arbitrary_annotations(annotation): """#SPC-notify.tst-arb_ann""" class DummyClass: var: f"{annotation}" extracted = detect_classvars(DummyClass) assert len(extracted) == 0
78,402
def matplotgraph_predictions(user: discord.Member, predictions: List[Pattern], min_max_pattern: Pattern, average_prices: List[float], testing=False) -> BytesIO: """Graph the predictions""" x_axis = day_segment_names[2:] abs_min_points = [price.min for price in min_max_pattern.prices][2:] abs_max_points...
78,403
def open_corpus_volatile(treebank_id, tigerxml_corpus_path, veeroot=True): """Indexes a TIGER-XML corpus using a volatile in-memory index.""" db = sqlite3.connect(":memory:") _index_treebank(tigerxml_corpus_path, db, veeroot) return Corpus(treebank_id, db, EmptyDbProvider())
78,404
def char_to_bool(letter): """Transform character (J/N) to Bool.""" if letter.upper() == 'J': return True elif letter.upper() == 'N': return False else: raise ValueError('Ongeldige letter, alleen J of N toegestaan.')
78,405
def parse_exception(definition, name, message): """Parse an exception. :param definition: Definition. :param name: Name. :param message: Message. :returns: the parsed exception or :class:`UnknownException` if the exception is not known. """ if definition == 'entangle': ...
78,406
def write(configsetname, node, cnfxml): """ Write configuration file with content supplied as an XML string. Return None for success, or a string containing error information. """ config = configPath(configsetname, node) if config and os.path.exists(config): return "Output file already e...
78,407
def _prf_divide(numerator, denominator): """Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements to zero. """ result = numerator / denominator mask = denominator == 0.0 return ma.array(result, mask=mask)
78,408
def authenticate_user(username: str, password: str) -> Optional[Admin]: """Authentucate user process. Check if the username is in the admin database and the password is correct. If both conditions are correct, it returns an Admin instance; otherwise it returns None""" user = get_user(username) if n...
78,409
def mock_clipboard(monkeypatch, request): """Fixture mocking clipboard IO. This mocks pandas.io.clipboard.clipboard_get and pandas.io.clipboard.clipboard_set. This uses a local dict for storing data. The dictionary key used is the test ID, available with ``request.node.name``. This returns th...
78,410
def get_xml_tree(xml_path): """Parses xml file and returns am xml tree. Args: xml_path (str): full path to xml file to parse Returns: ElementTree.Tree: ElementTree representing xml file """ if not os.path.exists(xml_path): raise XMLHelperError("Could not find xml file: %s" ...
78,411
def fileNumber(filePath): """ Get the number of the file. foo.0080 would return 0080 """ num = filePath.split('.')[-1] return int(num)
78,412
def dice(x, y): """Implementation of dice scores ofr 0/1 numy array""" return 2 * np.sum(x * y) / (np.sum(x) + np.sum(y))
78,413
def create_scale(image, path, i): """ Saves the image with a scale. """ f = plt.figure() plt.axis('off') plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB).astype(np.uint8)) plt.subplots_adjust(wspace=0, hspace=0, top=1, bottom=0, left=0, right=1) line = Line2D([100, 850], [100, 100]...
78,414
def build_namespace_dataset_details( formatter: NamespaceFormatter) -> Iterator[Tuple[str, str]]: """Generates all the detail pages for all namespaces and datasets.""" for section in formatter.sections(): yield section.name, section.to_details_markdown()
78,415
def getAddressNode(network, address): """ Get the Layer3Address node of a host that has the igven address. :param network: Hostnames the host could have -> Nmap scan :type network: Layer3Network :param address: Address to find :type address: str :returns: Layer3Address node or None ...
78,416
def get_top_adj(full_results, num): """ Takes dictionary of results from run_adj_analysis and number of top results to return. Returns the top num adjectives associated with male pronouns and female pronouns. :param full_results: dictionary from result of run_adj_analysis :param num: number of ...
78,417
def create(): """ Create a new RSS feed over XHR :return: Feed creation status response :rtype: Response """ status = api.STATUS_FAIL feed = "rss_{0}".format(re.sub('[^0-9a-zA-Z]+', '_', request.values['feed'].lower())) if config.has_section(feed): msg = "Duplicate feed name" e...
78,418
def get_host_token(profile=None): """ Get the host and token for a profile from ~/.databrickscfg. """ cfg = provider.get_config() if profile is None else provider.get_config_for_profile(profile) return (cfg.host,cfg.token)
78,419
def dump_stack(skip=0, limit=None): """Dumps current stack trace.""" skip += 2 # To skip dump_stack and traceback.extract_stack if limit is None: limit = options.STACK_DUMP_LIMIT print("--- Stack trace: -----------------------------------------------------") try: stack = traceback.e...
78,420
def loadAll(param=basic_param): """ Charge toutes les colonnes selon les paramètres Paramètres ---------- param : set dictionnaire des paramètres Retours ---------- df_global : pandas.dataframe si Return == True renvoie le dataframe complet """ t1 = time() df_g...
78,421
def rfc_save_test(request, rfc_id, *args, **kwargs): """ """ # Check user permissions # Get the form data form = RfcModuleForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(form.errors) # Get the rfc in question update_rfc = request_for_change.objects.get(r...
78,422
def testPair(pair,coglist): """Determine the next cognate set to choose for a pair""" curcog = cognateSet() for cog in coglist: curcog += cog mycogs = [cognateSet()] mycogs[0].noncognates += max((len(pair[0]),len(pair[1])))*2 newcogs = getListOfCognates(pair[0],pair[1],cognateSet()) ...
78,423
def _search_phrase_op(il, target_op): """ Helper for finding parts of a phrase[+displacement] il """ op = il.operation # Handle starting points if op == LowLevelILOperation.LLIL_SET_REG: return _search_phrase_op(il.src, target_op) if op == LowLevelILOperation.LLIL_STORE: return _search_phrase_op(il....
78,424
def cube(path='./', pattern='', verbose=True): """ Convenience wrapper around find.files to get *.cube files """ return files('cube', path=path, pattern=pattern, verbose=verbose)
78,425
def is_schema_compatible_in_topic(target_schema, topic): """Check whether given schema is a valid Avro schema and compatible with existing schemas in the specified topic. Note that target_schema is the avro json object. """ enabled_schemas = get_schemas_by_topic_name(topic.name) for enabled_sche...
78,426
def JobStatus(jobid): """return status(es) of job Parameter --------- jobid id of job Returns ------- list state of each job in array """ status = [] for line in JobInfo(jobid, ['jobid', 'state'], noheader = True).split('\n'): if (line.split() and '+' ...
78,427
async def test_set_reschedule_deadline_end_invalid_date(): """Sets a reschedule deadline end but date is invalid.""" cog, mock_bot, _ = init_mocks() with pytest.raises(discord.ext.commands.UserInputError): await cog.set_reschedule_deadline_end(cog, tosurnament_mock.CtxMock(mock_bot), date="some date...
78,428
def make_msg(comment, request): """ Return a message from a comment & request. """ return build_msg('', user_name = comment.user_name, user_email = comment.user_email, user_url = comment.user_email, comment = comment.comment, user_ip = request.META.get...
78,429
def DataFrameTableColumnComponent( widget, is_interactive, column, SpanOnBeginChange, SpanOnEndChange, TokenSpanOnBeginChange, TokenSpanOnEndChange, ): """Constructs the widget component representing a single column of data within the table.""" column_items = [] # Begin with th...
78,430
def get_user(data_encoded): """ Endpoint returning logged-in user Args: data_encoded: BASE64 encoded JSON Returns: Flask response, consisting of serialized user, response code, response message, affected class, and http code """ user = http_auth.current_user data_string = b...
78,431
def monkeypatch_behave(): """ Apply patches to "behave" to make documenation runs work. """ from behave_ext.terminal.ansiterm import AnsiStyle from behave_ext.terminal import ansi_escapes as ansi_escapes2 from behave.formatter import ansi_escapes ansi_escapes.colors["grey"] = ansi_escapes.co...
78,432
def arg_wrap(fft_func, **extra_args): """Decorator to add kwargs based on fft suite. Args: fft_func: the fft function to arg wrap extra_args: extra args to add to the PyFFTW call Returns: the wrapped function """ using_fftw = FFTMODULE.__name__.split('.')[0] == 'pyfftw' def ...
78,433
def Init(parent): """ configuration of all the buttons, some buttons just need to be toggled meaning that they need just to be clicked and the function associated to the button is called and executed. Other buttons are checkable meaning that until the user has not finished to use the function...
78,434
def get_healpix_dec_mask(dec_lim, nside): """ Compute a Healpix binnary mask given a limit declinaison Parameters ---------- - dec_lim (deg): the limit declinaison for the mask - nside : Healpix Nside argument Outputs -------- - mask (int array): the binnary mask cut at dec_lim ...
78,435
def singleton(fn): """ Lazily instantiate a function """ _instance = None def wrapped(): nonlocal _instance if _instance is None: _instance = fn() return _instance return wrapped
78,436
def manhattan_distance(x, y): """ Returns the Manhattan (City Block) distance between two lists """ return sum(abs(a - b) for a, b in zip(x, y))
78,437
def score_from_local(directory): """Calculate score from a local results directory""" results = gym.monitoring.monitor.load_results(directory) # No scores yet saved if results is None: return None episode_lengths = results['episode_lengths'] episode_rewards = results['episode_rewards'] ...
78,438
def Write_Vasp_POSCAR(cal_loc, structure_filename, structure_file_folder, workflow): """ Write POSCAR in folder cal_loc as follows: If no POSCAR in cal_loc, write POSCAR: If tag sort_structure is on, struture_filename under structure_file_folder is assumed in the form of POSCAR. ...
78,439
def CheckSetupSection(config, State, Model, Dimension, InFileName): """Check that valid inputs are provided in SETUP section.""" import nanpack.backend.fetchoptions as fo fetch = fo._FetchOptions() state_options = fetch.StateOptions() model_options = fetch.ModelOptions() dim_options = fe...
78,440
def sacct(connection: Connection): """Retrieve information for all jobs.""" click.echo(yaml.dump(connection.client.poll(connection.info["machine"])))
78,441
def aws_credentials(): """Mocked AWS Credentials for moto.""" os.environ["AWS_ACCESS_KEY_ID"] = "testing" os.environ["AWS_SECRET_ACCESS_KEY"] = "testing" os.environ["AWS_SECURITY_TOKEN"] = "testing" os.environ["AWS_SESSION_TOKEN"] = "testing" os.environ["AWS_DEFAULT_REGION"] = "eu-west-1"
78,442
def test_empty_text(): """Thanks for nothing!""" assert upsidown("") == "" assert upsidown(None) == "" assert upsidown([]) == ""
78,443
def test_set_default_rated_temperature(subcategory_id): """should return the default capacitance for the selected subcategory ID.""" _temp_rated = capacitor._set_default_rated_temperature(subcategory_id, 2) assert ( _temp_rated == { 1: 85.0, 2: 125.0, 3: ...
78,444
def notify(webhook_url, update, attachments=None): """ Args: (ch: 投稿するchannel, update: 投稿内容, attachments: slackのoption) Return: None """ message = f'{update.title}\n{update.link}' main_content = { "username": "kkwiki", "avatar_url": "http://www2.teu.ac.jp/kiku/wiki/?plugin=ref&p...
78,445
def ecm(n, B1=10, B2=20): """ TODO: Determine the best defaults for B1 and B2 and the best way to increment them and iters "Modern" ECM using Montgomery curves and an algorithm analogous to the two-phase variant of Pollard's p-1 method TODO: We currently compute the prime lists from the ...
78,446
def generate_dispatcher(method_handler, parent_class=None): """ Create a dispatcher class and return an instance of it from a dispatcher definition. The definition is a class with the following attributes: _ EXPORTED_METHOD: dictionary where keys are method names and values class attribute nam...
78,447
def show_slave_hosts(server): """Function: show_slave_hosts Description: Return the output of the 'show slave hosts' command. Arguments: (input) server -> Server instance. (output) Results of command in dictionary format. """ return server.col_sql("show slave hosts")
78,448
def get_used_materials(materials_map: Dict[int, str], path_info: pd.DataFrame) -> str: """Collect text of used materials specifications. Args: materials_map: map material number -> spec. path_info: dataframe containing column with used material numbers. Returns: All the used materi...
78,449
def test_player_view_get_proper_behavior_in_round_4_when_user_has_made_trade_in_this_but_NOT_in_last_round(client, db): """ User is in round 4. He traded in round 2, but not in round 3, and not yet in round 4. """ # some market is in round 4 market = MarketFactory(round=4) # a user has joined ...
78,450
def starting_coordinates(): """ Starting coordinates on a pixel matrix. """ return (10, 10)
78,451
def get_args(): """Eat command line arguments, return argparse namespace for settings""" parser = ArgumentParser() parser.add_argument("filename", nargs="?", help="trace file dump, stdin if not given") parser.add_argument("-s", "--start", type=float, default=0, help="start timest...
78,452
def delete_machine(index): """Add a new machine""" Machine.delete(index) return '', 200
78,453
def strip_html_tags(i_string): """ Quick solution to remove html tags being returned in episode description. Will probably replace eventually. """ strippable = ('<p>', '</p>') spaces = ('&nbsp;',) breaks = ('<br>',) for s in strippable: i_string = i_string.replace(s, '') for...
78,454
def dos_element_spd_spin_polarized( folder, element_spd_dict, output='dos_element_spd_sp.png', fill=True, alpha=0.3, linewidth=1.5, sigma=0.05, energyaxis='x', soc_axis='z', color_list=None, legend=True, total=True, figsize=(4, 3), erange=[-6, 6], fontsize=12,...
78,455
def solve_weighted_kernel_ridge_gradient_descent( Ks, Y, deltas, alpha=1., fit_intercept=False, step_sizes=None, lipschitz_Ks=None, initial_dual_weights=None, max_iter=100, tol=1e-3, double_K=False, random_state=None, debug=False): """Solve weighted kernel ridge regression using gradient des...
78,456
def generate_index(csv_filepath): """ Generate an index 0...k for the k labels. Parameters ---------- csv_filepath : str Path to 'test.csv' or 'train.csv' Returns ------- tuple of dict and a list dict : Maps a symbol_id as in test.csv and train.csv to an integer in ...
78,457
def getPlayer(playerId,fullname): """ Retrieves player stats for the last game. Career results can be added in the future """ url = "http://data.nba.net/prod/v1/2018/players/{}_gamelog.json".format(playerId) with urllib.request.urlopen(url) as url2: data = json.loads(url2....
78,458
def remove(name=None): """ Removes a MySQL service :param name: Name of instance """ m = MySQL(name=name) m.remove()
78,459
def last_name_similarity_scorer(a: str, b: str): """Compares two first last strings, returns 1 if they match, 0 otherwise. Uses Jaro-Winkler Distance Algorithm (JWDA) (en.wikipedia.org/wiki/Jaro–Winkler_distance). JWDA "measurement scale is 0.0 to 1.0, where 0.0 is the least likely and 1.0 is a positiv...
78,460
def scoringInnings(team_1_array, team_2_array, innings, bat_bowl_choice, batting_score, innings_data, start_message, max_overs, max_wickets, is_test)...
78,461
def load_archive(filename, direction=0): """ stream in data batch by batch from given archive data """ with open(filename, 'r') as fi: reader = csv.DictReader(fi) batch = [] item = 0 for row in reader: # seq number retrieved within each 30-sec query ...
78,462
def get_tempfile(): """Return tempfile.""" dirname = get_tempdir() filename = uuid.uuid4().hex return os.path.join(dirname, filename)
78,463
def signed_container_file(): """A real container signed via the Demo MobileID service with a test account""" with open(Path(__file__).parent / "files" / "signed-test-mobileid-ee.asice", "rb") as f: yield f
78,464
def fib_iter(n: int): """迭代解法,自低向上""" dp = {} dp[1] = dp[2] = 1 i = 3 while i <= n: dp[i] = dp[i - 1] + dp[i - 2] i += 1 return dp[n], dp
78,465
def convert_dashboard_tile_to_presentation_tile(element: dict) -> LookerPresentationTile: """Take the API response and convert into a LookerPresentationTile object""" return LookerPresentationTile( title=element['title'], subtitle_text=element['subtitle_text'], body=element['slide_params...
78,466
def wrap_angle(array, wrap_count): """ Wraps angle vector Helper-function that wraps an angle vector containing angles in radian by the number of elements specified by wrap count. The last wrap_count elements in array are stacked to the beginning of the array and lowered by 2*pi and the first...
78,467
def three_points_bezier(x1, y1, x2, y2, x3, y3, canvas, color, stroke_width): """Draws a cubic bezier curve. Args: x1, y1, x3, y3: coords representing the two 2d points x2, y2: 2d points representing the anchor point canvas: Canvas object color: 3-int tuple representing rgb colo...
78,468
def get_db_data(relation_data, unprefixed): """Organize database requests into a collections.OrderedDict :param relation_data: shared-db relation data :type relation_data: dict :param unprefixed: Prefix to use for requests without a prefix. This should be unique for each side of ...
78,469
def send_email(): """ 发送邮件 """ content = get_weather_info() or ANGRY_MSG message = MIMEText(content, "plain", MAIL_ENCODING) message["From"] = Header("暖宝宝", MAIL_ENCODING) message["To"] = Header("A handsome soul") message["Subject"] = Header("😘 男朋友的日常问候", MAIL_ENCODING) try: ...
78,470
def KleinBottle(): """ A minimal triangulation of the Klein bottle, as presented for example in Davide Cervone's thesis [Cer1994]_. EXAMPLES:: sage: simplicial_complexes.KleinBottle() Minimal triangulation of the Klein bottle """ return UniqueSimplicialComplex([[2, 3, 7], [1, 2...
78,471
def speech_to_text(file_name, model_id): """Use Watson Speech to Text to convert audio file to text.""" # create Watson Speech to Text client stt = SpeechToTextV1(iam_apikey=keys.speech_to_text_key) # open the audio file with open(file_name, 'rb') as audio_file: # pass the file to Watson ...
78,472
def auth_connection(connection) -> openeo.Connection: """Connection fixture to a backend of given version with some image collections.""" connection.authenticate_basic(TEST_USER, TEST_PASSWORD) return connection
78,473
def convert(tree,fileName=None): """ Converts input files to be compatible with merge request #412, where we switch from custom XML pathing to standard XPATH nomenclature. @ In, tree, xml.etree.ElementTree.ElementTree object, the contents of a RAVEN input file @ In, fileName, the name for the raven in...
78,474
def merge_object_masks(list_masks, thr_overlap=0.7): """ merge several mask into one multi-class segmentation :param [ndarray] list_masks: :param float thr_overlap: :return ndarray: >>> m1 = np.zeros((5, 6), dtype=int) >>> m1[:4, :4] = 1 >>> m2 = np.zeros((5, 6), dtype=int) >>> m2[2:, ...
78,475
def s3_lazy_put(filename, assume_immutable=False): """Put file to s3 only if out of sync.""" key = BUCKET.get_key(filename) if key is None: key = BUCKET.new_key(filename) print 'uploading', filename key.set_contents_from_filename(filename) return key elif assume_immutable...
78,476
def moments(Xax, data, vheight=True, estimator=np.mean, negamp=None, veryverbose=False, nsigcut=None, noise_estimate=None, **kwargs): """ Returns the gaussian parameters of a 1D distribution by calculating its moments. Depending on the input parameters, will only output a subset of the abo...
78,477
def change_params(inst, extra_params): """ Function to update the value of some parameters in inst with values from *extra_params*. Parameters ---------- inst: dict parameters extra_params: dict parameters to be updated and their new values """ new_params = {k: v for k, ...
78,478
def preprocess_adj(adj): """Preprocessing of adjacency matrix for simple GCN model""" return normalize_adj(adj + sps.eye(adj.shape[0])).astype(np.float32)
78,479
def test_matrix_params_build(): """Sample from a program with matrix-valued params.""" program_code = """ data { int<lower=2> K; int<lower=1> D; } parameters { matrix[K,D] beta; } model { for (k in 1:K) for (d in 1:D) ...
78,480
def set_sftp_log_level(level): """Set the AsyncSSH SFTP/SCP log level This function sets the log level of the AsyncSSH SFTP/SCP logger. It defaults to `'NOTSET`', meaning that it will track the debug level set on the main AsyncSSH logger. For additional control over the level of debug ...
78,481
def get_handler_name( *, handler: _Handler, instance: Any) -> str: """ Get a handler name. Parameters ---------- handler : _Handler Target handler. instance : VariableNameInterface Instance to bind target handler. Returns ------- handler_name :...
78,482
def do_lookup(get_locations_func): """ Generic method which gets the locations in [(lat,lng),(lat,lng),...] format by calling get_locations_func and returns an answer ready to go to the client. :return: """ try: locations = get_locations_func() return {'results': [get_elevation(...
78,483
def get_parameter_for_dev_mode(dev_mode_setting): """Return parameter for whether the test should be running on dev_mode. Args: dev_mode_setting: bool. Whether the test is running on dev_mode. Returns: str. A string for the testing mode command line parameter. """ return '--params....
78,484
def load_MDU(mdu): """parse MDU and store parameter key/values in dictionary :function: TODO :returns: TODO """ params = {} key_value = re.compile("(.*)=(.*)#.*") with open(mdu, "r") as f: lines = f.readlines() for line in lines: match = key_value.match(line)...
78,485
def get_username(prompt: str) -> str: """Prompt the user for a username""" username = input(prompt) return username
78,486
def load_tracking_params(base, ext, names = None, init_fname = None): """Loads parameters from file If file doesn't exist, returns empty dictionary Parameters -------------- base : str relative path to file ext : str file extension, must be either ".npz" or ".dat" [defa...
78,487
def write_sip(in_wcs, outfile, overwrite=False): """ Write input WCS to a FITS file and include the SIP information in the header. This is not done by default and you need to set an obscure flag to make it happen. """ in_wcs.to_fits(relax=WCSHDO_SIP).writeto(outfile, overwrite=overwrite)
78,488
def preprocess(x, y, nb_classes=10, clip_values=None): """Scales `x` to [0, 1] and converts `y` to class categorical confidences. :param x: Data instances. :type x: `np.ndarray` :param y: Labels. :type y: `np.ndarray` :param nb_classes: Number of classes in dataset. :type nb_classes: `int` ...
78,489
def mkatas(u_t, v_t, wap, t_t, ttt, g_w, p_l, lat, nlat, ntp, nlev): """Compute the stat.-trans. eddy APE conversions from u, v, wap and t. Arguments: - u_t: a 3D zonal velocity field; - v_t: a 3D meridional velocity field; - wap: a 3D vertical velocity field; - t_t: a 3D temperature field; ...
78,490
def fourier_model(cn, Nfreqs): """ Calculate a 1D (complex) Fourier series model from a set of complex coefficients. Parameters ---------- coeffs : array_like Array of complex Fourier coefficients, ordered from (-n, n), where n is the highest harmonic mode in the model. Nfreqs ...
78,491
def remove_low_information_features(feature_matrix, features=None): """Select features that have at least 2 unique values and that are not all null Args: feature_matrix (:class:`pd.DataFrame`): DataFrame whose columns are feature names and rows are instances features (list[:class:`f...
78,492
def working_directory(path): """ Execute some code in a different working directory. """ prev_cwd = os.getcwd() os.chdir(path) try: yield finally: os.chdir(prev_cwd)
78,493
def latlt2cart(lat,lt,hemisphere): """ Latitude and local time to cartesian for a top-down dialplot """ r,theta = latlt2polar(lat,lt,hemisphere) return r*cos(theta),r*sin(theta)
78,494
def md5_password(password, salt): """获取原始密码+salt的md5值 """ trans_str = password + salt md = hashlib.md5() md.update(trans_str.encode('utf-8')) return md.hexdigest()
78,495
def build_belief(belief_type: Belief, num_agents=NUM_AGENTS, **kwargs): """Evenly distributes the agents beliefs into subgroups. """ if belief_type is Belief.MILD: middle = math.ceil(num_agents / 2) return [0.2 + 0.2 * i / middle if i < middle else 0.6 + 0.2 * (i - middle) / (num_agents...
78,496
def find_time_delay(s1, s2, datarate=1, resolution: bool=False): """ Finds the time shift or delay between two signals If s1 is advanced to s2, then the delay is positive. Parameters ---------- s1: array-like s2: array-like datarate: int, optional Input data sample rate in Hz. I...
78,497
def create(workout_type, user_id): """Creates a workout object of the specified type.""" workout = None if workout_type == Keys.WORKOUT_TYPE_EVENT: workout = Event.Event(user_id) elif workout_type == Keys.WORKOUT_TYPE_REST: workout = Rest.Rest(user_id) else: workout = Workout...
78,498
def populate_hop_connections(graph, switchbox_models, connections): """ Populates HOP connections """ # Process connections bar = progressbar_utils.progressbar conns = [c for c in connections if is_hop(c)] for connection in bar(conns): # Get switchbox models src_switchbox_m...
78,499