content
stringlengths
22
815k
id
int64
0
4.91M
def parse(peaker): # type: (Peaker[Token]) -> Node """Parse the docstring. Args: peaker: A Peaker filled with the lexed tokens of the docstring. Raises: ParserException: If there is anything malformed with the docstring, or if anything goes wrong with parsing. #...
31,300
def listify(what, *, debug=False): """ non-reversible version of listify_safe(). In this case "None" always means "no columns". output: list """ l, _ = listify_safe(what, debug=debug) return l
31,301
def check_server_url(url): """Check if given url starts with http tag""" goodName = url.startswith('http://') or url.startswith('https://') if not goodName: msg = "You must include http(s):// in your server's address, %s doesn't" % url raise ValueError(msg)
31,302
def sphrec(r, colat, lon): """ Convert from spherical coordinates to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphrec_c.html :param r: Distance of a point from the origin. :type r: float :param colat: Angle of the point from the positive Z-axis. :type...
31,303
def counter_endpoint( event=None, context=None ): """ API endpoint that returns the total number of UFO sightings. An example request might look like: .. sourcecode:: http GET www.x.com/counter HTTP/1.1 Host: example.com Accept: application/json, text/javascript Results will...
31,304
def search_trie(result, trie): """ trie search """ if result.is_null(): return [] # output ret_vals = [] for token_str in result: ret_vals += trie.find(token_str) if result.has_memory(): ret_vals = [ one_string for one_string in ret_vals if resu...
31,305
def get_nb_entry(path_to_notes: str = None, nb_name: str = None, show_index: bool = True) -> str: """Returns the entry of a notebook. This entry is to be used for the link to the notebook from the table of contents and from the navigators. Depending on the value of the...
31,306
def get_label_encoder(config): """Gets a label encoder given the label type from the config Args: config (ModelConfig): A model configuration Returns: LabelEncoder: The appropriate LabelEncoder object for the given config """ return LABEL_MAP[config.label_type](config)
31,307
def get_lesson_comment_by_sender_user_id(): """ { "page": "Long", "size": "Long", "sender_user_id": "Long" } """ domain = request.args.to_dict() return lesson_comment_service.get_lesson_comment_by_sender_user_id(domain)
31,308
def output(pin, dir): """ Writes state (HIGH, LOW) based on pin number. Param 'pin': Any pin from 1 to 16. Param 'dir': Defines pin state, on (HIGH) or off (LOW). Return: ValueError if pin or dir are invalid. """ global LATA, LATB if (str(pin).isdigit() and (0 < pin < 17)): ...
31,309
def _inertia_grouping(stf): """Grouping function for class inertia. """ if hasattr(stf[2], 'inertia_constant'): return True else: return False
31,310
def parse_input(raw_input: str) -> nx.DiGraph: """Parses Day 12 puzzle input.""" graph = nx.DiGraph() graph.add_nodes_from([START, END]) for line in raw_input.strip().splitlines(): edge = line.split('-') for candidate in [edge, list(reversed(edge))]: if candidate[0] == END: ...
31,311
def zonal_mode_extract(infield, mode_keep, low_pass = False): """ Subfunction to extract or swipe out zonal modes (mode_keep) of (y, x) data. Assumes here that the data is periodic in axis = 1 (in the x-direction) with the end point missing If mode_keep = 0 then this is just the zonal averaged field I...
31,312
def create_room(game_map, room): """Go through the tiles in the rectangle and make them passable.""" for x in range(room.x1 + 1, room.x2): for y in range(room.y1 + 1, room.y2): game_map.walkable[x, y] = True game_map.transparent[x, y] = True
31,313
def clone(): """Clone model PUT /models Parameters: { "model_name": <model_name_to_clone>, "new_model_name": <name_for_new_model> } Returns: - {"model_names": <list_of_model_names_in_session>} """ request_json = request.get_json() name = request_...
31,314
def GetFlagFromDest(dest): """Returns a conventional flag name given a dest name.""" return '--' + dest.replace('_', '-')
31,315
def updated_clicked_recipe_maker(w): """ Updates the maker display Data with the selected recipe""" if not w.LWMaker.selectedItems(): return DP_HANDLER.clear_recipe_data_maker(w) handle_alcohollevel_change(w) cocktailname = w.LWMaker.currentItem().text() machineadd_data, handa...
31,316
def get_rst_export_elements( file_environment, environment, module_name, module_path_name, skip_data_value=False, skip_attribute_value=False, rst_elements=None ): """Return :term:`reStructuredText` from exported elements within *file_environment*. *environment* is the full :term:`Javascript` enviro...
31,317
def oriented_tree(): """ Number of unique oriented trees with n unlabeled nodes OEIS A000238 """
31,318
def get_insight_comments(): """ Get comments for insight """ alert_id = demisto.getArg('insight-id') resp_json = req('GET', 'alert/%s/comments' % alert_id, QUERY) comments = [to_readable(comment, ['id', 'alert_id', 'author', 'body', 'last_updated', 'timestamp'], {'ale...
31,319
def ganache_url(host='127.0.0.1', port='7445'): """Return URL for Ganache test server.""" return f"http://{host}:{port}"
31,320
def to_news_detail_list_by_period(uni_id_list: list, start: str, end: str) -> list: """ 根据统一社会信用代码列表,获取企业在给定日期范围的新闻详情列表,使用串行 :param end: :param start: :param uni_id_list: :return: """ detail_list = [] for uni_id in ...
31,321
def positions_to_df(positions: List[alp_api.entity.Asset]) -> pd.DataFrame: """Generate a df from alpaca api assests Parameters ---------- positions : List[alp_api.entity.Asset] List of alpaca trade assets Returns ------- pd.DataFrame Processed dataframe """ df = p...
31,322
def get_all_pages(date): """For the specific date, get all page URLs.""" r = requests.get(URL, params={"search": date}) soup = BeautifulSoup(r.text, "html.parser") return [ f"https://www.courts.phila.gov/{url}" for url in set([a["href"] for a in soup.select(".pagination li a")]) ]
31,323
def boundary_condition( outer_bc_geometry: List[float], inner_bc_geometry: List[float], bc_num: List[int], T_end: float, ): """ Generate BC points for outer and inner boundaries """ x_l, x_r, y_d, y_u = outer_bc_geometry xc_l, xc_r, yc_d, yc_u = inner_bc_geometry N_x, N_y, N_t, N...
31,324
def test_upsert_return_created_values(): """ Tests that values that are created are returned properly when returning is True. """ results = pgbulk.upsert( models.TestModel, [ models.TestModel(int_field=1), models.TestModel(int_field=3), models.Test...
31,325
def extractInfiniteNovelTranslations(item): """ # Infinite Novel Translations """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None tagmap = [ ('Ascendance of a Bookworm', 'Ascend...
31,326
def set_output_dir( data: dict, rel_path: str, default: str = DEFAULT_DIR ) -> None: """Set the 'output_dir' key correctly on a dictionary.""" out_dir = get_output_dir(data, rel_path, default) os.makedirs(out_dir, exist_ok=True) data["output_dir"] = out_dir
31,327
def fill_diagonal(matrix, value, k=0, unpadded_dim=None): """ Returns a matrix identical to `matrix` except that the `k'th` diagonal has been overwritten with the value `value`. Args: matrix: Matrix whose diagonal to fill. value: The value to fill the diagonal with. k: The diagonal to fill. unpa...
31,328
def loop_filter(data, images, features, matches, pairs): """ if there’s an edge between (i, j) where i and j are sequence numbers far apart, check that there also exists an edge (i plus/minus k, j plus/minus k), where k is a small integer, and that the loop formed by the four nodes pass the multiplying-...
31,329
def container_model(*, model: type, caption: str, icon: Optional[str]) -> Callable: """ ``container_model`` is an object that keeps together many different properties defined by the plugin and allows developers to build user interfaces in a declarative way similar to :func:`data_model`. ``container_mod...
31,330
def ward_quick(G, feature, verbose = 0): """ Agglomerative function based on a topology-defining graph and a feature matrix. Parameters ---------- G graph instance, topology-defining graph feature: array of shape (G.V,dim_feature): some vectorial information related to th...
31,331
def conv3x3(in_planes, out_planes, stride=1, output_padding=0): """3x3 convolution transpose with padding""" return nn.ConvTranspose2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, output_padding=output_padding, ...
31,332
def unwrap(func): """ Returns the object wrapped by decorators. """ def _is_wrapped(f): return hasattr(f, '__wrapped__') unwrapped_f = func while (_is_wrapped(unwrapped_f)): unwrapped_f = unwrapped_f.__wrapped__ return unwrapped_f
31,333
def get_payload_from_scopes(scopes): """ Get a dict to be used in JWT payload. Just merge this dict with the JWT payload. :type roles list[rest_jwt_permission.scopes.Scope] :return dictionary to be merged with the JWT payload :rtype dict """ return { get_setting("JWT_PAYLOAD_SCO...
31,334
def missing_keys_4(data: Dict, lprint=print, eprint=print): """ Add keys: _max_eval_all_epoch, _max_seen_train, _max_seen_eval, _finished_experiment """ if "_finished_experiment" not in data: lprint(f"Add keys _finished_experiment ...") max_eval = -1 for k1, v1 in data["_eval_trace"].i...
31,335
def translate(txt): """Takes a plain czech text as an input and returns its phonetic transcription.""" txt = txt.lower() txt = simple_replacement(txt) txt = regex_replacement(txt) txt = chain_replacement(txt) txt = grind(txt) return txt
31,336
def struct_getfield_longlong(ffitype, addr, offset): """ Return the field of type ``ffitype`` at ``addr+offset``, casted to lltype.LongLong. """ value = _struct_getfield(lltype.SignedLongLong, addr, offset) return value
31,337
def test_connect(loop, conn): """ 测试连接对象属性 """ assert conn.loop is loop assert conn.timeout == 5 assert not conn.closed assert not conn.autocommit assert conn.isolation_level is '' assert conn.row_factory is None assert conn.text_factory is str
31,338
def subscribe(request): """View to subscribe the logged in user to a channel""" if request.method == "POST": channels = set() users = set() for key in request.POST: if key.startswith("youtube-"): channel_id = key[8:] if models.YoutubeChannel.ob...
31,339
def generate_orders(events, sell_delay=5, sep=','): """Generate CSV orders based on events indicated in a DataFrame Arguments: events (pandas.DataFrame): Table of NaNs or 1's, one column for each symbol. 1 indicates a BUY event. -1 a SELL event. nan or 0 is a nonevent. sell_delay (float): N...
31,340
def test__parser__match_construct(method, input_func, raw_seg): """Test construction of MatchResults.""" # Let's make our input src = input_func(raw_seg) # Test construction getattr(MatchResult, method)(src)
31,341
def RunCommand(cmd, print_cmd=True, error_ok=False, error_message=None, exit_code=False, redirect_stdout=False, redirect_stderr=False, cwd=None, input=None, enter_chroot=False, num_retries=0, log_to_file=None, combine_stdout_stderr=False): """Runs a shell command. Argum...
31,342
def eval_accuracies(hypotheses, references, sources=None, filename=None, mode='dev'): """An unofficial evalutation helper. Arguments: hypotheses: A mapping from instance id to predicted sequences. references: A mapping from instance id to ground truth sequences. copy_info: Map of id -->...
31,343
def perform_login(db: Session, user: FidesopsUser) -> ClientDetail: """Performs a login by updating the FidesopsUser instance and creating and returning an associated ClientDetail.""" client: ClientDetail = user.client if not client: logger.info("Creating client for login") client, _ = ...
31,344
def check(e, compiler_params, cmd=None, time_error=False, nerror=-1, nground=-1, nsamples=0, precompute_samples=None, print_command=False, log_rho=False, do_copy=True, extra_args='', do_run=True, do_compile=True, get_command=False, skip_save=False, ndims=-1, our_id=None, sanity_code=None, code_only=False): """ ...
31,345
def _bytestring_to_textstring(bytestring: str, number_of_registers: int = 16) -> str: """Convert a bytestring to a text string. Each 16-bit register in the slave are interpreted as two characters (1 byte = 8 bits). For example 16 consecutive registers can hold 32 characters (32 bytes). Not much of con...
31,346
def sigma_XH(elem,Teff=4500.,M_H=0.,SNR=100.,dr=None): """ NAME: sigma_XH PURPOSE: return uncertainty in a given element at specified effective temperature, metallicity and signal to noise ratio (functional form taken from Holtzman et al 2015) INPUT: elem - string elem...
31,347
def search(outputpath: str, query: Optional[str] = None, since: Optional[datetime.date] = None, until: Optional[datetime.date] = None, limit: Optional[int] = None, limit_per_database: Optional[int] = None, databases: Optional[List[str]] = None, publication_types: Optional[List[str]] = None, scopus_api_t...
31,348
def test_ipow_special_cases_two_args_equal__less_equal_1(arg1, arg2): """ Special case test for `__ipow__(self, other, /)`: - If `x1_i` is `-infinity`, `x2_i` is less than `0`, and `x2_i` is an odd integer value, the result is `-0`. """ res = asarray(arg1, copy=True) ipow(res, arg2) ...
31,349
def plot_graph(graphs, title=None, xlabel='x', ylabel='y'): """ Plot graphs using matplot libray Paramaters ---------- graphs : list List of created graphs title : str title of graph xlabel : str name of x axis ylabel : str ...
31,350
def lazy_load_command(import_path: str) -> Callable: """Create a lazy loader for command""" _, _, name = import_path.rpartition('.') def command(*args, **kwargs): func = import_string(import_path) return func(*args, **kwargs) command.__name__ = name # type: ignore return command
31,351
def tlam(func, tup): """Split tuple into arguments """ return func(*tup)
31,352
def sax_df_reformat(sax_data, sax_dict, meter_data, space_btw_saxseq=3): """"Function to format a SAX timeseries original data for SAX heatmap plotting.""" counts_nb = Counter(sax_dict[meter_data]) # Sort the counter dictionnary per value # source: https://stackoverflow.com/questions/613183/how-do-i-so...
31,353
def rm_action(): """TODO: merge with clean_action (@pgervais)""" parser = ArgumentParser(usage='mprof rm [options] numbers_or_filenames') parser.add_argument('--version', action='version', version=mp.__version__) parser.add_argument("--dry-run", dest="dry_run", default=False, act...
31,354
def filter_not_t(func): """ Transformation for Sequence.filter_not :param func: filter_not function :return: transformation """ return Transformation( "filter_not({0})".format(name(func)), partial(filterfalse, func), {ExecutionStrategies.PARALLEL}, )
31,355
def get_task_by_id(id): """Return task by its ID""" return TaskJson.json_by_id(id)
31,356
def priority(floors, elevator): """Priority for a State.""" priority = 3 - elevator for i, floor in enumerate(floors): priority += (3 - i) * len(floor) return priority
31,357
def get_user_groups(user_id: Union[int, str]) -> List[UserSerializer]: """ 获取指定 User 的全部 Groups Args: user_id: 指定 User 的 {login} 或 {id} Returns: Group 列表, 语雀这里将 Group 均视作 User. """ uri = f'/users/{user_id}/groups' method = 'GET' anonymous = True return Request.send(...
31,358
def user_news_list(): """ 新闻列表 :return: """ user = g.user page = request.args.get("page") try: page = int(page) except Exception as e: current_app.logger.error(e) page = 1 # 查询 news_list = [] current_page = 1 total_page = 1 try: pagin...
31,359
def unificate_link(link): """Process whitespace, make first letter upper.""" link = process_link_whitespace(link) if len(link) < 2: return link.upper() else: return link[0].upper() + link[1:]
31,360
def compute_vel_acc( robo, symo, antRj, antPj, forced=False, gravity=True, floating=False ): """Internal function. Computes speeds and accelerations usitn Parameters ========== robo : Robot Instance of robot description container symo : symbolmgr.SymbolManager Instance of symbol...
31,361
def _sample_n_k(n, k): """Sample k distinct elements uniformly from range(n)""" if not 0 <= k <= n: raise ValueError("Sample larger than population or is negative") if 3 * k >= n: return np.random.choice(n, k, replace=False) else: result = np.random.choice(n, 2 * k) sele...
31,362
def plot_bout_start_end( body_speed, start: int = 0, end: int = -1, is_moving: np.ndarray = None, precise_end: int = None, precise_start: int = None, speed_th: float = 1, **other_speeds, ): """ Plot speeds zoomed in at start and end of bout """ f, axes = plt.subplots(...
31,363
def test_nelder_mead_max_iter(check_error): """ Test the OptimizationWorkChain with the Nelder-Mead engine in the case when the set `max_iter` is reached. This triggers the 202 exut status. """ check_error( engine=NelderMead, engine_kwargs=dict( simplex=[[1.2, 0.9], [1.,...
31,364
def test_search_not_found(): """ test search incorrect project function""" result = CliRunner().invoke( cli, ["search", "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"], catch_exceptions=False, ) assert result.exit_code == 0 assert "Project not found!" in result.output
31,365
def _all_usage_keys(descriptors, aside_types): """ Return a set of all usage_ids for the `descriptors` and for as all asides in `aside_types` for those descriptors. """ usage_ids = set() for descriptor in descriptors: usage_ids.add(descriptor.scope_ids.usage_id) for aside_type i...
31,366
def svn_client_invoke_get_commit_log2(*args): """svn_client_invoke_get_commit_log2(svn_client_get_commit_log2_t _obj, apr_array_header_t commit_items, void * baton, apr_pool_t pool) -> svn_error_t""" return _client.svn_client_invoke_get_commit_log2(*args)
31,367
def round_extent(extent, cellsize): """Increases the extent until all sides lie on a coordinate divisible by cellsize.""" xmin, ymin, xmax, ymax = extent xmin = np.floor(xmin / cellsize) * cellsize ymin = np.floor(ymin / cellsize) * cellsize xmax = np.ceil(xmax / cellsize) * cellsize ymax = ...
31,368
def add_numbers(): """Add two numbers server side, ridiculous but well...""" #a = request.args.get('a', 0, type=str)#input from html a = request.args.get('a') print(a) result = chatbot.main(a) print("Result: ", result) #input from html returned=a #return jsonify(returned);...
31,369
def _parse_stack_info(line, re_obj, crash_obj, line_num): """ :param line: line string :param re_obj: re compiled object :param crash_obj: CrashInfo object :return: crash_obj, re_obj, complete:Bool """ if re_obj is None: re_obj = re.compile(_match_stack_item_re()) complete = Fals...
31,370
def list_findings(DetectorId=None, FindingCriteria=None, SortCriteria=None, MaxResults=None, NextToken=None): """ Lists Amazon GuardDuty findings for the specified detector ID. See also: AWS API Documentation Exceptions :example: response = client.list_findings( DetectorId='string'...
31,371
def Orbiter(pos,POS,veloc,MASS,mass): """ Find the new position and velocity of an Orbiter Parameters ---------- pos : list Position vector of the orbiter. POS : list Position vector of the centre object. veloc : list Velocity of the orbiter. MASS : int M...
31,372
def remove_queue(queue): """ Removes an SQS queue. When run against an AWS account, it can take up to 60 seconds before the queue is actually deleted. :param queue: The queue to delete. :return: None """ try: queue.delete() logger.info("Deleted queue with URL=%s.", queue.url...
31,373
def build_heading(win, readonly=False): """Generate heading text for screen """ if not win.parent().albumdata['artist'] or not win.parent().albumdata['titel']: text = 'Opvoeren nieuw {}'.format(TYPETXT[win.parent().albumtype]) else: wintext = win.heading.text() newtext = '' ...
31,374
def GetTraceValue(): """Return a value to be used for the trace header.""" # Token to be used to route service request traces. trace_token = properties.VALUES.core.trace_token.Get() # Username to which service request traces should be sent. trace_email = properties.VALUES.core.trace_email.Get() # Enable/dis...
31,375
def get_file_size(file_obj): """获取文件对象的大小 get_file_size(open('/home/ubuntu-14.04.3-desktop-amd64.iso')) :param file_obj: file-like object. """ if (hasattr(file_obj, 'seek') and hasattr(file_obj, 'tell') and (six.PY2 or six.PY3 and file_obj.seekable())): try: curr...
31,376
def test_io_set_raw_more(tmpdir): """Test importing EEGLAB .set files.""" tmpdir = str(tmpdir) # test reading file with one event (read old version) eeg = io.loadmat(raw_fname_mat, struct_as_record=False, squeeze_me=True)['EEG'] # test negative event latencies negative_late...
31,377
def sql( where: str, parameters: Optional[Parameters] = None ) -> Union[str, Tuple[str, Parameters]]: """ Return a SQL query, usable for querying the TransitMaster database. If provided, parameters are returned duplicated, to account for the face that the WHERE clause is also duplicated. """ ...
31,378
def test_encoding_mismatch(tmp_path): """Render a simple template that lies about its encoding. Header says us-ascii, but it contains utf-8. """ template_path = tmp_path / "template.txt" template_path.write_text(textwrap.dedent("""\ TO: to@test.com FROM: from@test.com Conten...
31,379
def write_out_results (output_dir, ofile_prefix, param_suffixes, results): """ Write the results to the disk. The output filename is compiled in the following way: output_dir + "/" + prefix + "_" + dataframe_type + "_" + suffix.csv, with: prefix: string, can be used to index results comput...
31,380
def clip(a, a_min, a_max): """Clips the values of an array to a given interval. Given an interval, values outside the interval are clipped to the interval edges. For example, if an interval of ``[0, 1]`` is specified, values smaller than 0 become 0, and values larger than 1 become 1. Args: ...
31,381
def hole_eigenvalue_residual( energy: floatarray, particle: "CoreShellParticle" ) -> float: """This function returns the residual of the hole energy level eigenvalue equation. Used with root-finding methods to calculate the lowest energy state. Parameters ---------- energy : float, eV ...
31,382
def open_raster(filename): """Take a file path as a string and return a gdal datasource object""" # register all of the GDAL drivers gdal.AllRegister() # open the image img = gdal.Open(filename, GA_ReadOnly) if img is None: print 'Could not open %s' % filename sys.exit(1) el...
31,383
def reduce2latlon_seasonal( mv, season=seasonsyr, region=None, vid=None, exclude_axes=[], seasons=seasonsyr ): """as reduce2lat_seasonal, but both lat and lon axes are retained. Axis names (ids) may be listed in exclude_axes, to exclude them from the averaging process. """ # backwards compatibility with...
31,384
def GetFreshAccessTokenIfEnabled(account=None, scopes=None, min_expiry_duration='1h', allow_account_impersonation=True): """Returns a fresh access token of the given account or the active account. Same as GetAccessTo...
31,385
def my_plot( true, ass ): """画图""" f = plt.figure( ) plt.scatter( true[:,0], true[:,1], marker = '+', color = 'c' ) plt.scatter( ass[:, 0], ass[:,1], marker = 'o', color = 'r' ) plt.legend( ['True Position', 'Located Position']) plt.show( ) plt.savefig('mds-map.png')
31,386
def unicode_to_xes(uni): """Convert unicode characters to our ASCII representation of patterns.""" uni = uni.replace(INVISIBLE_CRAP, '') return ''.join(BOXES[c] for c in uni)
31,387
def AvailableSteps(): """(read-only) Number of Steps available in cap bank to be switched ON.""" return lib.Capacitors_Get_AvailableSteps()
31,388
def alembicConnectAttr(source, target): """ make sure nothing is connected the target and then connect the source to the target """ cmds.ExocortexAlembic_profileBegin(f="Python.ExocortexAlembic._functions.alembicConnectIfUnconnected") currentSource = cmds.connectionInfo(target, sfd=True) if currentSource != "" ...
31,389
def modify_list(result, guess, answer): """ Print all the key in dict. Arguments: result -- a list of the show pattern word. guess -- the letter of user's guess. answer -- the answer of word Returns: result -- the list of word after modified. """ guess = guess.lowe...
31,390
def test_DCT(): """ Test the opDCT operator """ from scipy.misc import lena import matplotlib.pyplot as plt from compsense.utilities import softThreshold, hardThreshold img = lena().astype(np.double) img /= img.max() op = opDCT(img.shape) img_conv = op.T(i...
31,391
def f(p, snm, sfs): """ p: proportion of all SNP's on the X chromosome [float, 0<p<1] snm: standard neutral model spectrum (optimally scaled) sfs: observed SFS """ # modify sfs fs = modify(p, sfs) # return sum of squared deviations of modified SFS with snm spectrum: return np.sum( ...
31,392
def get_N_intransit(tdur, cadence): """Estimates number of in-transit points for transits in a light curve. Parameters ---------- tdur: float Full transit duration cadence: float Cadence/integration time for light curve Returns ------- n_intransit: int Number of...
31,393
def assert_invalid_dimensions(deviceType, serial_interface, width, height): """ Assert an invalid resolution raises a :py:class:`luma.core.error.DeviceDisplayModeError`. """ with pytest.raises(luma.core.error.DeviceDisplayModeError) as ex: deviceType(serial_interface, width=width, height=hei...
31,394
def test_build_docs(): """Test that the documentation builds. We do this in a subprocess since the Sphinx configuration file activates the veneer and has other side-effects that aren't reset afterward. """ oldDirectory = os.getcwd() try: os.chdir('docs') subprocess.run(['make', ...
31,395
def version_callback(print_version: bool) -> None: """Print the version of the package.""" if print_version: console.print(f"[yellow]google_img[/] version: [bold blue]{version}[/]") raise typer.Exit()
31,396
def extract_keys(keys, dic, drop=True): """ Extract keys from dictionary and return a dictionary with the extracted values. If key is not included in the dictionary, it will also be absent from the output. """ out = {} for k in keys: try: if drop: ou...
31,397
def jsonresolver_loader(url_map): """Resolve the referred EItems for a Document record.""" from flask import current_app def eitems_resolver(document_pid): """Search and return the EItems that reference this Document.""" eitems = [] eitem_search = current_app_ils.eitem_search_cls() ...
31,398
def getStations(options, type): """Query stations by specific type ('GHCND', 'ASOS', 'COOP', 'USAF-WBAN') """ conn = sqlite3.connect(options.database) c = conn.cursor() if type == "ALL": c.execute("select rowid, id, name, lat, lon from stations") else: c.execute("select rowid, id...
31,399