content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def invert0(x): """ Invert 0 -> 1 if OK = 0, FALSE > 1 """ return 0 if x > 0 else 1
1c7a71885cdc84f12b3e2214aa74f99ff2aab326
3,608,800
def _calc_proj_cnrs(imgs, ncore, nlist, method, medfilt2_kernel_size, medfilt_kernel_size, ): """ Private function calculate slit corners concurrently Parameters ---------- imgs :...
a3d6addcd4bab497820b771e2a3de39d083199d7
3,608,801
from tokenize_rt import ( src_to_tokens, tokens_to_src, reversed_enumerate, ) from typing import Tuple def remove_trailing_semicolon(src: str) -> Tuple[str, bool]: """Remove trailing semicolon from Jupyter notebook cell. For example, fig, ax = plt.subplots() ax.plot(x...
0c566a446d3097ebf2ae94549d5788002b067fb8
3,608,802
from datetime import datetime def calc_duration_rel(wl_obj, end_time, start_time): """ Determines a duration based on two times. Arguments: - wl_obj -- the work log object. - end_time -- the ending time. - start_time -- the starting time. Returns: a timedelta obj...
be87c4b66b4bfe9056da306b1cad6caf4b04616c
3,608,803
def setup_EC(w_EC, c, V, b, U, rho_e, dx, ds, normal, dirichlet_bcs, neumann_bcs, boundary_to_mark, c_1, u_1, K_, veps_, phi_, solutes, per_tau, z, dbeta, enable_NS, enable_PF, use_iterative_solvers, q_rhs): """ ...
0df40d4942ba5c4387b66cc884b68f7868b2fb71
3,608,804
def list_get_comments_g(amid: int, order: str = "time", verify: utils.Verify = None): """ 获取评论 :param amid: 歌单ID :param order: :param verify: :return: """ replies = common.get_comments(amid, "audio_list", order, verify) return replies
28f31c934ed4bb1bbef644456b69d737b27ee2c6
3,608,805
import torch def bounded_iou_loss(loc1, size1, loc2, size_): """ loc1/2:[(l,t),...] size1/2:[(w,h),...] 2 |= target :return 0 if same, >0 if diff SINGLE_IMAGE """ loc_delta = torch.abs(loc1 - loc2) iou_loc = torch.div(size_ - loc_delta, size_ + loc_delta) iou_size = torch.min(t...
67964833f5a190065b843f1c89c1eccd16824245
3,608,806
def show_user_keys(username): """ Client's personal page GET: Displays the client page html. Displays download button and generates hash if keys haven't been downloaded for this user """ downloaded = hl.checkDistributeFlag(username) #Prevent Replay Attacks by downloading keys hash ...
d5aecb2794dbf4e69cb0a1b4182d9137413394b5
3,608,807
def one_or_more(amount, single_str, multiple_str): """ Return a string which uses either the single or the multiple form. @param amount the amount to be displayed @param single_str the string for a single element @param multiple_str the string for multiple elements @return the string represent...
8c3495614cd8c718e243383bcc72cc7daa8fa286
3,608,808
def get_sql_debug(): """ :rtype: bool """ result = getattr(state, 'sql_debug', None) if result is not None: return result return getattr(settings, 'SQL_DEBUG', False)
b6f133adb6b1e2b60bc27a701de5b0675035abdc
3,608,809
def auroc(labels=None,predictions=None,tp=None,fp=None): """auroc - calculate area under the curve from a given fp/rp plot""" if labels is not None: [fp, tp] = roc(labels,predictions) n = tp.size auc = 0.5*((fp[1:n]-fp[0:n-1]) * (tp[1:n]+tp[0:n-1])).sum() return auc pass
1ed616ec6455d0159bdd51321f23ef972f21d63b
3,608,810
def det_ZZ(n=200, min=1, max=100, system='sage'): """ Dense integer determinant over ZZ. Given an n x n matrix A over ZZ with random entries between min and max, inclusive, compute det(A). INPUT: - ``n`` - matrix dimension (default: ``200``) - ``min`` - minimal value for entries of matrix ...
7d8c74853a5b49323aee2ce0a66b7a72b1433a3d
3,608,811
def particle_class_instance(flavor, particle_config): """ Return a particle class from a flavor or handle CLI error message """ particle_class = particle_class_from_flavor(str(flavor).strip()) if particle_class is None: fail( "Error: {} is not a supported Particle or Quasiparticle flavor...
3bbb7a7ca358f5b38b3488943382b88be8de4d0a
3,608,812
def create_being(): """ Creating a new entry of type being """ form = EntryBeing() form.category_id.choices = [(i.id, i.name) for i in Category.query.all()] if form.validate_on_submit(): being = Being(name=form.name.data, meaning=form.meaning.data, ...
e55b8d0b0b0442412cd05d576031d05ff714dd52
3,608,813
import torch def accuracy(output, target, topk=(1,), exact=False): """ Computes the top-k accuracy for the specified values of k Args: output (ch.tensor) : model output (N, classes) or (N, attributes) for sigmoid/multitask binary classification target (ch.t...
cc2194bb72460ff39e3648e173d52875f64abeab
3,608,814
def liqwater_h(T, To=0): """Calculates the specific enthalpy [J/kg] of liquid water at atmospheric pressure, for a given temperature ( Celsius). Notes: This is calculated via the specific heat capacity of water at Patm, for a specified reference temp (O C by defualt). Some sources report slightly diffe...
172b54d687fe2ea02696b68477fc092af64bc312
3,608,815
import itertools def enumerate_hyperparameter_combinations(parameter_to_options): """ Returns a list of dictionaries of all hyperparameter options :param parameter_to_options: a dictionary that maps parameter name to a list of possible values :return: a list of dictionaries that map parameter names ...
8665ef66b7cb1467599ff0a56f47ac60042e0e9a
3,608,816
def get_ts_guess_function_and_params(reaction, bond_rearr): """Get the functions (1dscan or 2dscan) and parameters required for the function for a TS scan Arguments: reaction (autode.reaction.Reaction): bond_rearr (autode.bond_rearrangement.BondRearrangement): Returns: (list): ...
39a0e45748d87dd481db5737d8654216c424908e
3,608,817
from typing import List from datetime import datetime from operator import add def water_licences_summary(licences: List[Feature], polygon: Polygon) -> LicenceDetails: """ takes a list of licences and the search polygon, and returns a summary of the licences that fall within the search area. """ ...
5d86ffe3da3bb940e27467ea8ee6cc5b511b703b
3,608,818
import os def extract_line_information(line_information: str) -> LineInfo: """ Lines from sphinx log files look like this /warnings/index.rst:22: WARNING: Problems with "include" directive path: InputError: [Errno 2] No such file or directory: 'I_DONT_EXIST'. """ file_and_line = line_i...
d05665e9cb1c53f61df0b5dea9fcf30b203de980
3,608,819
def get_new_pvars(opvs, epvs): """Returns a list of new projection variables from a list of old PVar's opvs, based on a list of existing PVar's epvs. Args: opvs: Old projection variables. evps: Existing projection variables. Returns: A list of projection variables. """ ...
b344e4fb60daa0452c944065b3164d90e7698a21
3,608,820
def check_all_types(src_dict, sinks, sourceField): # type: (Dict[Text, Any], List[Dict[Text, Any]], Text) -> Dict[Text, List[SrcSink]] # sourceField is either "soure" or "outputSource" """Given a list of sinks, check if their types match with the types of their sources. """ validation = {"warning":...
99d8b7e1a8ed7818aa3c46bd85799f466cb8837a
3,608,821
import requests def get_metadata(path): """ Get metadata relative to metadata/computeMetadata/v1/instance/ """ URL = 'http://metadata.google.internal/computeMetadata/v1/instance/' HEADERS = {'Metadata-Flavor': 'Google'} full_path = URL + path try: resp = requests.get(full_path, headers=HEA...
f4bb27434327745efa3340e11865513e1fbf9290
3,608,822
def count_gaps(sequence): """In order to calculate the correct percent divergence between two strings where there are gaps present, the gaps need to be counted in order to be deducted from the total number of differences. This function takes a sequence string and returns the number of instanc...
a0124ef8ee77d5b1c39da96131a9a0dff7301bcc
3,608,823
def get_year_graph(cardinal: GraphFst) -> 'pynini.FstLike': """ Returns year verbalizations as fst < 2000 neunzehn (hundert) (vier und zwanzig), >= 2000 regular cardinal **00 ** hundert Args: delete_leading_zero: removed leading zero cardinal: cardinal GraphFst """ year_g...
b50f61b1b51934cad41e5fdb35efe973d41e528c
3,608,824
def sql_update_pd(sql, table_1=None, table_2=None, func1=None, func2=None, func3=None): """主函数""" # 第一步,判断SQL是否正确 table_1_cols = table_1.columns.tolist() table_2_cols = table_2.columns.tolist() if isinstance(table_2, pd.DataFrame) else [] judge_format(sql, table_1_cols, table_2_cols) # 第二步,解析SQL...
cc7392237ef90ce5bfd009907571d8f97d3c8cae
3,608,825
def getReAuthors(articleurl): """获取相关学者""" # 本篇文章的作者 res = [] authors = getAus(articleurl) for author in authors: co = getACo(author.url) # 同机构的学者 res.extend(co) return res[0:20]
68a260672c2bbb474559de46e2c715719798667f
3,608,826
import functools def route(route=None, **kw): """ Decorator marking the decorated method as being a handler for requests. The method must be part of a subclass of ``Controller``. :param route: string or array. The route part that will determine which http requests will match the dec...
ac26a919bfd2639a845e829219367470366ee3a1
3,608,827
def multiprocess_tokenize_tweet(documents): """ Args: documents (list): this is a list of the documents to be tweet tokenized Returns: tokenized_tweets (list): a list of tokenized tweets done with multiprocessing """ n_processes = mp.cpu_count() p = mp.Pool(n_processes) ...
c3c669f0fb5146cce88a72d641a382fa925a2857
3,608,828
def _node_description(op: saldag.OpNode, kind: str, inner): """ Returns description of node properties. """ if inner: return "{{ {{ <I>{}</I> | <B>{}</B> }} | {} | {} }}".format( op.out_rel.name, kind, inner, _column_list(op)) else: ...
2e1bee71865f24e0d48917f8e6c623b1135ae381
3,608,829
import ctypes def _is_little_endian(obj: ctypes.Structure) -> bool: """ Checks whether a Structure instance/class is little endian :param obj: Structure instance/class :return: True if little endian """ is_swapped = hasattr(obj, _CTYPES_SWAPPED_ATTR) if _SYS_ENDIANNESS_IS_LITTLE: ...
4dde9bedc4847f4e1bb38670a5b5b691975b6527
3,608,830
import bokeh import packaging import importlib def get_plotting_function(plot_name, plot_module, backend): """Return plotting function for correct backend.""" _backend = { "mpl": "matplotlib", "bokeh": "bokeh", "matplotlib": "matplotlib", } if backend is None: backend ...
d6a43dcc81a2013312fab0aa534d3bd5cc4f3aca
3,608,831
def get_mean_next_generation_matrix_from_simulation(N,counters): """ Compute the mean next generation matrix from a simulation result. Parameters ========== N : int Number of species/states counters : list of tuple of (int, :class:`collections.Counter`) Each entry of this li...
a69fcb203d92875414a379c79703670764e19957
3,608,832
def detect_seq(x, value=0, min_seq=1, show=False, ax=None): """Detect initial and final indices of sequential data identical to value. Detects initial and final indices of sequential data identical to parameter value (default = 0) in a 1D numpy array_like. Use parameter min_seq to set the minimum numbe...
a6fc354d5d7fcff06b6715ea8adf19e07837d74e
3,608,833
from typing import List from typing import Optional def _expand_param_units(param: BaseDescriptor) -> List[Optional[str]]: """ Get expanded param units :param param: The param to get units for :return: A list of the units (or None if no unit) """ unit = getattr(param, 'unit', None) expand...
e9b610063d28427af5ec29e7734da9fb5784ebf8
3,608,834
def get_dissimilarity_matrix(sequences, function): """ Computes a dissimilarity matrix using a given function. This function can be a measure of dissimilarity, distance, or any other measurement between two sequences. The column names and index on the matrix are the indexes of each sequences in the collection. E...
37aa422cbca03f5d94084c3ae6c0e7b92e09f921
3,608,835
def request_project_by_key(cfg, project_key): """Request project data by jira project key""" url = cjm.request.make_cj_url(cfg, "project", project_key) response = cjm.request.make_cj_request(cfg, url) return response.json()
693a73c29aab1ec5deaa2c6859e29fcdf2b19eda
3,608,836
def _minimum( *, value, schema: dict, uri: str, validation: Validation, ref_list: RefList ) -> Callback: """ minimum https://json-schema.org/draft-06/json-schema-validation.html#rfc.section.6.4 https://json-schema.org/draft-07/json-schema-validation.html#rfc.section.6.2.4 """ return lambda ...
b1d7a838a7e045472957e3b50b72f8c2937e803f
3,608,837
from typing import Union def euclidean_distance(p1: Union[Vector, np.array], p2: Union[Vector, np.array]) -> float: """Euclidean distance between two 3D points. Support {Vector} and {np.array} as data types. Arguments: p1 {Union[Vector, np.array]} -- first 3D point p2 {Union[Vector, np.array]...
4ebad943fbb46f34ffbceb43a7b8ec90c8340f6f
3,608,838
def suffix(pattern, k): """we define SUFFIX(Pattern) as the last (k-1)-mers in a k-mer Pattern""" return pattern[-(k - 1):]
d6cec61ba024f551071a6ba9d6409963ff2ffe7d
3,608,839
import time def wait_for_reload(ctx): """ Wait for system to come up with max timeout as 25 Minutes """ begin = time.time() pattern_to_match = r"RP\/0\/RP0\/CPU0\:ios(\([^()]*\))?#|RP\/[0-3]\/RS?P[0-1](?:\/CPU[0-3])?:ios#|rommon \d+ >|XML>" if not ctx.is_console: ctx.disconnect() ...
9e20631997fa89f6b483bf692b7a3cdee0951b59
3,608,840
def get_api(alias=None): """ Returns global API object and if present, otherwise raise MissingConfiguration exception. :param alias: Alias of the API to retrieve :type alias: str :returns: An API object :rtype: :class:`infermedica_api.webservice.API` :raises: :class:`infermedica_api.ex...
0f7575ea49591f31c123f4acfaa9582fe8386477
3,608,841
def grad_coordinate_mom( loss_derivative, j, X, y, inner_products, fit_intercept, n_samples_in_block, ): """Computation of the derivative of the loss with respect to a coordinate using the median of means (mom) stategy.""" # TODO: parallel ? # TODO: sparse matrix ? return...
f0ec79f4f0b3c354af3c3fdc149ac471fac55c0c
3,608,842
import subprocess def execute(*args, **kwargs): """Creates a subprocess and waits for it to finish. Returns ExecuteResult object which provides return code and output. Blocking call. """ kwargs["stdout"] = kwargs.get("stdout", subprocess.PIPE) kwargs["stderr"] = kwargs.get("stderr", subprocess...
cf1186b155fbf00f3fab5319c8f5e4191020b08a
3,608,843
def mol_to_smiles(molecule, isomeric=True, explicit_hydrogen=True, mapped=True): """ Generate canonical SMILES with OpenEye. Parameters ---------- molecule: oechem.OEMol isomeric: bool If True, SMILES will include chirality and stereo bonds explicit_hydrogen: bool If True, S...
8e58b5941d81f426114c65a7cc14b05c84fd776f
3,608,844
import torch def conj(x): """ Computes the complex conjugate of complex-valued input tensor (x). ``conj(a + ib)`` = :math:`\\bar{a + ib} = a - ib` Args: x (torch.Tensor): A tensor. Returns: torch.Tensor: The conjugate. """ assert is_complex_as_real(x) or is_complex(x) ...
2eb4768d90c3c683f6e4513de3ea3fccfffbcdc7
3,608,845
from .fs import is_pathname_valid from . import fs from .fs import is_pathname_valid from . import fs import os.path from .fs import from_posix, abspath def absurl(url, relative_to = None): """ Turn relative file URLs into absolute file URLs. This is necessary, because while JSON pointers do not allow relative...
401f8e733e01ef9c93d945a8623bfc13dba3bfc2
3,608,846
import re def get_page_count(filename: str) -> int: """ How many pages are in a PDF? """ log.debug("Getting page count for {!r}", filename) require(PDFTK, HELP_MISSING_PDFTK) stdout, _ = run([PDFTK, filename, "dump_data"], get_output=True) regex = re.compile(r"^NumberOfPages: (\d+)$", re.M...
28a3407c9ad152e3ea14b8a50aa5cce20cf0b3ce
3,608,847
def runSingleThreaded(runFunction, arguments): """ Small overhead-function to iteratively run a function with a pre-determined input arguments :param runFunction: The (``partial``) function to run, accepting ``arguments`` :param arguments: The arguments to passed to ``runFunction``, one r...
9cdc34f5e44751667ec5a3bddcf2958b3302f4d1
3,608,848
def clean_year(year): """ Cleaning up year column """ if len(year) > 3 and year[0].isnumeric() and year[3].isnumeric() and year[1].isnumeric() and year[2].isnumeric(): return year[:4] else: return np.nan
4bda1034e921bb450a6052b056fa46688e1203d0
3,608,849
def init_residual_weights_matrix(dim_in, dim_out, borrow=True): """Partial isometry initialization.""" if dim_out == dim_in: weights = np.identity(dim_in) else: d = max(dim_in, dim_out) weights = np.linalg.qr(np.random.randn(d,d))[0][:dim_in,:dim_out] return theano.shared(np.asar...
acef4bac45b198655be4eb53204e8f4019ce7565
3,608,850
def get_pointers_samples(tot_samples_one_frame,adjusted_shift_inside_frame,accu_block,\ rel_pos_frame,tot_samples_sup_frame,ref_offset=0): """ Compute metadata relative to sample organization (sample ids, offsets, chunk sizes...). Parameters ---------- tot_samples_on...
987c7333bf098781b8dfe922eb4a87b908c1e138
3,608,851
def calc_velocity(STRIDE_LENGTH, LEG_LENGTH, grav_const): """Calculate velocity of the dinossaur """ return ((STRIDE_LENGTH / LEG_LENGTH) - 1) * sqrt(LEG_LENGTH * grav_const)
22b2b047a347ee256adf293d9548e2860ce65b35
3,608,852
import time def velocidade(funcao): """ Função decoradora: Verifica o tempo que uma função leva para executar """ def envolve(*args, **kwargs): """ Função que envolve e executa outra função """ # Tempo inicial start = time() # Pega o tempo atual # Executa a função ...
2784eed306b4c2c90423bbb1eb05f54ee9cc4ace
3,608,853
from typing import Dict def get_env_variables(runner: Runner, remote_info: RemoteInfo) -> Dict[str, str]: """ Generate environment variables that match kubernetes. """ # Get the environment: remote_env = _get_remote_env( runner, remote_info.pod_name, remote_info.conta...
e7116645cbd069298e2d7f766c259aba6ddc1c4b
3,608,854
def comp(*args) -> bool: """Compare string lengths.""" return len(set([len(arg) for arg in args])) == 1
c3bf069c723b37030531ffbbb84a0a91488a7345
3,608,855
import sysconfig def get_build_cflags(): """Synthesize a CFLAGS env var from the current python env for building of C modules.""" return '{} {} -I{}'.format( sysconfig.get_config_var('BASECFLAGS'), sysconfig.get_config_var('OPT'), sysconfig.get_path('include') )
4449c19a6f1758c4db415f76a50fd7749afd8b57
3,608,856
def DC_LC(z): """Method for comoving distance in Linear Coasting model""" return np.log(1.0+z)
52d28730a7f8a69bb5aed1cf342608fe3e18ce82
3,608,857
def clip(num, num_min=None, num_max=None): """Clip to max and/or min values. To not use limit, give argument None Args: num (float): input number num_min (float): minimum value, if less than this return this num Use None to designate no minimum value. num_max (float): maxim...
fe46f5a200ab24d517c57c5e1d93d4bf86192e13
3,608,858
def Singleton(name, bases, dict): """Use this metaclass on Converter subclasses to create a instance.""" return type(name, bases, dict)()
d7a196f0a645dac8150d9fba46b426882358a9a6
3,608,859
from typing import Dict def tSNE(X: Matrix, **kwargs: Dict[str, VALID_INPUT_TYPES]): """ This function performs dimensionality reduction using tSNE algorithm based on the paper: Visualizing Data using t-SNE, Maaten et. al. :param X: Data Matrix of shape (number of dat...
c267b9d0a84180bfde3701853ea282f2bf0ef5cf
3,608,860
import collections def build_model_metrics_aggregator( model: model_lib.Model, metrics_type: computation_types.Type ) -> computation_impl.ConcreteComputation: """Creates a stateless aggregator for client metrics.""" @computations.federated_computation( computation_types.at_clients(metrics_type)) def ...
35b55d2808a7bc02659a564b9ca11c9cef108494
3,608,861
def sparse_std(a, axis=None): """Standard deviation of sparse matrix a std = sqrt(var(a)) """ return np.sqrt(vars(a, axis))
2bc56bbe70da190ccbb0234a7a9b61281058431c
3,608,862
def reduce_with_mantid(ws, data_set, apply_db=False, apply_scaling_factor=False): """ @param ws: Mantid workspace @param data_set: template object """ kwargs = { "InputWorkspace": ws, "NormalizationRunNumber": str(data_set.norm_file), "SignalPeakPixelRange": data_set....
dd1494074b9754c5e85fec1dfebc66489af1367a
3,608,863
def calculate_fraction_of_sn_discovered( log, surveyCadenceSettings, snSurveyDiscoveryTimes, redshifts, peakAppMagList, snCampaignLengthList, extraSurveyConstraints, zmin, zmax): """ *Given a list of the snSurveyDiscoveryTimes calculate the...
70409bba2f7dd2601ed073ad140d75c8ec863942
3,608,864
import random import os def computeTrainValidationTestRecords(dataPath, foldName='Default'): """ Function to compute consistent train/validation/test split by a constant random seed on the Physionet 2018 challenge data :return: Names of records for training, validation, testing data sets """ print...
b1cdd0fcfcdff8665013ea1a4197a69c5b026eca
3,608,865
def create_model_info(config, loss_func, accuracy): """Create a dictionary of relevant model info. Parameters ---------- param : dict Any parameter relevant for logging. accuracy_log : dict A dictionary containing accuracies. Returns ------- type Description of ...
25cd8f49a0c7c7fd9b52f3d33c8a8ac24167fbff
3,608,866
def grid_coordinates(roi, x_divisions, y_divisions, position): """ Function that returns the grid coordinates of a given position. To do so it computes, for a given area and taking into account the number of x and y divisions which is the total amount of cells. After that it maps the given position to the cell it ...
1db6e8ed8b1c0abde965e3a5536867ae32ac2228
3,608,867
def splitmessage(message): """Returns a tuple containing the command and arguments from a message. Returns None if there is no firstword found """ assert isinstance(message, str) words = message.split() if words: return (words[0], words[1:])
d8db56ef55097f9f8858de95ee3d7799c0dc127e
3,608,868
def methods_of(obj): """Get all callable methods of an object that don't start with underscore. returns a list of tuples of the form (method_name, method) """ result = [] for i in dir(obj): if callable(getattr(obj, i)) and not i.startswith('_'): result.append((i, getattr(obj, i)...
ca22a91b5c60749e7a6b700cb029baab6b64eeb7
3,608,869
import typing def implement_insulation_widths(delphin_dict: dict, system: pd.DataFrame) -> typing.List[dict]: """Permutate width of system applied materials""" # look up current material assume system db_material = get_material_info(system.loc['insulation' + '_00', 'ID']) insulation_select = ['insula...
41fcf75890f09cb1568509d20dca0803dbef0db3
3,608,870
def make_moment_matcher(config): """make_moment_matcher(config: dict) -> (MM, dict) Initialize an MM given `config` and return unconsumed part of `config`. """ return _make_mm_from_kwargs(**dict(DEFAULT_PARAMS, **config))
10704127ada70d70629c989bd39bb8306032d3ca
3,608,871
def get_reddit_instance(refresh_token=None): """Get the interface to talk to Reddit :param refresh_token: The refresh token given on a previous authentication, which we can use to continue their session. """ user_agent = ('Dust. Giving users the power to remove their content.' ...
110f17f4406a185e30185fd0eb482af95d3fc94f
3,608,872
def num_allowed_shape_input(): """ This function receives input from the user - The total number of matchsticks for division It returns the user's input """ while True: num_allowed_s = raw_input("ENTER THE NUMBER OF MATCHSTICKS FOR DIVISION: ") if num_...
251b26e33671fa26ff5a63b880a7072e619454ce
3,608,873
from textwrap import dedent async def query(conn: pg.Connection, timestamp) -> Record: """ Returns current P2PK address counts by minimal balance. Assumes snapshots are up to date. """ qry = dedent( """ select count(*) as total , count(*) filter (where value >= 0.001 *...
daa5ef5c08c2ca94e3d8bf7486431ee039ef3c7c
3,608,874
from typing import Dict from bs4 import BeautifulSoup def check_html_doc( html_path: str, all_links: bool = False, top_root: str = None, checked_links: Dict[str, UrlResult] = None, ) -> Dict[str, UrlResult]: """ Check links in an html document (file). Parameters ---------- html_pa...
58c7cb71b67859821bbf5fde38dab85fe5fe2007
3,608,875
def dec_to_str(total): """Converts decimals to strings for more natural speech.""" if total == 0.125: return "an eighth" elif total == 0.25: return "a quarter" elif total == 0.5: return "a half" elif total == 0.75: return "three quarters" else: if total % ...
05e170eb21f5f0b188a32a634b5c617536c64a11
3,608,876
from typing import Iterable def make_location_trees(tables: Iterable[Table]) -> list[LocationTreeNode]: """ Return a graph representation of the origins for given tables Graph is a collection of trees: B LocationFile L LocationBlock # table B LocationBlock # include ...
a67701963170c7b61a8149ac3ccaca89741dd0e3
3,608,877
def _order_logging_keys(logger, method_name, event_dict): # pylint: disable=unused-argument """ Returns an OrderedDict with a spesific key order. Unnamed keys are alphabetically sorted at the end. """ keys = len(SORT_ORDER) return dict(sorted(event_dict.items(), key=lambda i: SORT_ORDER.get(i[0...
cf0b9f379f9f5a97b8578e5ac5a1a7ba10c2fa37
3,608,878
def maybe_cast_list(value, types): """ Try to coerce list values into more specific list subclasses in types. """ if not isinstance(value, list): return value if type(types) not in (list, tuple): types = (types,) for list_type in types: if issubclass(list_type, list): ...
c3078c42087103ee8b0a8b3257d345e7d73c0fd7
3,608,879
def bilinear(image, warp): """ Bilinear interpolation. Parameters ---------- array: nd-array Input array for sampling. warp: nd-array Deformation coordinates. Returns ------- sample: nd-array Sampled array data. """ result = n...
80fe5bde81f878b91418898d26d628f18e152899
3,608,880
def forxml(uri): """ Escape XML nasties in a URI """ return xmlutils.cleanxml(uri)
aefc461d7f9d2be53f4ef4fb0a10f9551b0eb334
3,608,881
def create_set_brightness(hass): """Returns service for set_brightness.""" async def async_set_brightness(call): _LOGGER.debug( f'hue_syc_box async_set_brightness handler called ' f'with data: {call.data}.') entity_ids = call.data.get(const.ATTR_ENTITY_ID) brightness = call.data.get(con...
4349f53bca124832d0a72a9f52f26a556bab7786
3,608,882
def dh_noConv(value, pattern, limit): """Helper for decoding a single integer value, no conversion, no rounding.""" return dh(value, pattern, encNoConv, decSinglVal, limit)
1107ca20edf660d66818bb9e3922cf36c34cefe3
3,608,883
import re from typing import OrderedDict def CustomExtension(observable=None, type='x-custom-observable', properties=None): """Decorator for custom extensions to STIX Cyber Observables. """ if not observable or not issubclass(observable, _Observable): raise ValueError("'observable' must be a vali...
6cbc0adb9191b710abca60804ab9b56ce79556f7
3,608,884
def read_wi_table(wi_file, wi_column): """ Reads in the relative adaptiveness file """ tmp_wi_dict = {} line_number = 0 with open(wi_file, 'r') as infile: for line in infile: line_number += 1 if line_number == 1: continue # skip header ...
89a1b38e375678b8d221b7386dd742fe6745223c
3,608,885
def uri_encode(data): """ Return URI encoding of the passed string. Args: data (str): String to encode Raises: None Returns: TYPE: str """ return quote(str(data))
3c0b7274f2661a4ba4939404669f51e16f98b11c
3,608,886
def get_accuracy_by_dtype(predictions): """ Calculates model accuracy w/r to available data types. Parameters: predictions (pandas.Series): model predictions for each sample Returns: accuracies (pandas.Series): model accuracy w/r to data types """ d_types = list(set(predictions...
e4eb37cdcf6273b6daa3cf0431c88a892a544e25
3,608,887
def run_retina(params): """Run the retina using the specified parameters.""" tmpdir = tempfile.mkdtemp() print "Setting up simulation" pyNN.Timer.start() # start timer on construction pyNN.setup(timestep=params['dt'],max_delay=params['syn_delay']) pyNN.pynest.setDict([0],{'threads' : params['...
6180c6e233cdb67cf2109f53611a9736e0393297
3,608,888
def basic_form3_exams(request): """TODO: Docstring for home. :returns: TODO """ form3 = models.BasicForm3Exam.objects.all() return render(request, 'membership/basic_form3_exams.html', { 'form3': form3 })
a2d32a21a6df72d95faed492a8c80a4de314cc9c
3,608,889
def detect_cycle(init_progs, compiled_moves): """Find a cycle length by repeating a list of compiled moves""" progs = fastdance(list(init_progs), compiled_moves) cycle = 1 while progs != init_progs: progs = fastdance(progs, compiled_moves) cycle += 1 return cycle
782771b4e218bbe0c352cb503cff4de4b8a0d070
3,608,890
def get_thickness(system, axis): """Get the thickness of an atomic system along a basis vector direction. Args: system(ase.Atoms): The system from which the thickness is evaluated. axis(int): The index of the unit cell basis in which direction the thickness is evaluated. Return...
64e57ba302cc7f64ba45f16b32744522938c92e9
3,608,891
import os import warnings def load_tng_small_data(gal_type, data_drn=BEBOP): """Load a smaller subsample of the stellar mass histories from the IllustrisTNG simulation. The loaded stellar mass data has units of Msun assuming the h = H_TNG from the cosmology of the underlying simulation. The outp...
dff602f6c3633c5ef51487cccf82ddb56ac94d82
3,608,892
def affilation_wks(short_name, graph_df): """ Find wich wks to use by postfix at command :param short_name: command last word like Basketball_FF1 :param graph_df: pandas df of graph :return: node_id and link_id """ row = get_row_by_keys(graph_df, key_value=[short_name]...
bb5a63248d45c37275314972f36bcee12877ec31
3,608,893
import re import optparse import doctest import matplotlib from matplotlib import pyplot import sys import time import warnings def main(argv=None): """Command line usage main function.""" if float(sys.version[0:3]) < 2.6: print("This script requires Python version 2.6 or better.") print("This...
65d2910d80b414b6ebdb9e93eb0cba53d9ca2af5
3,608,894
def healthcheck(): """Returns health information""" return jsonify({ "message": "I feel good." })
0bc6e43fcbb5c15771be417a0831822e9ef34971
3,608,895
from os import makedirs from os.path import exists def check_path(path): """Check if path ends with a slash ('/'). Else, it adds a slash. The function also creates the directory if it does not existing. Parameters ---------- path : str A path Returns ------- path : str ...
f583d720d04d84f62fef4ca022a1b7d71c5d4493
3,608,896
def get_msg_fileslug(msg): """ for a given message, which file/foia is this? checks entire message thread for category labels """ convo = get_conversation(msg['conversationId']) for msg in convo: for cat in msg['categories']: if 'file' in cat: return cat
aa177140a15c3b26bbb307414be173e4ac7ea12c
3,608,897
import os def dir_select(): """Getting the user to select the folder in which the file is located""" root = tk.Tk() root.withdraw() print("\nPlease select the folder directory where the file is located") origin_directory = filedialog.askdirectory() print("\nSelected directory path:") origi...
381d013f96aca0886bf6f3dd56528275788c1c82
3,608,898
import numpy def empty_like_pinned(a, dtype=None, order='K', subok=None, shape=None): """Returns a new, uninitialized NumPy array with the same shape and dtype as those of the given array. This is a convenience function which is just :func:`numpy.empty_like`, except that the underlying memory is pinn...
f2a03e31ea8adbfecf81943b37dd7dc32606cfc7
3,608,899