content
stringlengths
22
815k
id
int64
0
4.91M
def bingimage(text, bot): """<query> - returns the first bing image search result for <query>""" api_key = bot.config.get("api_keys", {}).get("bing_azure") # handle NSFW show_nsfw = text.endswith(" nsfw") # remove "nsfw" from the input string after checking for it if show_nsfw: text = ...
77,000
def insert_package_path(): """This init_path.py should be placed at `${PROJECT_DIR}/package/utils/init_path.py`. Here we add `${PROJECT_DIR}/package` to `sys.path`. If you want to move this file to other places, remember to change the following path to insert. """ sys.path.insert(0, ospdn(ospdn(ospd...
77,001
def convert_to_axes(axes, container=tuple): """Convert `obs` to the list of obs, also if it is a :py:class:`~ZfitSpace`. Return None if axes is None. Raises TypeError: if the axes are not int """ if axes is None: return axes axes = convert_to_container(value=axes, container=cont...
77,002
def aumentar(n=0, p=0, formato=False): """ Somar porcentagem :param n: número a ser somado :param p: porcentagem a ser somada :param formato: (opicional) mostrar o moeda :return: resultado """ n = float(n) resultado = n + (n * p / 100) return moeda(resultado) if formato else resu...
77,003
def calculate_threshold_value(q: int, t: int, p: int, lmbda: int, w: float, lower_val: float, upper_val: float, ...
77,004
def _parse_gtf_group(rows): """ This is a helper function for parsing GTF attributes from a data frame. It is not intended for external use. """ import pandas as pd import pbio.misc.parallel as parallel res = parallel.apply_df_simple(rows, parse_gtf_attributes) res = pd.DataFrame(res) ...
77,005
def z_levels(fid, x, y, variable, n_levels, n_frames, t_idx, symflag, n_lev_auto, n_dec, n_seg, avleng): """ list(float) = zlevels(fid, variable, n_levels, n_frames, t_idx, symflag, n_lev_auto, n_dec, n_seg, avleng) """ z_levs_auto = auto_z_levels(fid, x, y, variab...
77,006
def getint( string: Union[io.StringIO, str], key: str, section: Optional[str] = None ) -> Union[int, None]: """get option's value in `int` type""" val = get(string, key, section) if val: return int(val)
77,007
def notify(summary, body='', app_name='', app_icon='', timeout=3000, actions=[], hints=[], replaces_id=0): """Send a system notification""" _bus_name = 'org.freedesktop.Notifications' _object_path = '/org/freedesktop/Notifications' _interface_name = _bus_name session_bus = dbus.SessionBu...
77,008
def add_grid_frame( grid: np.ndarray, generation: int, grid_frames: List[np.ndarray], pixels_per_cell: int, ) -> None: """Add the grid to the grid_frames""" arr_grid = enlarge_image(grid * 255, pixels_per_cell) image = Image.fromarray(arr_grid, mode="L").convert("P") grid_frames.append(...
77,009
def train(data_path, entity_path, relation_path, entity_dict, relation_dict, neg_batch_size, batch_size, shuffle, num_workers, nb_epochs, embedding_dim, hidden_dim, relation_dim, gpu, use_cuda,patience, freeze, validate_every, num_hops, lr, entdrop, reldrop, scoredrop, l3_reg, model_name, decay, ls, w_matrix, bn_list, ...
77,010
def fec_old_patch(): """ Further Education College UK RSF patch generated with the old `rsfcreate.py` script. """ with open("tests/fixtures/fec_old_patch.rsf") as handle: return handle.read().splitlines()
77,011
def get_n_pixels(bad_bin_mask, window=10, ignore_diags=2): """ Calculate the number of "good" pixels in a diamond at each bin. """ N = len(bad_bin_mask) n_pixels = np.zeros(N) loc_bad_bin_mask = np.zeros(N, dtype=bool) for i_shift in range(0, window): for j_shift in range(0, window)...
77,012
def argparser(): """parse command line arguments""" parser = argparse.ArgumentParser(prog='impsamp') parser.description = 'MT decoding by importance sampler' parser.formatter_class = argparse.ArgumentDefaultsHelpFormatter parser.add_argument("proxy", type=str, ...
77,013
def generate_test_data(vocab_ids, writer_lm_all, writer_seq_ae_all): """Generates test data.""" # Construct test data writers writer_lm = build_shuffling_tf_record_writer(data.TEST_LM) writer_rev_lm = build_shuffling_tf_record_writer(data.TEST_REV_LM) writer_seq_ae = build_shuffling_tf_record_writer(data.TEST...
77,014
def ruleset_refresh(p_engine, p_username, rulesetname, envname): """ Refresh ruleset on the Masking engine param1: p_engine: engine name from configuration param2: rulesetname: ruleset name param3: envname: environment name return 0 if added, non 0 for error """ return ruleset_worker(p_...
77,015
def str_or_raise(value: Any) -> str: """Return string or raise exception.""" return enforce_type(str_or_none(value), str)
77,016
def trima(close, timeperiod=30): """Triangular Moving Average 三角移动平均线 the triangular moving average (TMA) is a technical indicator that is similar to other moving averages. The TMA shows the average (or mean) price of an asset over a specified number of data points—usually a number of price bars. H...
77,017
def CheckCardinalities(*cardinality): """Checks cardinality values for compatibility. None is treated as a wild card that matches all cardinalities. It returns the resulting cardinality, or None if all are wild cards. If they don't match then a ProcessingError is raised.""" cReturn = None for...
77,018
def build_ground_altitudes(ground_altitudes, espa_metadata): """Build list of ground altitudes based on the standard ground altitudes and the scene. Also, write these altitudes to a file for later use Args: ground_altitudes <file>: List of altitudes to process espa_metadata <espa.metad...
77,019
async def index_route(request): """ Redirect to the dashboard. """ return response.redirect('/jobs')
77,020
def make_format_plugin_table(group="waveform", method="read", numspaces=4, unindent_first_line=True): """ Returns a markdown formatted table with read waveform plugins to insert in docstrings. >>> table = make_format_plugin_table("event", "write", 4, True) >>> print(tab...
77,021
def create_gsheet(gc, eid, program_db): """ Creates a Google sheet for the program. :param gc: The `gspread.Client` object. Should have called `gc = authorize_google_sheets()` before passing into this function. :type gc: `gspread.Client` object :param eid: The eid of the program. :type...
77,022
def learning_cuve(training, validation, name='Metric'): """ training : list List of training metrics. validation : list List of validation metrics. """ plt.plot(training, label='train', color='C0', linestyle='-') plt.plot(validation, label='test', color='C0', linestyle=':') ...
77,023
def nexus(host, db, user, password, table, book, perc, filename): """ Connect to the mysql db and loop through what we find """ db = MySQLdb.connect(host=host, user=user, passwd=password, db=db, charset='utf8') cur = db.cursor() if book: cur.execute("SELECT id FROM {}_ed_vus WHERE BOOK=...
77,024
def solve(a: numpy.ndarray, b: List[float]): """ usage.statsmodels: 1 """ ...
77,025
def categorical_numericarray( draw ) -> Categorical: """Strategy for creating NumericArray-mode Categoricals.""" raise NotImplementedError()
77,026
def probability_of_selection(spt, snr): """ probablity of selection for a given snr and spt """ ref_df=SELECTION_FUNCTION.dropna() #self.data['spt']=self.data.spt.apply(splat.typeToNum) interpoints=np.array([ref_df.spt.values, ref_df.logsnr.values]).T return griddata(interpoints, ref_df.tot_...
77,027
def generate_bert_sentiment_database(company_name, client_address): """ Calculate the bert sentiment scores and put them into the database. :param company_name: the name of the company. Used as the entry in the database. :param client_address: the address of the database. """ client = MongoClie...
77,028
def set_timeline_upper_limit(filter_json: JsonDict, filter_timeline_limit: int) -> None: """ Enforces a maximum limit of a timeline query. Params: filter_json: The timeline query to modify. filter_timeline_limit: The maximum limit to allow, passing -1 will disable enforcing a ma...
77,029
def entryPoint(coursesCompleted, coursesDesired, startSem): """ This is the entry point function for the ILP scheduler. coursesCompleted: a list of courses that the person already has credits for coursesDesired: a list of courses that the person wants to take. startSem: either 0 or 1 indicating wet...
77,030
def render(template, context=None, **kwargs): """ Return the given template string rendered using the given context. """ renderer = Renderer() return renderer.render(template, context, **kwargs)
77,031
def deserialize_graph(data): """De-serialize from the given json data.""" graph = import_class(data['module'], data['cls'])() graph._nodes = [] for node in data['nodes']: graph._nodes.append(deserialize_node(node)) nodes = {n.identifier: n for n in graph.nodes} for node in data['nodes']:...
77,032
def normalCdf(x,mu=0.0,sigma=1.0): """ Computation of normal cdf @ In, x, list or np.array, x values @ In, mu, float, optional, mean @ In, sigma, float, optional, sigma @ Out, cdfReturn, list or np.array, cdf """ return stats.norm.cdf(x,mu,sigma)
77,033
def setup(bot: ModmailBot) -> None: """Load the Extension Manager cog.""" bot.add_cog(ExtensionManager(bot))
77,034
def transform(codec): """ transform post """ if codec not in CODECS: return abort(404) return run(codec, request.get_data())
77,035
def test_parsers_ex1(): """ Execute textfsm.py: $ textfsm.py exercise1.tpl ex1_show_int_status.txt """ cmd_list = ["textfsm.py", "exercise1.tpl", "ex1_show_int_status.txt"] script_dir = "../day3/parsers/solutions/" std_out, std_err, return_code = subprocess_runner(cmd_list, script_dir) ...
77,036
def largest_connected_component(H): """ A function to find the largest connected component of a hypergraph. Parameters ---------- H: Hypergraph object The hypergraph of interest Returns ------- set The largest connected component (a set of nodes) of the hypergraph. ...
77,037
def setup_args(args): """ Setup the args Args: args (ArgParse): args parsed by arg parser Returns: args (CoreclrArguments) """ coreclr_args = CoreclrArguments(args, require_built_core_root=False, require_built_product_dir=False, require_built_te...
77,038
def log_str(proc_str, start): """Create a preamble string for stdout.""" former = "[{:>4}".format(proc_str) latter = "] {:.2f}".format(round(time.time() - start, 3)) return former + latter
77,039
def authenticate_user_from_request(request): """ Given a request, attempt to authenticate based on Auth Header Scheme/Credentials Called via the middleware, etc """ # Step 1: Detect if we have an Auth Header raw_auth_header_val = request.headers.get('Authorization', None) if not raw_auth_he...
77,040
def test_creature_fight(): """ Tests the situation when a fight happend bewteen two creatures. """ my_creature_1 = ertai.Creature( title="Selfless Savior", cost=ertai.Mana("White"), power=1, toughness=1, ) my_creature_2 = ertai.Creature( title="Usher of t...
77,041
def linear_kernel(X, Y=None): """Compute linear Gram matrix between X and Y (or X) Parameters ---------- X: torch.Tensor of shape (n_samples_1, n_features) First input on which Gram matrix is computed Y: torch.Tensor of shape (n_samples_2, n_features), default None Second input on whic...
77,042
async def test_cancel_event(): """Ensure exception is thrown when cancel event is received.""" iterable = AsyncIterWrapper([b'event:cancel\n']) with pytest.raises(aiofirebase.StreamCancelled): await aiofirebase.FirebaseHTTP._iterate_over_stream(iterable=iterable, callback=None)
77,043
async def test_reset_unloads_entry_if_setup(hass): """Test calling reset while the entry has been setup.""" entry = Mock() entry.data = {"host": "1.2.3.4", "username": "mock-username"} entry.options = {CONF_ALLOW_HUE_GROUPS: False, CONF_ALLOW_UNREACHABLE: False} hue_bridge = bridge.HueBridge(hass, e...
77,044
def split_to_pieces(number, name, lang, doc_path): """ :param number: id number of document :param name: file name :param lang: language one of ENG, RUS, ESP, JAP, etc. :param doc_path: document path :return: pieces ids :structure: list(ObjectId Bson) """ if len(doc...
77,045
def hit(health): """Hits health for a random number between 1 and 10""" hit_value = random.randint(1, 10) print "hits for:", hit_value health = health - hit_value print "health now:", health return health
77,046
def parallel_func(func, n_jobs): """Return parallel instance with delayed function Util function to use joblib only if available Parameters ---------- func: callable A function n_jobs: int Number of jobs to run in parallel Returns ------- parallel: instance of jobl...
77,047
def evaluate_task_accuracy(scenario, prediction_results, subclasses, null_label=NULL_LABEL): """ Evaluates the accuracy of the predictor for each task, where we consider the best possible performance as the ground truth. The best possible is the perfect labeling for current iteration. :param scenario: ...
77,048
def _graycode(bqm): """Get a numpy array containing all possible samples in a gray-code order""" # developer note: there are better/faster ways to do this, but because # we're limited in performance by the energy calculation, this is probably # more readable and easier. n = len(bqm.variables) ns...
77,049
def get_indices_of_line(l, angle, dist): """ Return indices in square matrix of <l>x<l> for Hough line defined by <angle> and <dist> """ # Get start and end points of line to traverse from angle and dist x0, y0, x1, y1 = get_extremes(angle, dist, l) # To ensure no lines are defined outside th...
77,050
def get_oaa_connection(agent): """return the LibOaa OAA connection for the specified agent, or None if none exists""" if _AGENT_OAA.has_key(agent): return _AGENT_OAA[agent] return None
77,051
def diaresnet18(**kwargs): """ DIA-ResNet-18 model 'DIANet: Dense-and-Implicit Attention Network,' https://arxiv.org/abs/1905.10671. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.chainer/models' ...
77,052
def _release_ips(ips): """ Release the given IPs using the data store. :param ips: Set of IPAddress objects to release. :return: None """ # release_ips returns a set of addresses that were already not allocated # when this function was called. But, Mesos doesn't consume that # informat...
77,053
def mc_indices(context_vector, fns, mc = 50): """Return the indices of the @mc highest values of context_vector. @fns is just for reference. Not really optimized. """ # If the context vector has more nonzero elements than mc, only take the mc occurrences! if len(np.flatnonzero(context_vector)) > mc...
77,054
def split_date(dates): """ Split datetime64 dates into year, month, day components. """ y = dates.astype("<M8[Y]").astype(int) + 1970 m = dates.astype("<M8[M]").astype(int) % 12 + 1 d = (dates - dates.astype("<M8[M]")).astype("<m8[D]").astype(int) + 1 return y, m, d
77,055
def random_random_crop(image: tf.Tensor, size: tf.Tensor, groundtruths: Dict[str, tf.Tensor], seed=None) -> (tf.Tensor, tf.Tensor): """Will `randomly` perform a random crop of a tensor to a given size. Slices a shape `size` portion out of `val...
77,056
def flowless(hyper_list, T, weight=None): """ Implementation of greedy++ algorithm proposed in [1]. It efficiently compute almost densest subgraph without max flow. Parameters ---------- G: undirected, graph (networkx). T: int, number of iterations. weight: str that specify the edge att...
77,057
def format_counts(d, nocolor=False, keys_fg='cyan', vals_fg='white'): """Format & colorize the inspection results.""" padding = len(max(d.keys(), key=len)) fmt_keys = [i.ljust(padding) for i in d.keys()] fmt_vals = [str(i) for i in d.values()] if not nocolor: fmt_keys = [click.style(i, fg=ke...
77,058
def getDmzProxySecurityActionValue( nodename, proxyname, action, ): """Gets an individual security value""" return getDmzProxySecurityActionLevelOrValue( nodename, proxyname, action, 'values' )
77,059
def get_left_right_spans(ribo): """ In counting number of reads going to each region (UTR5, CDS and UTR3), We artificially introduce two regions UTR5_junction: A region between UTR5 and CDS containing the start site [start_site - left_span, start_site + leftspan] UTR3_junction: ...
77,060
def filters_effect( ftype=None, cutoff_hz=None, sfreq=None, width_hz=None, ripple_db=None, window=None, ): """ Generate example filter input-output plots for pure sinewave data. Parameters ---------- key=val see :ref:`check_filter params() Parameters <filter_parameters_label>` R...
77,061
def _aggregate(y, aggfunc, weights): """Apply aggregation function by row. Parameters ---------- y : pd.DataFrame Multivariate series to transform. aggfunc : str Aggregation function used for transformation. weights : list of floats Weights to apply in aggregation. ...
77,062
def main(): """This script reads an XML file in MARC slim format and generates statistics about used fields.""" parser = OptionParser(usage="usage: %prog [options]") parser.add_option('-i', '--input-file', action='store', help='The input file containing MARC slim XML records') parser.add_option('-p', '--patter...
77,063
def iterate_run_calcdist(listoffiletuples, pdbpath, outpath): """ Iteratively runs calculate_distance.py over pairs of files. Parameters ---------- listofffiletuples: list pdbpath: pathlib.PosixPath outpath: pathlib.PosixPath """ counter=1 for filetuple in listoffiletuples: ...
77,064
def encryption(lockdown: LockdownClient, backup_directory, mode, password): """ Set backup encryption on / off. When on, PASSWORD will be the new backup password. When off, PASSWORD is the current backup password. """ will_encrypt = lockdown.get_value('com.apple.mobile.backup', 'WillEncrypt') ...
77,065
def replace_classifier(arch, model, dataset, fine_tune=False): """ Replace the final classifier based on the dataset.""" # TODO: pass arch? if dataset == "imagenet": return # https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html num_classes = get_num_classes(dat...
77,066
def test_classmethod(): """methodtype arg of MethodType.cls returns MakeMethod.mkclsmethod""" expected = core.RunMethodType(core.MethodType.cls, core.MakeMethod.mkclsmethod) assert core.create_method(core.MethodType.cls) == expected
77,067
def test_p_qq_errors_probabilities_greater_than_one(): """ Testing for errors with probatilities greater than one. """ try: err_str = {"p_value": [0.5,.3,-.02]} p_qq((err_str), 0, 0.01) except(TypeError): assert True else: assert False
77,068
def create_session(engine): """ Create a session for accessing the DB. """ return sqla.orm.scoped_session( sqla.orm.sessionmaker( autocommit=False, autoflush=False, bind=engine ) )
77,069
def firm_sim_load_firms(NAICS2012_to_NAICS2007): """ For now, just read FirmsandEstablishments.cvs file created by dev/NFM_Firmsynthesis.R """ data_dir = setting('data_dir', inject.get_injectable('data_dir')) table_list_name = 'firm_synthesis_tables' table_list = setting(table_list_name) a...
77,070
def request(caller_id): """ Method requests single PublicIP address for caller. If caller's quota is exceeded, exception is raised. Otherwise caller obtains a new PublicIP address. @cmview_user @response{string} newly obtained PublicIP's address @raises{public_lease_not_found,CMException} ...
77,071
def get_user_tweets(user_name): """Retrieve all (accessible) tweets from a given user name by stepping backward through the status paging""" all_tweets, lowest_id = _get_user_tweets_batch(user_name) while True: next_batch, lowest_id = _get_user_tweets_batch(user_name, lowest_id) all_tweets +...
77,072
def hex_to_chars(num): """ Convert the hex representation of the number to a correctly ordered string. Parameters ---------- val: int The integer representing the string. This is in reverse order. Ie. XXYYZZ -> chr(ZZ)chr(YY)chr(XX) Returns ------- str The actua...
77,073
def Split(l, indexes, axis=-1, merge_sublayers=False, name=""): """\ Split layer into a list of tensor layers. :param l: parent layer :param indexes: ``[20, 60] => [:20, 20:60, 60:]`` :param axis: which axis to split on (-1 = last) :merge_sublayers: merge layers symbolically (affects plotting)...
77,074
def load(filename): """ Load a compressed pickle from disk """ return pickle.loads(_loads(filename))
77,075
def hilbert(x, N=None, axis=-1): """ Compute the analytic signal, using the Hilbert transform. The transformation is done along the last axis by default. Parameters ---------- x : array_like Signal data. Must be real. N : int, optional Number of Fourier components. Default:...
77,076
async def peer_detail(request): """ --- description: Show current peers, if {level} is set, include logs for {id} tags: - peers produces: - application/json parameters: - in: path name: peer_id description: peer id required: true type: string responses: ...
77,077
def attachCurve(q=1,e=1,bb="float",bki=1,cch=1,kmk=1,m="int",nds="int",p="float",rv1=1,rv2=1,ch=1,n="string",o=1,rpo=1): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/attachCurve.html ----------------------------------------- attachCurve is undoable, queryable, and editable. Thi...
77,078
def interruptable_task(coro, loop=None): """ Turn the given coroutine into an interruptable task by turning it into an InterruptableFuture and returning it. :param coro: the coroutine that should be made interruptable :param loop: the event loop in which to run the coroutine, by default uses tornado.io...
77,079
def STALTA_picker_refraction(st, nsta=1e-3, nlta=4e-2, fc=50, nc=2, noise_mag=1e-25, SNR_window=5e-3): """The STA/LTA picker provides a first order good estimate of the arrival times for both the P- and S- wave. The STA/LTA picker uses :py:class:`obspy.signal.trigger.recursive_sta_lta`. :param st: ...
77,080
def _validate_fastparquet(): """ Raise an informative error message if fastparquet is not installed """ if fp is None: raise ImportError("""\ The datashader.spatial module requires the fastparquet package""")
77,081
def Roleta(): """Faz a parte da roleta. possibilidades: 100 a 950, de 50 em 50. dois 1000; duas 'passa a vez'; duas 'perdeu tudo', os resultados são equiprováveis; perdeu tudo == 0 passa a vez == 1 none -> int""" possibilidades = [0, 0, 1, 1, 1000, 1000] for i in range(100, 951, 50): # Ad...
77,082
def parse_trace_collection_time_range(collection, time_range, gmt=False, handles=None): """Parse a time range string, using a trace collection to disambiguate incomplete dates. Args: collection (TraceCollection): a babeltrace TraceCollection instance. ...
77,083
def lgr_validate_label(lgr, label, udata): """ Validate a label for an LGR. :param lgr: The LGR to use for variant generation. :param label: Label to validate. :param udata: The associated Unicode database. :return: CSV containing the label validation output. """ return _validate_label_...
77,084
def encodeDNA(seq_vec, maxlen=None, seq_align="start"): """Convert the DNA sequence into 1-hot-encoding numpy array # Arguments seq_vec: list of chars List of sequences that can have different lengths maxlen: int or None, Should we trim (subset) the resulting sequence. ...
77,085
def sortedWrite(inTree): """ Write out a GLM from a tree, and order all tree objects by their key. Sometimes Gridlab breaks if you rearrange a GLM. """ sortedKeys = sorted(list(inTree.keys()), key=int) output = '' try: for key in sortedKeys: output += _dictToString(inTr...
77,086
def seed_db(): """Seeds the database.""" db = get_db() add_game({ 'game_title': 'Caverna: The Cave Farmers', 'game_url': 'https://boardgamegeek.com/boardgame/102794/caverna-cave-farmers', 'play_time_min': 30, 'play_time_max': 210, 'players_min': 1, 'players_ma...
77,087
def callback(): """ 修改记录 """ # 检查用户权限 _common_logic.check_user_power() content = web_helper.get_form('content', '内容', is_check_special_char=False) # 防sql注入攻击处理 content = string_helper.filter_str(content, "'") # 防xss攻击处理 content = string_helper.clear_xss(content) fields = { ...
77,088
def get_stripped_contextual_model(path: pathlib.Path = None, aliases_not_to_be_stripped: List[str] = None) -> Tuple[Type[OscalBaseModel], str]: """ Get the stripped contextual model class and alias based on the contextual path. This function relies on the directory structu...
77,089
def test_start_run( run_and_check_cli: RunAndCheckCLICallable, modified_config: submanager.models.config.ConfigPaths, command: str, cli_args_run: list[str], cli_args_start: list[str], check_text: str, check_error: type[BaseException] | None, ) -> None: """Test that the test configs valid...
77,090
def eval_policy(eval_positions): """Evaluate all positions with all models save the policy heatmaps as CSVs CSV name is "heatmap-<position_name>-<model-index>.csv" CSV format is: model number, value network output, policy network outputs position_name is taken from the SGF file Policy network outp...
77,091
def init_process(rpc_config, mp_contexts): """Work loop in the worker""" try: _init_rpc(*rpc_config) keep_polling = True data_queue, task_queue, barrier = mp_contexts collate_fn_dict = {} while keep_polling: try: # Follow https://github.com/py...
77,092
def create_geotiff(pixels, gps_bounds, out_path, nodata=-99, asfloat=False, extractor_info=None, system_md=None, extra_metadata=None, compress=True): """Generate output GeoTIFF file given a numpy pixel array and GPS boundary. Keyword arguments: pixels -- numpy array of pixel value...
77,093
def validate_cypher(statement, raise_exception=False, exc_class=ValidationError): """ Checks if ``statement`` is a valid Cypher statement. :param statement: Cypher statement to parse. :type statement: str :param raise_exception: Raise ValidationError if not valid. :type raise_exception: boo...
77,094
def test_merge_compute(left_dict, right_dict, expected): """ Given left and right dict should be merged as expected. """ assert expected == merge_compute(left_dict, right_dict)
77,095
def strip_newlines(base): """Strip newlines from a string""" return base.replace("\n", "")
77,096
def fixture_log_output(): """Capture structlog log output for testing. Reference: https://www.structlog.org/en/stable/testing.html """ return structlog.testing.LogCapture()
77,097
def reduced_canonical_form(G): """ """ pass
77,098
def calculate_g(lat): """calculate the gravitational acceleration with lat in degrees""" import numpy as np g0 = 9.780325 nom = 1.0 + 0.00193185 * np.sin(np.deg2rad(lat)) ** 2.0 denom = 1.0 - 0.00669435 * np.sin(np.deg2rad(lat)) ** 2.0 g = g0 * (nom / denom)**0.5 return g
77,099