content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import collections def flatten(d, parent_key='', sep='_'): """ Will flatten the dictionary d (i.e., config) with all keys merged by `sep`. """ items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k if isinstance(v, collections.abc.MutableMapping): ...
1e5682a6d84315cef70878877f586ca867187c41
78,661
def remove_length_annotation(id): """ Remove the length from the query id """ return config.query_length_annotation_delimiter.join(id.split(config.query_length_annotation_delimiter)[:-1])
2712be55f57be7b82577bed40b7f4a809e40a216
78,662
import time def getId(): """ Create a unique identifier """ time.sleep(0.001) v = int(time.time() * 1000) - HASH_ZERO return HASHIDS.encode(v)
0748242a16fc183a2b8ef15c9cf29bcb9aeb2e05
78,663
def get_modfreq_from_quantiles_many_samples(scores_per_sample, q=0.1): """Return modification frequency calculated using quantiles method""" freqs = np.zeros(len(scores_per_sample)) minc = min(map(len, scores_per_sample)) q1, q2 = np.quantile(np.concatenate([s[:minc] for s in scores_per_sample]), [q, 1-...
ed2fedfdaadfa65a9080887c11ab7a7731494962
78,664
def model_ids(models): """Generates a list of model ids from a list of model objects.""" return [m.pk for m in models]
a938434df3805c77c0446ab3f4fec4161fbaa39e
78,665
def annotate_the_bootstrap_tree(str_bs_tree, gene_tree_transfer_recipient, gene_tree_transfer_donor, speciation_res_ge, transfer_res_ge, loss_res_ge, duplicate_res_ge): """ this should take in all the results of parsing the rangerDTL output for one single bootstrap and the string containing that bootstrap t...
0ae44de6ed3c24d2f67b869930fc80b5db329ce4
78,666
import pkgutil def read_package_file(file): """ Read entire contents of a package file """ return pkgutil.get_data(__name__, file).decode()
bf240683fe7442f5ab24a804e264c5d4b4ca21f5
78,667
import functools def _expand_variable_args(func): """ Expand single positional argument into multiple positional arguments with optional keyword dicts. Permits e.g. `get(('t', {'lat': 'mean'}))` tuple pairs. """ @functools.wraps(func) def _wrapper(self, *keys, **kwargs): args = [] ...
afe9604e888636704cdeb6cb7ad545d2cff5138e
78,668
def data_variance_plot(data, settings=None, xlabel='Time', xlim=None, xlog=False, ylabel='Variance', ylim=None, ylog=False, show=True, save=None): """Plot the variance statistics with standard errors of a data object (if variance data are available). ...
721d52c9666be1c2e54229c801faba1815ac73e8
78,669
def std_moments_error(θ: np.ndarray, policyF, xs, mean_std_observed_prices, prior_shocks, df, min_periods=3) -> float: """ Computes the **norm** (not gmm error) of the different between the observed moments and the moments predicted by the model + θ Moments: average (over firms) s...
ea309aae2cfd9eda55117cf46d2b6b087d8b84b4
78,672
def bsplclib_BoorScheme(*args): """ * Performs the Boor Algorithm at parameter <U> with the given <Degree> and the array of <Knots> on the poles <Poles> of dimension <Dimension>. The schema is computed until level <Depth> on a basis of <Length+1> poles. * Knots is an array of reals of length : <Length> + <Degree...
9b570d5637832e49fa266f209fa3187c40fe779f
78,673
def _KNV0_loop(ker_pole, transfer_matrix, poles, B, maxiter, rtol): """ Loop over all poles one by one and apply KNV method 0 algorithm """ # This method is useful only because we need to be able to call # _KNV0 from YT without looping over all poles, otherwise it would # have been fine to mix _...
b191dd637072d6c43b2c8fa616439e1f34b1f9e9
78,674
def check_annot(filename, line_num, annot): """ Function checks for the annotation condition @parameters filename: Path to the file line_num: function/method line number annot: Annotation condition (Ex: @Test) @return This function returns function/method definitions ...
e2c6881d5f9b5be49b060275fdaac77450a873ec
78,676
from typing import Counter def create_edges2(df_binary_matrix, edge = "character"): """ Esta función crea la lista de cantos a partir de la matrix binaria """ print("empezando edges: ") edges = [] # Creamos la lista depediendo de qué queremos observar if edge == "text_unit": li...
9329b5682a43ae05b2828e3bb43bef230e95e865
78,678
def ignore_dt(dt_anno, index, difficulty): """ Indicates whether to ignore detection Args: dt_anno [dict]: Detection annotation index [int]: Detection index difficulty [int]: Difficulty index Returns ignore [bool]: Ignore flag """ ignore = False return ignore
28fa46defcf3effa49cf0eb575c0da7deeeb53e4
78,680
def requires_auth(permission=""): """A decorator to authenticate users and verify permissions for a request. Args: permission: A str representing the permission required to access the requested resource """ def requires_auth_decorator(f): @wraps(f) def wrapper(*args...
866b9421895fdd9a52e4f91830f17f0dcfbace46
78,681
import functools import inspect def logging(lcolor=LColor.REGULAR): """Return a decorator that logs the method call in the specified lcolor.""" def decorator(method): @functools.wraps(method) def wrapper(*args, **kwargs): log = "===> calling '%s'" % method.__name__ cal...
8161a38cc9a9d0693fdff46db718f869200ee14d
78,682
def _v_str_ ( self , fmt = ' %g' ) : """Self-printout of SVectors: (...) """ index = 0 result = '' while index < self.kSize : if 0 != index : result += ', ' result += fmt % self.At( index ) index += 1 return "( " + result + ' )'
b983051bb6a097b8cbdffffab53f6b133117fe74
78,685
import json from datetime import datetime def batch_edit_mock_data(): """ 页面添加或修改数据使用本函数 :return: """ # 获取数据后解析成字典 obj 结构 data = request.get_data() json_data = json.loads(data.decode("utf-8")) print(json_data) db_in_data_list_id = json_data['batch_edit_id'] db_in_data_list_key...
fe92aaee425bf736ebbbec5ba97d4d15757879a7
78,686
def get_N_vs_sweepgate(dat: DatHDF, fit_name: str = 'gamma_small') -> Data1D: """Quick fn for Josh, to get Occupation vs sweep to see that peak is at 2/3""" fit = dat.NrgOcc.get_fit(name=fit_name) nrg = NrgUtil(NRGParams.from_lm_params(fit.params)) x = dat.NrgOcc.avg_x occ = nrg.data_from_params(x=x...
6a3396e10956412e6d5da09b677cf52feb93e58e
78,688
def strip_comments(sql): """sqlparse default implementation of strip comments has a bad performance when parsing very large SQL due to the grouping. This is because the default implementation tries to format the SQL for pretty-printing. Impala shell use of strip comments is mostly for checking and not for alter...
5664eb5b806d87f3b0b33f3d81b2c5f8d5a28535
78,689
def get_parameters(item: str, block: list) -> list: """ evaluate a class of items to download and return the list of actual objects to download. :return: list """ if item == "all": block.remove("all") return block else: return [item]
5acdd48956678d5407d9a9fae8945aeabb10d684
78,690
def build_onetime_request_body(donation): """Method to create body with CAPTURE intent""" # returl_url or cancel_url params in application_context tested to be only useful if order not initiated by Javascript APK return \ { "intent": "CAPTURE", "application_context": { "brand...
0880b3575db443dcd0ee75ca478729d74b8aba5b
78,691
def get_big_action(): """ Return an action which is a big choice between all possible actions. """ all_actions = [ v for k,v in _ivy_ag.actions.iteritems() if k != 'error' ] result = ChoiceAction(*all_actions) result.label = ' + '.join([ k for k,v ...
86273c8b456b169c3e350bcf5058cdaa83ec845e
78,692
from datetime import datetime import json import http def set_dynamic_time(request): """ Set a time to a People. Accept only POST request with parameters: :arg int num: The bib number of the runner :returns: A JSON data with some runner informations. """ # sanity checks ...
17593ff762325b182c2c9c000944ba1bb894ccda
78,694
def get_arg(key, args=None, default=None, default_none=False): """ Get an argument from object `args` or the default value for an argument if it is not in `args`. :param key: Argument key (name). :param args: Argument object or `None` to always get the default argument. :param default: Default valu...
dcdb3b5a4822d2eb222f6c05b68abcc81440eef7
78,695
def SetIamPolicy(project_ref, policy, update_mask=None): """Set IAM policy, for a given project.""" client = projects_util.GetClient() messages = projects_util.GetMessages() set_iam_policy_request = messages.SetIamPolicyRequest(policy=policy) # Only include update_mask if provided, otherwise, leave the field...
71cf27bc785337f8cc6e94452f9d84a1dee8074d
78,697
from re import L def singleLayerHead(feature_map, num_anchors_layer, num_class, last_channel): """ YOLO HEAD for one specific feature stage (after FPN) """ assert isinstance(num_anchors_layer, int) assert isinstance(num_class, int) ### NOTE: 7 means [objectness, x, y, z, w, h ,d] final_output_chan...
d22e2e191b371aeac4db0de6f1ce168d10c2366b
78,698
def day_events_card(date): """ Displays Events that happened on the supplied date. `date` is a date object. """ d = date.strftime(app_settings.DATE_FORMAT) card_title = "Events on {}".format(d) return { "card_title": card_title, "event_list": day_events(date=date), }
e799bb18a0765aff9acc79eb55f3d390c546d847
78,700
import csv def _extract_and_parse_csv(input_csv, key_header_label, values_header_label): """Extracts two columns from the given CSV file given the header row keys.""" freeform_labels = {} with open(input_csv, 'rb') as csvfile: reader = csv.reader(csvfile) # Parse the header row. header = reader.ne...
78d161379064f8c88c9b0d8eeb93cc03ca441850
78,701
def contacts_per_person_symptomatic_10x60(): """ Real Name: b'contacts per person symptomatic 10x60' Original Eqn: b'contacts per person normal 10x60*(symptomatic contact fraction 60+symptomatic contact fraction 10\\\\ )/2' Units: b'contact/Day' Limits: (None, None) Type: component b'' ...
97b7090769d242206bbfcb9c51ac8822d37c6d8a
78,702
from datetime import datetime import struct def dump_to_rsb(params: dict, times: np.ndarray, data: np.ndarray) -> bytes: """Сохранение данных в формате rsb. @params -- параметры набора @times -- абсолютные времена блоков в наносекундах @data -- данные блоков (block_num, block_size) @return -- се...
716f0eb0853836bfc5e3b9eefe5bfd6019a6674f
78,703
from typing import List def grid_hess(inp, grid, bound: List[int], interpolation: List[int], extrapolate: int): """ /!\ Used only in backward pass of grid_grad inp: (B, C, *spatial_in) tensor grid: (B, *spatial_out, D) tensor bound: List{D}[int] tensor interpolation: List{D}[int] ...
e658cfa96c1c10125ec24970c9508e5bdf16e928
78,704
def _mcse_quantile(ary, prob): """Compute the Markov Chain quantile error at quantile=prob.""" ary = np.asarray(ary) if _not_valid(ary, shape_kwargs=dict(min_draws=4, min_chains=1)): return np.nan mcse_q, *_ = _conv_quantile(ary, prob) return mcse_q
830c04f4f823490f7d0fb9186d9917c6a212e6eb
78,705
def oneYearHistory( token="", version="stable", filter="", format="json", **timeseries_kwargs ): """Rates data https://iexcloud.io/docs/api/#treasuries Args: token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-results...
569ce5f0218117ccd115fa7876c6a7986e6912e8
78,706
def is_numeric(obj: str) -> bool: """ Returns True if argument can be coerced to type 'float' """ try: float(obj) return True except ValueError: return False
b75ac54e7cd29406f6ef02882b89d1ab884a09c0
78,707
def version(): """ Return the package version """ return _gauss_version
590649f4455dca10d185c5ba0c666a85f50cb811
78,708
def get_post_detail(pk): """ Returns the details of one specific post :param pk: :return: """ post = Post.query.filter_by(id=int(pk)).first() if post.users is not None: author = post.users.first_name + ' ' + post.users.last_name else: author = '' post_blob = { ...
2b41d4c2eca81cb79955aad7e3a63a1e1e6459c3
78,709
def absolute_difference(ground_truth, simulation): """ Absolute difference between ground truth simulation measurement Meant for scalar valued measurements """ try: return np.abs(float(simulation) - float(ground_truth)) except TypeError: print('Input should be two scalar, numeri...
1093f4b5daf4cb66e68c679ab83ffe7736ffcd83
78,710
import math import copy def recInQspace(n, dimen, qspace, sd=.5): """Given n number of receptors and qspace, returns an epithelium with receptors at equally incremented distances from one another and the distance between them. Precondition: qspace must be a square that has origin at 0""" dime...
c83e96f6ec9d439b53920381d4dae0e2f5148950
78,711
def sliding_dot_products(q, t, q_len, t_len): """ Computes the sliding dot products between a query and a time series. Parameters ---------- q: numpy.array Query. t: numpy.array Time series. q_len: int Length of the query. t_len: int ...
787aba523f735ae07aea004bf816d8e69cf49a69
78,712
def _clauses(lexer, varname, nvars): """Return a tuple of DIMACS CNF clauses.""" tok = next(lexer) toktype = type(tok) if toktype is OP_not or toktype is IntegerToken: lexer.unpop_token(tok) first = _clause(lexer, varname, nvars) rest = _clauses(lexer, varname, nvars) ret...
a5d72b1e42679e00e9aaaf99bb82bb4175716035
78,713
from typing import Any from typing import Tuple def get_lat_long(ds: Any, most_suitable: Any) -> Tuple[float, float]: """ Return the lat_long of the pixel with mean value of the resources """ diff = most_suitable - np.mean(most_suitable[most_suitable > 0]) i, j = np.unravel_index(np.abs(diff).argm...
163ef5eced36c4e7eb687af397b7e4e6489b2760
78,714
import string def char_input(): """Choose password character options and return list of choices.""" char_list = [] chars = [ string.ascii_uppercase, string.ascii_lowercase, string.digits, "!@#$%^&*" ] input_list = [ "uppercase letters (A-Z)", "lowercase letters (a-z)", ...
418e1a118135039130ef4eb0f40f0d4fdad96b45
78,715
def GetFunctionParamPrototype(scope, param): """Gets the string needed to declare a parameter in a function prototype. Args: scope: the scope of the prototype. param: the Function.Param to declare Returns: a (string, list) pair. The string is the declaration of the parameter in the prototype. Th...
66f821c83a5e3ddb860835d9f6fa4215c28a543b
78,716
from common.base_utils import generate_request_id def activate_request(request, request_id=None): """ 将 Request 相关信息记录至线程变量,检查必要参数 """ if not request_id: request_id = generate_request_id() request.request_id = request_id _local.request = request return request
959f1137f58a6b9ea004ffb1693f70d6104fd27c
78,717
import itertools def cylinder_factory( length, radius, mass=None, name='cylinder', pose=[0, 0, 0, 0, 0, 0], use_permutation=True, color=None): """Factory function for cylinder-shaped models. It parses the vectors `radius` and `length` to generate the cyl...
d8e50f81ac4e35780d3bf8a0138f8122f65d14fb
78,718
def isfloat(x): """Test if a string is a valid float number.""" try: float(x) except ValueError: return False else: return True
6aa39af478df745565fb4ca16e66faf52fc29f80
78,719
import json from typing import Iterable def stringify_request(request_data): """ stringfy HTTP request data Args: request_data (dict): HTTP request data in dict. { "url": "http://127.0.0.1:5000/api/get-token", "method": "POST", "headers": {...
60e3286b6b829f9b5c1ba850bc17fc34672bbb03
78,720
import attr def include_list_name(name): """ Class decorator. It is used for stats model classes. Decorated class will be registered to IncludeLists, so when you convert your stats model to dict and list you'll be able to specify list of fields to include.""" def decorator(cls): if not attr.has(cls): ...
42d388424661394efe60321f1b03e0aa9a4a6e7f
78,722
def get_or_make_group(ec2, name, vpc_id=None, quiet=False): """ Get the EC2 security group of the given name, creating it if it doesn't exist """ groups = ec2.security_groups.all() groups = [g for g in groups if g.group_name == name and g.vpc_id == vpc_id] if len(groups) > 0: return ...
48b9c0a3fef99763e05e60bc6f2186f52f841031
78,723
def job(): """ endpoing: /getDomainAge/job job endpoint for placing new job request """ session[SessionParam.PAGE_INDEX.value] = 0 add_job_form = AddJobForm(request.form) if request.method == HttpMethod.POST.value: return redirect(Endpoint.API_JOB_ADD.value, code=307) return re...
e36fe48ca32b28a444732a2d677a6d43a34ce394
78,725
def dice_coefficient2(a, b, case_insens=True): """ :type a: str :type b: str :type case_insens: bool duplicate bigrams in a word should be counted distinctly (per discussion), otherwise 'AA' and 'AAAA' would have a dice coefficient of 1... https://en.wikibooks.org/wiki/Algorithm_Implemen...
131cd2660140e94341b2357d3baa22d76863675e
78,726
def sbm(n_blocks, block_size, p, q, rng=None): """ (Symmetric) Stochastic Block Model Parameters ---------- n_blocks : int Number of blocks. block_size : int Block size. p : float Probability for intra-community edge. q : float Probability for inter-community...
1ecbad95ee3edbe5c91975112afdd94b4234c8c3
78,727
import inspect def kwargs_sep(fcn, kwargs): """Used to separate kwargs for multiple different functions Args: fcn: function kwargs: dict of keyword args Returns: dict for fcn keywords contained in kwargs""" #list of fcn argument names fcn_args = [key for key, val in i...
016e8ab7e423e9c8f896bfd18213d323d58a129b
78,729
import requests def lookup_by_email(email_value=None): """ Lookup a Patron by their email address :param email_value: the email address to search for :return: dict: patron information """ if not email_value: return {} email_value = email_value.strip().lower() headers = get_h...
7c87ef300eb38b8bbf4c80e6ff2977bbb7810354
78,730
def plot_weibull_prob_plot(t, r, ci_lb=None, ci_ub=None, ax=None, marker='o', color='blue', label=None): """ Produces a linearised probability plot for the Weibull distribution. :param t: The time values. :param r: The reliability estimates corresponding to the time va...
fad9a7df4c50d72ca34db361465c0040def9d28d
78,731
from re import A from typing import List def lists(elements: SearchStrategy[A], min_size=0): """ Create a search strategy that produces `pfun.list.List` instances Args: elements: strategy used to draw elements of the list min_size: minimum size of the lists Example: >>> lists(...
fb879395a877f965a604083037666886e4bc428c
78,732
from typing import List from typing import Optional from typing import MutableSequence def diff_list(json1, # pylint: disable=too-many-branches; linter balking on := walrus json2, path: List[str] = None, ignore_keys: List[str] = None) \ -> Optional[List[Node]]: "...
4475276e232cb38392a704f813df432d192943ce
78,733
def bernoulli_gamma(bijector=None, axis=-1, epsilon=1.0E-6): """ Returns a joint Bernoulli-Gamma distribution constructor, paramterized by 'params'. Parameters p, alpha, beta are selected from the given axis, in that order. """ def _bernoulli_gamma(params: tf.Tensor): logits = tf.gather(para...
a98956a0e2248d7aacafed59e1393fd9a57809a0
78,734
def build_tzinfo(tzname, tzsign="+", tzhour=0, tzmin=0): """ create a tzinfo instance according to given parameters. tzname: 'Z' ... return UTC '' | None ... return None other ... return FixedOffset """ if tzname is None or tzname == "": return None if tzname...
7ad0d1cbbae7865be804002c1daf6a9bb79f8b87
78,735
from typing import Tuple from typing import Optional def check_locale_float(text: str) -> Tuple[Optional[str], bool]: """ This is intended as a locale safe way to parse a float. It supports various types of floats. Example ------- >>> _check_float('3.14') 3.14, True >>> _check_float('...
f2f4689ead0e56e9e6827464c1cdc1107a016638
78,736
def get_oam_ip(): """ get OAM ip details """ try: with openstack.OpenStack() as client: oam_list = client.sysinv.iextoam.list() if oam_list: return oam_list[0] except Exception as e: LOG.exception("failed to get OAM IP") raise e return None
8da1f69cf3fc36b367aeab3874309ce620740741
78,737
def revjul(jd, formatstr='%4d-%02d-%02d %02d:%02d:%02d', tz_off=0): """Returns a more human readable revjul compared to swe Converts a given jd (float) to a tuple [y,m,d,h,mm,ss] Args: A float corresponding to a Julian day Returns: A tuple detailing the year, month, day, hour, minute and ...
13361af52d67188bb651d3610845a1a74e98579e
78,739
import importlib def try_to_import(pkg, name, current_pkg=None): """Import an attribute from a module, or return an error-producing fake. This method is provided as a convenience for libraries that want to easily expose modules with a variety of prerequisite libraries without forcing the user to inst...
4b70d100decf1c694dc4d0661f987da2a0d1b1e4
78,740
def fit_parameter(estimates, fun, start_values, xval): """ Fitting any numbers of given infectious rate function using least squares. Used count of observed events in observation window as weights. :param estimates: estimated values of function :param fun: function to fit :param start_values: i...
676e3d313cf451cf7f0c40d968ed6836b2c1c753
78,741
def mod_crop(img, scale): """Mod crop images, used during testing. Args: img (ndarray): Input image. scale (int): Scale factor. Returns: ndarray: Result image. """ img = img.copy() if img.ndim in (2, 3): h, w = img.shape[0], img.shape[1] h_remainder, w_r...
825f70fde2dd19ea069c14be77fdf8c6e8cc0d82
78,742
def min(*values, key=None): """ With a single iterable argument, return its smallest item and the position of this item. With two or more arguments, return the smallest argument with its position. """ if len(values) == 1: values = values[0] iterable, key = build_arguments(values, key) ...
1ca88547d5c852f7fc295e453d1c3a608dbb2e18
78,743
def dist_riem_squared(X, Y): """ Computes the squared distance, induced by riemmanian norm, between two SPD matrices. """ x = _transform_mat(X, 'isqrt') mid = np.einsum('...ij,...jk,...kl', x, Y, x) return norm_frob_squared(_transform_mat(mid, 'log'))
1856881ea5a113ae851738d378bbf8b9fca92b40
78,745
from typing import Optional from typing import Sequence def get_data_keys(apm_domain_id: Optional[str] = None, data_key_type: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetDataKeysFilterArgs']]] = None, opts: Optional[pulumi.InvokeOptions] ...
a1938558068856d2b1609e6aa03f417109d148ad
78,746
import functools def which_bin(exes): """ Decorator wrapper for hubblestack.utils.path.which_bin """ def wrapper(function): @functools.wraps(function) def wrapped(*args, **kwargs): if hubblestack.utils.path.which_bin(exes) is None: raise CommandNotFoundErro...
f7690303e1199c41e7d2bf78eeb646cfa38366a7
78,747
def set_ecs_access_key_id(config_fpath, bucket_name, ecs_access_key_id): """Write the ECS access key id to the dtool config file. :param config_fpath: path to the dtool config file :param bucket_name: name of the bucket in a ECS namespace :param ecs_access_key_id: ECS access key id """ key = EC...
34621568a2ace88b83182ed5f8199952576bfee3
78,749
def get_ip_lb_service_backends(ovh_client, service): """ Get legacy load balancing service backends GET /ip/LoadBalancing/{serviceName}/backend """ url = '/ip/loadBalancing/{service}/backend' return ovh_client.get(url.format(service=quote_plus(service)))
2822f6e90271df36141b4b490dc93c68a96c8bd7
78,750
async def CheckGuildHasSettings(guild): """ A function used to check if a guild exists in the config file and if it doesnt, create the settings. This should be used before every function that uses guild settings basically """ data = cogs._json.read_json('config') if not str(guild.id) in data...
43a5fac7857d19190fcce98e703005afbe5cd985
78,751
def mock_vcf_reader(variants): """Creates a Mock vcf_reader returning variants from variants. This function creates a mock vcf_reader with a query method that searches for overlapping variant protos from variants. Args: variants: list of learning.genomics.deepvariant.core.genomics.Variant protos. ...
2cf30e6407e279a353e6c8edea08734ee564e788
78,752
async def data_for_subreddit(sub, kind): """ """ data = await subreddit_type_submissions(sub, kind) return data
5cbf90aa4581272616876c68862ea79fddb6a2ae
78,753
def broadcast(x, axes): """ Broadcast the axes of x. Args: x (TensorOp): The tensor. axes: New axes. Returns: TensorOp: Tensor with additional axes. """ axes = make_axes(axes) if x.axes == axes: return x return BroadcastOp(x, axes)
fa542a5d22dc7a6ea277678454ec8aad6461e5a9
78,754
def constructLinkedList(nums): """ 方法功能:创建单链表 输入参数:nums: 作为链表结点的数据 返回值:head: 链表头结点;tail: 链表尾结点 """ head = LNode() cur = head for num in nums: tmp = LNode() tmp.val = num cur.next = tmp cur = tmp tail = cur return head, tail
5382367eee0cc350f521dcfe7edb6c1364404b75
78,755
import logging import traceback def log_exception(f): """Emit exceptions with full traceback instead of just the error text""" @wraps(f) def wrapped(*args, **kwargs): try: return f(*args, **kwargs) except Exception: logging.error(traceback.format_exc()) ...
c78438f5994ad10ae11f8e79dba971a3e6fbd283
78,758
import math def min_distance(weight_cols, points): """ 拟合直线,与直线距离最小 """ x_avr, y_avr = np.average(points, axis=0, weights=weight_cols) total = np.sum(weight_cols) A = 0 B = 0 C = 0 for i in range(len(points)): x = (points[i][0] - x_avr) * weight_cols[i] / total y = ...
2a6e2a1bd210c76458d7c24ccdeefdbc7a768211
78,759
import scipy def background(spectra, fsteps=10, ksteps=10): """Uses a 1-2-1 filter to generate 'red noise' background field for a spectra (as per WK1998) `fsteps` is the number of times to apply the filter in the frequency direction `ksteps` is the number of times to apply the filter in the wavenu...
1a5fc3f091d692b26d4840da85251613d60035dc
78,760
def mergeModes_magic(g, tau, imode): """merge modes imode and imode+1 into a single mode return gp and taup corresponding to this new mode; 12/2018 - also tries finetuning before returning uses helper functions: - normKern_magic() - costFcn_magic() """ iniGuess = [g[imode] + g[imode+1],...
0d9f8afb81f90a52b29b9f97a16cd3ce9224ca50
78,761
def guess_extension_from_headers(h): """ Given headers from an ArXiV e-print response, try and guess what the file extension should be. Based on: https://arxiv.org/help/mimetypes """ if h.get("content-type") == "application/pdf": return ".pdf" if ( h.get("content-encoding") ...
5f9fabaf20311f6f2c564b613d50d28d07b3dfdd
78,762
def process_event(self, source_name, codes=None, **kwargs): """ .. note:: MONKEY PATCH: This patch of the Pyaflowa function provides a slight alteration to the Pyaflowa source code by treating some data differently in the processing workflow The main processing function for Pyaf...
c0329bfa1c6d2254dfcc2338cdb2d9a2287267e3
78,763
import json import logging import textwrap def modify_function_json_to_include_binding( config, extra_config, app_type, app_path, ): """ Adds the output binding information as needed to the function.json file of the function! :param config: Configuration dictionary (the on...
3c4b057ed48a43920da6b0c3cab5bacde80dcac9
78,764
def move_one_node(soln, seed): """Move one node to another position to give a neighbor solution. The node to move and the position to move to are chosen randomly. The first and last nodes are left untouched as soln must be a cycle starting at that node. Parameters ---------- soln : list of...
e15348c7876e5ad5ad541b079d47bb6bde71f7f9
78,765
def strunit_array_to_qunit_array(array_like_of_str, parsing_dict): """ Converts an iterable of strings to an iterable of quantities Example : ========= """ qs = [] for s in array_like_of_str: q = expr_to_q(s, parsing_dict) qs.append(q) return qs
b5fe7b6a3c8a876d8cc8a4becc62f73337d0403b
78,766
def get_mean_vec(dps): """ return mean vector for each columns """ mean_vec_ = [] for i in range(len(dps[0])): data_cols = [dp[i] for dp in dps] dp_row_mean = np.mean(data_cols) mean_vec_.append(dp_row_mean) return np.array(mean_vec_)
957162607476b0c2d3a66aa619f92977d80af82a
78,767
def prop_zernikes(a, zernike_num, zernike_val, eps = 0., **kwargs): """Add Zernike-polynomial wavefront errors to current wavefront. Noll ordering is used and a circular system is assumed. An arbitrary number of Zernikes normalized for an unobscured circular region can be computed, but only the ...
87c2a97a3902e8a5f43bcad65c5936e16d172ae3
78,768
import scipy def pitchShiftSTFT(S, Fs, shift): """ Use image interpolation to do spectogram shifting in the spectral domain :param S: An NFreqsxNWindows spectrogram :param Fs: Sample rate :param shift: Number of halfsteps by which to shift :returns: An NFreqsxNWindows shifted spectrogram "...
dbab85e5345a11f2059d80959de39c03789b2b8c
78,769
def fast_exponentiation(base, exp, n): """ Iteratively finds the result of the expression (base**exp) mod n """ bin_exp = bin(exp)[2:] output = 1 for i in bin_exp: output = (output ** 2) % n if i == "1": output = (output*base) % n return output
c646a9226487fcac947160ee6d56a6a51b3106a9
78,770
def aln_mpi(alignment: 'StringVector') -> "int": """aln_mpi(StringVector alignment) -> int""" return _RNA.aln_mpi(alignment)
e2c66ded66e380f5d2589ceca18fb4d41b301a2d
78,771
def _edits1(word): """ Return a set of words with edit distance of 1 from the input word """ splits = [(word[:i], word[i:]) for i in range(len(word) + 1)] deletes = [L + R[1:] for L, R in splits if R] transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1] replaces = [L + c +...
36dc0719a2b194248f4fea6039d0b05b771d8930
78,773
def quat2eul(quat) -> np.ndarray: """Euler Angles from Quaternion (4,N) --> (3,N) """ # Convert from (w,x,y,z) to (x,y,z,w) quat_scipy = np.concatenate([quat[1:4], quat[0:1]]) eul = R.from_quat(quat_scipy.T).as_euler('ZYX').T return np.squeeze(eul[::-1])
96d2395c3b244ff56cd4f7efe6717e57ae2365cd
78,774
def readFlow(fn): """ Read .flo file in Middlebury format""" # Code adapted from: # http://stackoverflow.com/questions/28013200/reading-middlebury-flow-files-with-python-bytes-array-numpy # WARNING: this will work on little-endian architectures (eg Intel x86) only! # print 'fn = %s'%(fn) with o...
6661f36a56dde926adcf527ab97fddd75d7ceee2
78,775
def fit_gui(): """Provide multi fit app without running it.""" return run_server( name="lsqfit basic example", fit_setup_function=make_fitter, run_app=False, )
f810942680d7b0dc96991ad28029992efb0e80cf
78,776
def average_bounding_box(box): """Average list of 4 bounding box coordinates to a midpoint.""" lng = 0 lat = 0 for i in range(len(box[0])): lng += box[0][i][0] lat += box[0][i][1] lat /= 4 lng /= 4 return [lng,lat]
ca934edcab7b658aaeb263509c5dfe048e912873
78,777
def construct_sort_part(model_cls, part): """Create a `Sort` from a single string criterion. `model_cls` is the `Model` being queried. `part` is a single string ending in ``+`` or ``-`` indicating the sort. """ assert part, "part must be a field name and + or -" field = part[:-1] assert fie...
26966174bc3ac75d5d30fc9d9dc56dfba3a5af87
78,778
def validate_core_post_api_response_content(response): """ Validates our project's standard JSON response. The standard response is a variation of the JSend standard: https://github.com/omniti-labs/jsend Looks like this: { "post_success": ... ,"post_msg": ... ...
bd1fa1720cc793708a9c150fb6470b94ac0d2b8c
78,779
def part_1(puzzle_lines): """Function which calculates the solution to part 1 Arguments --------- Returns ------- """ claims = set() double_claims = set() for line in puzzle_lines: claim_id, x0_start, x0_end, x1_start, x1_end = parse_line(line) for ii in ran...
a5f793eb26357fef7f163c91d11a3607fc5d2c29
78,780