content
stringlengths
22
815k
id
int64
0
4.91M
def sort_results(boxes): """Returns the top n boxes based on score given DenseCap results.json output Parameters ---------- boxes : dictionary output from load_output_json n : integer number of boxes to return Returns ------- sorted dictionary """ r...
25,300
def get_date(d : str) -> datetime.datetime: """A helper function that takes a ModDB string representation of time and returns an equivalent datetime.datetime object. This can range from a datetime with the full year to second to just a year and a month. Parameters ----------- d : str ...
25,301
def validate_selected_audioTrackUID(audioTrackUID): """Check that an audioTrackUID has references required for this implementation""" if audioTrackUID.trackIndex is None: raise AdmError("audioTrackUID {atu.id} does not have a track index, " "which should be specified in the CHNA c...
25,302
def var_policer(*args): """Returns a variable policer object built from args.""" return VarPolicer(args)
25,303
def winner(board): """ Returns the winner of the game, if there is one. """ #looking horizontal winner i = 0 while i < len(board): j = 1 while j <len(board): if board[i][j-1]==board[i][j] and board[i][j] == board[i][j+1]: return board[i][j] ...
25,304
def freqz_resp_list(b, a=np.array([1]), mode='dB', fs=1.0, n_pts=1024, fsize=(6, 4)): """ A method for displaying digital filter frequency response magnitude, phase, and group delay. A plot is produced using matplotlib freq_resp(self,mode = 'dB',Npts = 1024) A method for displaying the filt...
25,305
def _nslookup(ipv4): """Lookup the hostname of an IPv4 address. Args: ipv4: IPv4 address Returns: hostname: Name of host """ # Initialize key variables hostname = None # Return result try: ip_results = socket.gethostbyaddr(ipv4) if len(ip_results) > 1:...
25,306
def get_service_node(service): """ Returns the name of the node that is providing the given service, or empty string """ node = rosservice_get_service_node(service) if node == None: node = "" return node
25,307
def set_up_boxes(path, device): """ Entrypoint for the segmentation file. Cycles through all the videos in the specified path and attempts to set up the bounding boxes for that video :param path: path to the videos :type path: str :param device: device to run models on :type device: str ...
25,308
def _download_nasdaq_symbols(timeout): """ @param timeout: the time to wait for the FTP connection """ try: ftp_session = FTP(_NASDAQ_FTP_SERVER, timeout=timeout) ftp_session.login() except all_errors as err: raise RemoteDataError('Error connecting to %r: $s' % ...
25,309
def sessions(request): """ Cookies prepeocessor """ context = {} return context
25,310
def dynamax_mnn(src: nb.typed.Dict, trg: nb.typed.Dict, src_emb: np.ndarray, trg_emb: np.ndarray, src_k: np.ndarray, trg_k: np.ndarray) -> np.ndarray: """ Run Dynamax-Jaccard in both directions and infer mutual neighbors. :param src nb.typed.Dict: src_id2pointers dictionary ...
25,311
def resnet152(pretrained=False, progress=True, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet152', Distil...
25,312
def initialize_weights(model: nn.Module, args: Namespace): """ Initializes the weights of a model in place. :param model: An nn.Module. """ for param in model.parameters(): if param.dim() == 1: nn.init.constant_(param, 0) else: if args.uniform_init: # for re...
25,313
def _load_model(featurizer_path): """Load the featurization model Parameters ---------- featurizer_path: str Path to the saved model file Returns ------- The loaded PyTorch model """ # load in saved model pth...
25,314
def grid0_baseline(num_runs, render=True): """Run script for the grid0 baseline. Parameters ---------- num_runs : int number of rollouts the performance of the environment is evaluated over render : bool, optional specifies whether to use the gui during e...
25,315
def read_aims(filename): """Method to read FHI-aims geometry files in phonopy context.""" lines = open(filename, 'r').readlines() cell = [] is_frac = [] positions = [] symbols = [] magmoms = [] for line in lines: fields = line.split() if not len(fields): con...
25,316
def test(model, issue_batches): """ return accuracy on test set """ session = tf.get_default_session() num_correct = 0 num_predict = 0 for epoch, step, eigens, labels in issue_batches: feeds = { model['eigens']: eigens, } guess = session.run(model['gues...
25,317
def evaluate_sample(ResNet50_model, X_train, Y_train, X_val_b,Y_val_b,X_data,Y_data,checkpoint_path): """ A function that accepts a labeled-unlabeled data split and trains the relevant model on the labeled data, returning the model and it's accuracy on the test set. """ # shuffle the training set: ...
25,318
def groupbys(df1, df2, by=None, left_by=None, right_by=None, allow_right_empty=False): """ df1: Left pandas.DataFrame df2: Right pandas.DataFrame by: "by" of groupby. Use intersection of each columns, if it is None. left_by: This or "by" is used as "by" of df1.groupby. right_by: This or "by" is ...
25,319
def plotThreePlanes(potentialOp, gridFun, limits, dimensions, colorRange=None, transformation='real', evalOps=None): """ Plot the potential generated by applying a potential operator to a grid function on the xy, xz and yz planes. *Parameters:* - potentialOp (PotentialOperato...
25,320
def Base64WSEncode(s): """ Return Base64 web safe encoding of s. Suppress padding characters (=). Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type unicode to string type first. @param s: string to encode as Base64 @type s: string @return: Base64 representation of...
25,321
def test_tf2zpk(): """test the tf2zpk function""" (a, b, c) = tf2zpk(1, 2) assert a.size == 0 assert b.size == 0 assert c == 0.5
25,322
def onlyWikipediaURLS(urls): """Some example HTML page data is from wikipedia. This function converts relative wikipedia links to full wikipedia URLs""" wikiURLs = [url for url in urls if url.startswith('/wiki/')] return ["https://en.wikipedia.org"+url for url in wikiURLs]
25,323
def run(): """Parses command line and dispatches the commands""" args = docopt(__doc__) configure_logging(args["--debug"]) disco_route53 = DiscoRoute53() if args['list-zones']: for hosted_zone in disco_route53.list_zones(): is_private_zone = hosted_zone.config['PrivateZone'] ...
25,324
def get_image_filename_index(): """ Obtain a mapping of filename -> filepath for images :return: """ index_path = osp.join(SEG_ROOT, 'privacy_filters', 'cache', 'fname_index.pkl') if osp.exists(index_path): print 'Found cached index. Loading it...' return pickle.load(open(index_p...
25,325
def _on_post_syncdb(app, **kwargs): """Handler to install baselines after syncdb has completed. This will install baselines for any new apps, once syncdb has completed for the app, and will notify the user if any evolutions are required. Args: app (module): The app whose models wer...
25,326
def test_find_matches_no_dupes(small_ktree): """Test find matches with small ktree.""" temp = find_matches(small_ktree, 3) assert len(temp) == 1
25,327
def merge_coordinates(coordinates, capture_size): """Merge overlapping coordinates for MIP targets. Parameters ---------- coordinates: python dictionary Coordinates to be merged in the form {target-name: {chrom: chrx, begin: start-coordinate, end: end-coordinate}, ..} capture_size: ...
25,328
def update_one_record(dns, zones, record_name, record_type, data): """ Update a DNS record to point at a specific value, creating it if necessary, deleting any other records of other types pointing at the same DNS name if necessary. @param dns: The DNS provider. @param zones: The list of zone ...
25,329
def log_in_directly(context): """ This differs to the `log_in` function above by logging in directly to a page where the user login form is presented :param context: :return: """ assert context.persona context.execute_steps(u""" When I fill in "login" with "$name" And I fill...
25,330
def induce_and_write_rules(): """Induce and write set of rules.""" examples = tsv_utils.read_tsv(FLAGS.input) config = induction_utils.InductionConfig( sample_size=FLAGS.sample_size, max_iterations=FLAGS.max_iterations, min_delta=FLAGS.min_delta, terminal_codelength=FLAGS.terminal_codeleng...
25,331
def Emojify_V2(input_shape, word_to_vec_map, word_to_index): """ Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation word_t...
25,332
def SetFdBlocking(fd, is_blocking): """Set a file descriptor blocking or nonblocking. Please note that this may affect more than expected, for example it may affect sys.stderr when called for sys.stdout. Returns: The old blocking value (True or False). """ if hasattr(fd, 'fileno'): fd = fd.fileno(...
25,333
def de_parser(lines): """return a dict of {OfficalName: str, Synonyms: str, Fragment: bool, Contains: [itemdict,], Includes: [itemdict,]} from DE lines The DE (DEscription) lines contain general descriptive information about the sequence stored. This information is generally sufficient to identify ...
25,334
def send_mail(address, passwd): """ Send verification emails based on below template. """ message = ( "Hey there!\n\nYour HOBY Feedback account is ready to be logged " + "into. If you have any problems logging in, please contact the " + "operations staff who created your account....
25,335
def roundPrecision(number, precision=4): """ Rounds the given floating point number to a certain precision, for output.""" return float(('{:.' + str(precision) + 'E}').format(number))
25,336
def get_profile(host, cluster = False): """ Download profile to temporary file and return tempfile handle. """ cmd = [GETPROF, host] if cluster: cmd.insert(1, "-C") if debug: cmd.insert(1, "-D") sys.stderr.write("%s: launching '%s'\n" % (CALL, " ".join(cmd))) tempfh = tempfile.Named...
25,337
def stringToNumbers(string, separators=[","], commentSymbol="#"): """ Return a list of splitted string and numbers from string "string". Numbers will be converted into floats. Text after "#" will be skipped. --- string: the string to be converted. --- separators: a list of additional separators other than whitesp...
25,338
def friend_invitation_by_facebook_send_view(request): # friendInvitationByFacebookSend """ :param request: :return: """ voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id recipients_facebook_id_array = request.GET.getlist('recipients_facebook_id...
25,339
def test_multichoiceanswer_init3(): """Test wrong arguments """ text = "text" with pytest.raises(TypeError): exam.MultiChoiceAnswer(image=text)
25,340
def inv_send_received(r, **attr): """ Confirm a Shipment has been Received - called via POST from inv_send_rheader - called via JSON method to reduce request overheads """ if r.http != "POST": r.error(405, current.ERROR.BAD_METHOD, next = URL(), ...
25,341
def gradcheck(trnodes,cost,datasrc,maxtime=2,rtol=1e-5,atol=1e-4): """ Checks the computation of grad() against numerical gradient. If any component of the numerical gradient does not match, an AssertionError is raised with information about the problem. """ # Collect each trainable node in the...
25,342
def filter_table(table, filter_series, ignore=None): """ Filter a table based on a set of restrictions given in Series of column name / filter parameter pairs. The column names can have suffixes `_min` and `_max` to indicate "less than" and "greater than" constraints. Parameters ---------- ...
25,343
def analogy_computation_2d(f_first_enc, f_first_frame, f_current_enc, first_depth): """Implements the deep analogy computation.""" with tf.variable_scope('analogy_computation'): frame_enc_diff = f_first_frame - f_first_enc fr...
25,344
def format_to_TeX(elements): """returns BeautifulSoup elements in LaTeX. """ accum = [] for el in elements: if isinstance(el, NavigableString): accum.append(escape_LaTeX(el.string)) else: accum.append(format_el(el)) return "".join(accum)
25,345
def plot_light_curve(time, magnitude, xunit="s", filename=None): """ Plot light curve caused by the doppler beaming in a binary system. Parameters ---------- time : 1D numpy.array(dtype=float) Array represents time. magnitude : 1D numpy.array(dtype=float) Array represents magnit...
25,346
def namedlist(typename, field_names, verbose=False, rename=False): """Returns a new subclass of list with named fields. >>> Point = namedlist('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with p...
25,347
def messages_to_corpus(messages, filename='corpus.txt', append=True): """ Converts midi messages to corpus of encoding to feed into the network :param messages: array of instrument messages filename: Name of the file in which to save the converted text append: Overwrites if false """ # t...
25,348
def preprocess_things(data_dir: str = "./data", file_identifier: str = "*-5k.json"): """Preprocess things (essentially proper nouns) from WikiData with files named "*-5k.json": - Filters things - Combines thingLabel and thingAltLabel to labels field """ fps = glob(os.path.join(data_dir, file...
25,349
def has_good_frames(frames: List[MonitoredFrame]) -> bool: """ Find a frame with a score larger than X """ return any([frame.score and frame.score > 3 for frame in frames])
25,350
def updateHistory(conn, author, message_id, backer): """ Updates the history Returns success """ c = conn.cursor() c.execute(prepareQuery("INSERT INTO votes_history (user_id, message_id, backer) VALUES (?,?,?)"), (int(author), int(message_id), int(backer), )) conn.commit() return c.rowco...
25,351
def pyc_loads(data): """ Load a .pyc file from a bytestring. Arguments: data(bytes): The content of the .pyc file. Returns: PycFile: The parsed representation of the .pyc file. """ return pyc_load(six.BytesIO(data))
25,352
def get_master_tag_list(context, ecosystem, use_token): """Call API endpoint master tag list.""" if use_token: context.response = requests.get(master_tag_list_url(context, ecosystem), headers=authorization(context)) else: context.response = requests.ge...
25,353
def main() -> None: """The main function for this file""" print(read_all('../../settings.cfg'))
25,354
def time_series_figure(time_series, polynomial, drift, snr): """ Return a matplotlib figure containing the time series and its polynomial model. """ figure = plt.figure() plot = figure.add_subplot(111) plot.grid() plt.title("Drift: {0: .1f}% - SNR: {1: .1f}dB".format( drift * 100, 10...
25,355
def _create_standard_configuration_models_py_(code, geometry_type, absolute_path, schema=None, primary_key_is_string=False): """ The simplest way to get a python file containing a database definition in sqlalchemy orm way. It will contain all necessary definiti...
25,356
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
25,357
def debug_config( config_path: Union[str, Path], overrides: dict = {}, code_path: Union[str, Path] = None, show_funcs: bool = False, show_vars: bool = False ): """Debug a config file and show validation errors. The function will create all objects in the tree and validate them. Note that ...
25,358
def log(cm_uuid: UUID): """ :GET: returns the most recent logs for the specified control module. accepts the following url parameters - limit: the number of logs that should be returned - offset: offset the number of logs that should be returned - log_type: the type of log that should be...
25,359
def RetrieveResiduesNumbers(ResiduesInfo): """Retrieve residue numbers.""" # Setup residue IDs sorted by residue numbers... ResNumMap = {} for ResName in ResiduesInfo["ResNames"]: for ResNum in ResiduesInfo["ResNum"][ResName]: ResNumMap[ResNum] = ResName ResNumsList = [] ...
25,360
def get_data_with_station(station_id): """ *** Returns Pandas DataFrame *** Please Input Station ID: (String)""" print("\nGETTING DATA FOR STATION: ",station_id) ftp = FTP('ftp.ncdc.noaa.gov') ftp.login() ftp.cwd('pub/data/ghcn/daily/all') ftp.retrbinary('RETR '+station_id+'.dly',...
25,361
def _canonicalize(path): """Makes all paths start at top left, and go clockwise first.""" # convert args to floats path = [[x[0]] + list(map(float, x[1:])) for x in path] # _canonicalize each subpath separately new_substructures = [] for subpath in _separate_substructures(path): leftmos...
25,362
def cleanup_all_built_pipelines(): """Cleans up all built pipelines.""" for pipeline_config_path in find_all_built_pipelines(): cleanup_pipeline(pipeline_config_path)
25,363
def AddAdvancedOptions(parser, required=False): """Adds the cloud armor advanced options arguments to the argparse.""" parser.add_argument( '--json-parsing', choices=['DISABLED', 'STANDARD'], type=lambda x: x.upper(), required=required, help=('The JSON parsing behavior for this rule. '...
25,364
def extract_meta(src: bytes) -> Tuple[int, int]: """ Return a 2-tuple: - the length of the decoded block - the number of bytes that the length header occupied. """ v, n = uvarint(src) if n <= 0 or v > 0xFFFFFFFF: raise CorruptError if v > 0x7FFFFFFF: raise TooLargeError ...
25,365
def metric_source_configuration_table(data_model, metric_key, source_key) -> str: """Return the metric source combination's configuration as Markdown table.""" configurations = data_model["sources"][source_key].get("configuration", {}).values() relevant_configurations = [config for config in configurations ...
25,366
def search(keyword, limit=20): """ Search is the iTunes podcast directory for the given keywords. Parameter: keyword = A string containing the keyword to search. limit: the maximum results to return, The default is 20 results. returns: ...
25,367
def job_checks(name: str): """ Check if the job has parameters and ask to insert them printing the default value """ p = job_parameters(name) new_param = {} if p: ask = Confirm.ask( f"Job [bold green] {name} [/bold green] has parameters, do you want to insert them?", ...
25,368
def post(): """Post new message""" error = None if request.method == 'POST'\ and request.form['message'] != '' and request.form['message'] is not None: user_zid = session['logged_in'] post_message = request.form['message'] post_privacy = request.form['post_privacy'] ...
25,369
def read_article_feed(): """ Get articles from RSS feed """ feed = feedparser.parse(FEED) for article in feed['entries']: if article_is_not_db(article['title'], article['published']): send_notification(article['title'], article['link']) add_article_to_db(article['title'...
25,370
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_connection_end_pointtopology_uuidnode_uuidnode_edge_point_uuidconnection_end_point_uuid_get(uuid, local_id, topology_uuid, node_uuid, node_edge_point_uuid, connection_end_point_uuid): # noqa: E501 """data_context_connectivity_context_...
25,371
def git_clone(url: str, path: Union[Path, str]) -> None: """Clone a git repository.""" Repo.clone_from(url, str(path))
25,372
def add_member_to_crypto_key_policy( project_id, location_id, key_ring_id, crypto_key_id, member, role): """Adds a member with a given role to the Identity and Access Management (IAM) policy for a given CryptoKey associated with a KeyRing.""" # Creates an API client for the KMS API. client = km...
25,373
def softmax(logits): """Take the softmax over a set of logit scores. Args: logits (np.array): a 1D numpy array Returns: a 1D numpy array of probabilities, of the same shape. """ if not isinstance(logits, np.ndarray): logits = np.array(logits) # 1D array logits = logit...
25,374
def _aggregate(df, variable, components=None, method=np.sum): """Internal implementation of the `aggregate` function""" # list of variables require default components (no manual list) if islistable(variable) and components is not None: raise ValueError( "Aggregating by list of variables...
25,375
def get_attributes(klass): """Get all class attributes. """ attributes = list() for attr, value in inspect.\ getmembers(klass, lambda x: not inspect.isroutine(x)): if not (attr.startswith("__") and attr.endswith("__")): attributes.append(attr) return attributes
25,376
def render(html): """Convert HTML to a PDF""" output = io.BytesIO() surface = cairo.PDFSurface(output, 595, 842) ctx = cairo.Context(surface) cffictx = cairocffi.Context._from_pointer(cairocffi.ffi.cast('cairo_t **', id(ctx) + object.__basicsize__)[0], incref=True) html = etree.parse(io.String...
25,377
def computeFlowImage(u,v,logscale=True,scaledown=6,output=False): """ topleft is zero, u is horiz, v is vertical red is 3 o'clock, yellow is 6, light blue is 9, blue/purple is 12 """ colorwheel = makecolorwheel() ncols = colorwheel.shape[0] radius = np.sqrt(u**2 + v**2) if output: ...
25,378
def day_display(year, month, all_month_events, day): """ Returns the events that occur on the given day. Works by getting all occurrences for the month, then drilling down to only those occurring on the given day. """ # Get a dict with all of the events for the month count = CountHandler(yea...
25,379
def decimal_to_octal(num): """Convert a Decimal Number to an Octal Number.""" octal = 0 counter = 0 while num > 0: remainder = num % 8 octal = octal + (remainder * math.pow(10, counter)) counter += 1 num = math.floor(num / 8) # basically /= 8 without remainder if any ...
25,380
def get_formatted_dates(date_ranges): """Returns list of dates specified by date_ranges, formtted for Swiftly API use. date_ranges is a list of dict, with each dict specifying a range of dates in string format. sample dict for Tue/Wed/Thu in Sep/Oct: { "start_date": "09-01-2019", "end_d...
25,381
def _get_config_path(config_path): """Find path to yaml config file Args: config_path: (str) Path to config.yaml file Returns: Path to config.yaml if specified else default config.yaml Raises: ValueError: If the config_path is not None but doesn't exist """ if config_...
25,382
def read_img(img: str, no_data: float, mask: str = None, classif: str = None, segm: str = None) ->\ xr.Dataset: """ Read image and mask, and return the corresponding xarray.DataSet :param img: Path to the image :type img: string :type no_data: no_data value in the image :type no_data: f...
25,383
def any_user(password=None, permissions=[], groups=[], **kwargs): """ Shortcut for creating Users Permissions could be a list of permission names If not specified, creates active, non superuser and non staff user """ is_active = kwargs.pop('is_active', True) is_superuser = kwargs.pop...
25,384
def devices_to_use(): """Returns the device objects for the accel. we are the most likely to use. Returns: List of logical devices of the accelerators we will use. """ if tf.config.list_logical_devices("TPU"): devices = tf.config.list_logical_devices("TPU") elif tf.config.list_logical_devices("GPU"):...
25,385
def barcode_density(bars, length): """ calculates the barcode density (normalized average cycle lifetime) of a barcode """ densities = np.zeros(len(bars)) nums = np.array([len(bars[i][1]) for i in range(len(bars))]) num_infs = np.zeros(len(bars)) for i in range(len(bars)): tot = ...
25,386
def create_parser(): """Creates the default argument parser. Returns ------- parser : ArgumentParser """ parser = argparse.ArgumentParser() parser.add_argument('--version', action='version', version=__version__) parser.add_argument('--config-file') parser.add_argument('--update-conf...
25,387
def test_prediction_gradient(): """Test computation of prediction gradients.""" # Binary classification n_classes = 1 mlp = MLPClassifier(n_epochs=100, random_state=42, hidden_units=(5,)) X, y = make_classification( n_samples=1000, n_features=20, n_informative=n_classes, n_redundant=0, ...
25,388
def preprocess_data(datadir, verbose=False): """ This function gets the raw data and the FSL results and restructures them in a convenient data format. """ dataDir = os.path.abspath(datadir) if verbose: print(f"Performing data preprocessing in directory:\n{dataDir:s}") time.sleep(...
25,389
def genRankSurvey(readername, candidates, binsize, shareWith=None): """ readername (str) candidates (iterable) binsize (int) shareWith (str) optional """ # connect and craete survey c = cornellQualtrics() surveyname = "Ranking Survey for {}".format(readername) surveyId = c.create...
25,390
def _get_badge_status( self_compat_res: dict, google_compat_res: dict, dependency_res: dict) -> BadgeStatus: """Get the badge status. The badge status will determine the right hand text and the color of the badge. Args: self_compat_res: a dict containing a package's sel...
25,391
def _get_yaml_as_string_from_mark(marker): """Gets yaml and converts to text""" testids_mark_arg_no = len(marker.args) if testids_mark_arg_no > 1: raise TypeError( 'Incorrect number of arguments passed to' ' @pytest.mark.test_yaml, expected 1 and ' 'received {}'.f...
25,392
def createsuperuser(name, username, email): """Create the superuser account to access the admin panel.""" from ..contrib.auth.models import User, Group name:str = name or Console.input.String("enter admin name: ") email:str = email or Console.input.String("enter admin email: ") ...
25,393
def combine_dicts(w_dict1, w_dict2, params, model): """ Combine two dictionaries: """ w_dict = w_dict1 + w_dict2 eps = params[0] params[0] = 0 P_w = [] w_dict = md.remove_duplicates_w_dict(P_w,w_dict,params,model) return w_dict
25,394
def geocode_mapping(row, aian_ranges, aian_areas, redefine_counties, strong_mcd_states): """ Maps an RDD row to a tuple with format (state, AIAN_bool, AIANNHCE, county, place/MCD, tract, block), where place/MCD is the five digit MCD in MCD-strong states and 5 digit place otherwise AIAN_bool is '1' if th...
25,395
def get_stan_input( scores: pd.DataFrame, priors: Dict, likelihood: bool, ) -> Dict: """Get an input to cmdstanpy.CmdStanModel.sample. :param measurements: a pandas DataFrame whose rows represent measurements :param model_config: a dictionary with keys "priors", "likelihood" and "x_cols". ...
25,396
def get_mph(velocity): """ Returns ------- convert m/s to miles per hour [mph]. """ velocity = velocity * 3600 /1852 return velocity
25,397
def _load_jsonl(input_path) -> list: """ Read list of objects from a JSON lines file. """ data = [] with open(input_path, 'r', encoding='utf-8') as f: for line in f: data.append(json.loads(line.rstrip('\n|\r'))) print('[LoadJsonl] Loaded {} records from {}'.format(len(data), ...
25,398
def run(config): """Run the nowcast system worker launch scheduler. * Prepare the schedule as specified in the configuration file. * Loop forever, periodically checking to see if it is time to launch the scheduled workers. :param config: Nowcast system configuration. :type config: :py:class:...
25,399