content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def PNT2Tidal_Tv14(XA,chiA=0,chiB=0,AqmA=0,AqmB=0,alpha2PNT=0): """ TaylorT2 2PN Quadrupolar Tidal Coefficient, v^14 Timing Term. XA = mass fraction of object chiA = aligned spin-orbit component of object chiB = aligned spin-orbit component of companion object AqmA = dimensionless spin-induced quadrupol...
82eae87495785a5d0cce4d3f0ae5b6654395a42c
3,597,662
def calculate_variance(centers_of_intervals, quantities_of_velocities_per_interval, size, mean) : """" Обчислює дисперсію """ variance = 0 for i in range(0, centers_of_intervals.size) : normalized_value = centers_of_intervals[i] - mean variance += (normalized_value*normalized_value) * quantities_of_veloc...
d5fece546bc96ce41374b1d5b4fdc6041fd62f0a
3,597,663
import random def noisify(val, eps): """ Add a Gaussian White noise to function value """ val_noisy = (1 + random.gauss(mu=0,sigma=eps)) * (1-val) return val_noisy
40059eb7f87aa1b7b7096a1c84c7edef09cef4e1
3,597,664
import json def json_response(obj): """Returns a json response from a json serializable python object""" return Response( response=json.dumps(obj, indent=4, cls=AirflowJsonEncoder), status=200, mimetype="application/json" )
92fcff50fbdab37fb3b2c8ebbd9e22e8d2c265b6
3,597,666
def inceptionv4(**kwargs): """ InceptionV4 model from 'Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning,' https://arxiv.org/abs/1602.07261. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx ...
13e96e4cb7a02369b488e241004b2e4f7469b0ff
3,597,667
def flatten_list(l): """Flatten list of lists""" return [item for sublist in l for item in sublist]
a22bd5ee79aba47c058436886b435bca47ab1db1
3,597,668
def evaluate(tokenizer, nlp, valid_data, labels): """Evaluate model performance on a test dataset.""" texts, cats = zip(*valid_data) golds = [] # Use the model's ops module # to make sure this is compatible with GPU (cupy array) # or without (numpy array) scores = np.zeros((len(cats), len(l...
199277feff079fb6c16cc9ec2fe72d21113c30b3
3,597,669
def simple_line_plot(x, y, x_title: str, y_title: str, error=None) -> go.Figure: """Generates a simple line plot Args: x: x-axis data y: y-axis data x_title: x-axis title y_title: y-axis title error: Optional error vector. If given, continuous error bar will ...
b31751b3c1c1e7adaff0af842a4d0899ed81c81f
3,597,670
def create_container(id_ref, project_id=None, external_project_id=None): """Generate a Container entity instance.""" container = models.Container() container.id = id_ref container.name = 'test name' container.type = 'rsa' container_secret = models.ContainerSecret() container_secret.container...
030fd789befe3fd76cd8338d50aad3e90c5c23a8
3,597,671
def str_to_int(string): """Convert a string to a integer.""" string = str_to_str(string) try: return int(string) except ValueError: raise errors.ConfigurationError(f'{string!r} is not an integer')
b9e538c8640ec746ce5fd457569b08927c359095
3,597,672
def is_xml(maybe_xml): """Determine whether a given parameter is XML. Args: maybe_xml (str): An string that may or may not be valid XML. Returns: bool: A boolean indicating whether the given Dataset is valid XML. """ error_log = _check_is_xml(maybe_xml) return not error_log.c...
df6607c44ae92ac56df0c1ede837c4a5e50f2626
3,597,673
def __get_pod_service_list(pod_items): """ Returns a set of pod service_account names from the pod_list parameter :param pod_items: the list of pod_items from which to extract the name :return: set of pod names """ out_names = set() for pod_item in pod_items: if pod_item.spec.service...
da09b2bac32feade9ddbe822e64dacc3676cab88
3,597,675
def valuelist(items, field=None, enumeration=False): """ Common template tag to show a list of values in detail pages. :param field: Use this attribute on each item instead of their unicode representation :param enumeration: Show enumerations, useful to match those shown by ``mapentity/leaflet.enumerat...
077a54536ca0e7956998cf3d37bc1c9edecfc7b9
3,597,676
def create_model_uses( ns_, model_name = "Uses", include_used_as = False, used_as = "tax", schema_list = ["prj","dmt","dmf","dsi","dsr","usr","rec"], ): """ Uses model """ uses_dict = {} for schema in schema_list : doc_uses = { ...
902cbd87de468f69db125bb8ffaa636b41c0f3fb
3,597,677
def list_checker(token, q): """ List checker """ try: tainted = False if type(q) is list: try: track(q, False) for i in q: token_mapper(i) except Exception as e: common.logger.error("Problem with list parsing in list_checker method of findMethods.py: " + str(e)) else: try: if is_...
0f7b66c37e6c58a805cb14dd3b3ed37e7d7d4e71
3,597,679
def decode_rlp(data: str) -> list: """ Decode an rlp/b2b message to a list Args: the encoded prefixed sting Returns: the raw data contained in the rlp message """ rlp_enc = decode(data) return rlp.decode(rlp_enc)
5cb1cb1e2d6098f5ac1b835465c2627ac7ae9d39
3,597,680
def get_box_size(box): """Get box size""" x0, y0, x1, y1 = box sx = abs(x1 - x0) + 1 sy = abs(y1 - y0) + 1 return (sx, sy)
cefa6c8950687f0b4d244ebf9080ab29e358a7b2
3,597,681
def norm_uri(uri): """スキーマのURIを正規化する。 """ if not uri.endswith('.xsd') and uri.startswith('http://disclosure.edinet-fsa.go.jp/taxonomy/'): v = uri.split('/') name_space = v[4] yyyymmdd = v[5] name_cor = v[6] # uri : http://disclosure.edinet-fsa.go.jp/taxonomy/jppfs/2...
2c099f56a563dceca29a35fbc375e634d040ffb3
3,597,682
from astropy.table import Table def state_intervals(times, vals): """ Determine contiguous intervals during which the ``vals`` is unchanged. Returns an Astropy Table with a row for each interval. Columns are: * datestart: date of interval start * datestop: date of interval stop * duration: ...
6770f6bb9358cbeb1efe23a4707a45376021a32d
3,597,683
import math def tfidf_async(sg): """DOESN'T WORK!!!!""" all_genres = sg.all_genres df = pd.DataFrame(columns=["token"]+all_genres) global_vocab = set() for genre in all_genres: # do this async gvoc = sg.models[genre].vocab.counts for word in gvoc: global_vocab.a...
e6f2b40a17ed7d88cffbb600f164c5b3884a496e
3,597,685
from intake.container import container_map import requests import msgpack def open_remote(url, entry, container, user_parameters, description, http_args): """Create either local direct data source or remote streamed source""" if url.startswith('intake://'): url = url[len('intake://'):] payload = d...
b36d4cb14b0ed06970ed90b45e1bf222285488b3
3,597,686
def get_carousel_state(state=None, action_args=None): """Obtain carousel state from dictionary of States. Args: state: The original state to convert into new format. action_args: Action arguments. Returns: new_state: Return state in a new format. """ new_state = {"focus": N...
3faa57312e6a9fc3d8cb13c760e208866b781ef8
3,597,687
import scipy def martinis_flux_pulse(length: float, theta_i: float, theta_f: float, lambda_2: float, lambda_3: float=0, lambda_4: float=0, sampling_rate: float =2.4e9): """ Returns the pulse specified by Martinis and Geller as θ(t) specif...
8e1ef2657565b6859bef34a81fa938ae9080303e
3,597,688
import inspect def parse_maker_spec(maker): """Return MakerSpec of `maker`.""" sig = inspect.signature(maker) input_specs = [] for parameter in sig.parameters.values(): if parameter.annotation is sig.empty: # We should probably not err out here because maker could be ...
421bc9dcf655712b841d60b2d221b913ff6856fe
3,597,689
def validate_hash(hash_name, hash_value): """ Verifies if the given hash value matches the hash algorithm. :param hash_name: Name of the hash algorithm. :type hash_name: str :param hash_value: String with the hash value to check. :type hash_value: str :returns: True if the algorithm and v...
800022e536ffa7394a24c8a28ac6069d53cf2053
3,597,690
import urllib def should_add_headers(url): """ Should Typhos add the pre-configured headers when navigating to ``url``? Avoids sharing tokens with unrelated sites that the user may click. Parameters ---------- url : str The URL in question Returns ------- True if headers...
a8376b6e4ff544d51edd102517f7a24739384ae6
3,597,691
def index(request): """View function for home page of site.""" # Generate counts of some of the main objects num_postcards = Postcard.objects.all().count() # Number of Approved postcards num_postcards_approved = Postcard.objects.filter(approved=True).count() context = { ...
4a98bee7e469c2f5ce468ffb2628f1f1190c3c02
3,597,692
import scipy def compute_depth(mask,N): """ compute the depth picture """ im_h, im_w = mask.shape N = np.reshape(N, (im_h, im_w, 3)) # =================get the non-zero index of mask================= obj_h, obj_w = np.where(mask != 0) no_pix = np.size(obj_h) #37244 full2obj = np.z...
428a9f18f253308c5ed1bff5170594a0e03bf4d7
3,597,693
import array import warnings def save_list_as_array(list_obj, grp_target, compress_float=False): """ Works for both lists and tuples. Returns True if the saving was successful. """ N = len(list_obj) if N > 0: type0 = type(list_obj[0]) if type0 in (BasicNumTypes + (str, ndarray)):...
8040da38671f1db0348182128683388f8a8cbee5
3,597,694
import re def get_rotations(sequence): """ Given a cube sequence, find all 24 rotations of it. Need to fix this so it doesn't necessarily expect the U-first case. """ cubes = ["UBFLRD", "UFBRLD", "ULRFBD", "URLBFD", "DFBLRU", ...
47061c29c0692f44213603d6826c53852c0de8eb
3,597,698
from io import open def get_serial(): """Get serial number of Raspberry Pi.""" serial = None with open('/proc/cpuinfo', 'r') as fh: for line in fh.readlines(): if 'Serial' in line[0:6]: serial = line[10:26] if not serial: raise IOError('Serial not found,...
e865288aa620cc214804e4320e54f9c3be364d78
3,597,699
from datetime import datetime def unix_epoch_to_datetime(ux_epoch): """Convert number of seconds since 1970-01-01 to `datetime.datetime` object. """ return datetime.utcfromtimestamp(ux_epoch)
13edceec1631a2a3db06dad215380f609693f441
3,597,701
import torch def rf2_ex(FpFmZ, alpha): """ Propagate EPG states through an RF excitation of alpha (radians) along the y direction, i.e. phase of pi/2. in Pytorch INPUT: FpFmZ = 3xN vector of F+, F- and Z states. alpha = RF pulse flip angle in radians OUTPUT: FpFmZ = Updat...
926d3c7a9b5db418f63fbec30cf7a15b55e58885
3,597,703
def get_token(): """request to get token for session""" return {"token": encode_auth_token()}, 200
afb407bbc4e2ff0a14664bdf03afa6a6ced74a6d
3,597,705
import torch def point_edt2(point: torch.Tensor, grid: torch.Tensor) -> torch.Tensor: """Batched version of a Squared Euclidean Distance Transform for a D-dimensional point. Args: point: torch.Tensor of size [batch, *, D]. Each element is interpreted as a D-dimensional point (e.g. [row, col] or...
b186ccccd94d8b709974efd3b2ec5817c698f77b
3,597,706
def mergeuniques(xs, ys): """ merge lists xs and ys. Return a sorted result """ result = [] xi = 0 yi = 0 xs.sort() # sort clause unneeded if lists already sorted (as in instructions), but added for generalising ys.sort() while True: if xi >= len(xs): # If xs list is finish...
da02def34b5d347b43f26fbe1da6679f2e0db07a
3,597,707
def get_ip_input(): """Get IP address input.""" ip_addr = request.args.get("ip") return ip_addr
89a4706b98d2abedd99af6d278b4fa6ef2b5d0e4
3,597,708
def construct_coordinate_grid(model, coordinates, N=5): """Given n coordinates get the coordinate range and generate a coordinate grid of combinations using cartesian product. Parameters ---------- model: opensim.Model coordinates: list of string N: int (default=5) the number of ...
d6e54b5b570ef6687f8dc3e6236b3109db183e89
3,597,710
def real(x): """ A generic real-part operator with backend selector """ backend = getBackend(x) if backend == 'numpy': return np.real(x) elif backend == 'arrayfire': return arrayfire.arith.real(x) elif backend == 'scalar': return np.real(x) elif backend == 'list':...
bfc48e5a212e5197e9a0dfce1b27490221b1d34c
3,597,711
import scipy def mcnemar_midp(b, c): """Computes McNemar's test using the "mid-p" variant. This is based closely on: M.W. Fagerland, S. Lydersen, P. Laake. 2013. The McNemar test for binary matched-pairs data: Mid-p and asymptotic are better than exact conditional. BMC Medical Research Methodology 13...
1a92ae0a0c27ae3c0a2707b10c75c2fedd210ddd
3,597,712
def image_other_2_numpy(input_image, return_all=False): """ Loads image data and returns a numpy array. There will likely be many parameters to specify because of the strange quantization issues seemingly inherent in loading images. """ output_array = imread(input_image) i...
8b32b77b22f7d123e946941394127e7a5bc796c5
3,597,714
def search_choice(): """ accepts input strings exit/help or string within range of options. calls validation function on user input. calls functions relative to the user's choice. """ while True: user_input = input( Style.BRIGHT + Fore.BLUE + "\nType y...
9211a94ae230241eb76e6a0004b04b34189aaf86
3,597,715
from typing import Callable def auth_required(route: Callable[P, R]) -> Callable[P, R]: """ Protect the given route with an authentication check. Wrapping the route with this decorator ensures that the current user will be authenticated before the route call. :param route: The route to protec...
a5255bbd63e2bf36698fa73bb8de4571d9e7d08d
3,597,716
def op_transform(ops, affine_matrix): """ x, y, z -> x+1/2, y+1/2, z 0, 1/2, z -> 1/2, 0, z Args: ops: SymmOp object permutation: list, e.g. [0, 1, 2] Returns: the new SymmOp object """ matrix2 = affine_matrix.dot(ops.affine_matrix) return SymmOp(matrix2)
8313a9d07f05eea873d939be98227431feb7832c
3,597,717
def bottom_right(bbox=full_frame()): """Returns a bounding box covering the bottom right quadrant of ``bbox``.""" return right_half(bottom_half(bbox))
014a1c5ccd5c5efcccf25d2c8b29385b5eab188c
3,597,718
def Sword(): """ Creates a sword """ item = (ItemBuilder() .with_name('sword') .with_damage(2, 'piercing') .with_damage(2, 'slashing') .build()) return item
5959d040213b2228906bf2855c00f09ecc0bc062
3,597,719
import yaml def _read_conf(conf): """ Convert a YAML configuration into a dictionary :param conf: The configuration filename :return: A dictionary """ with open(conf, 'r') as stream: try: d = yaml.load(stream) return d except yaml.YAMLError as exc: ...
e44211e6423f3e5bb77df01fcaeec0d3653a227b
3,597,720
from functools import reduce def merge_dicts(*dicts): """ Merges dictionaries recursively. Accepts also `None` and returns always a (possibly empty) dictionary """ # if len(dicts) == 1: return dicts[0] return reduce(lambda a, nd: merge_two_dicts(a, nd if nd else {}), dicts, {})
52f22c6900e4bc6fda3dcd05ca16ccbf4521e6a3
3,597,722
import queue def bfs(G, start): """ A simple breadth-first search algorithm implemented using native queues. """ seen = set() q = queue.Queue() # we don't care about threading so don't ask Queue to block execution q.put_nowait(start) while not q.empty(): # get the waiting node, again ...
a15f6ef42f8873b108c2bd48c462175c77fdeee8
3,597,723
import re def content_type(response, **patterns): """Return name for response's content-type based on regular expression matches.""" ct = response.headers.get('content-type', '') matches = (name for name, pattern in patterns.items() if re.match(pattern, ct)) return next(matches, '')
c1071b2feae41bd049a26542d89414de54c06d8e
3,597,724
import gzip import csv def load_precomp_pairs_single_cohort(pairs_tsv_in): """ Load precomputed HPO pairs for a single cohorts, if optioned Returns a dict of sample counts keyed on sorted HPO term pairs """ counts = {} if pairs_tsv_in.endswith('.gz'): fin = gzip.open(pairs_tsv_in, 'r...
315628206445e58e9147a96cea0009d4b72b57ba
3,597,725
import re def convert_ip_address(ip_address: str): """ This function converts a ipv4 address in standard string format to a HEX representation :param ip_address: string with IPv4 address in format '192.168.0.1' :return: HEX representation of IPv4 address (string) """ if re.search('^((25[0-5]|...
1f50e6e2cb34325d07680a58090b58a1e00b745e
3,597,726
import base64 def base32_decode(encoded_bytes: bytes) -> str: """ Decodes a given bytes-like object to a string, returning a string >>> base32_decode(b'JBSWY3DPEBLW64TMMQQQ====') 'Hello World!' >>> base32_decode(b'GEZDGNBVGY======') '123456' >>> base32_decode(b'ONXW2ZJANRXW4ZZAMNXW24DMMV4C...
215a1aacd815fe11b93cf7dc6105abdff3492ab2
3,597,727
import re def replaceThreeOrMore(word): """ look for 3 or more repetitions of letters and replace with this letter itself only once """ pattern = re.compile(r"(.)\1{3,}", re.DOTALL) return pattern.sub(r"\1", word)
c052a082d74873da1a4c64dc035aeff429b29efd
3,597,728
def distance(p1: Point, p2: Point) -> float: """Calculate the distance between two points.""" d = ((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2) ** 0.5 if isinstance(d, complex): return d.real else: return d
a797f4fa89157a3b8c9800df5f3db0c1af293583
3,597,730
def getSensor(deviceName, pinNum): """ Function to get a specific sensor :param deviceName: The name of the device the sensor is connected to :type deviceName: String :param pinNum: The pin that the sensor is connected to (Note that in the case of mulitple pins, us...
0b69e073cdc66743f87b391d9d9eb383d26c8730
3,597,731
def compute_modules(Z_scores, min_gene_threshold=10, fdr_threshold=None, z_threshold=None, core_only=False): """ Assigns modules from the gene pair-wise Z-scores Parameters ---------- Z_scores: pandas.DataFrame local correlations between genes min_gene_threshold: int, optional m...
175e9cede54174cff4d84d93af819c7f396aff7a
3,597,732
def abre_arquivo(caminho): """Abre arquivos""" with open(caminho, 'r') as arquivo: return arquivo.read()
f09d970eb4f142e9576e22fdf72984656b7b14b9
3,597,733
from re import X def player(board): """ Returns player who has the next turn on a board. """ # Stores all the possible values of the board in variables total_places = sum(1 for i in board for j in i) empty_places = sum(1 for i in board for j in i if j == None) x_moves = sum(1 for i in boa...
dcdab52bde69c519d2082d962117b8ff7ea4184f
3,597,734
def get_b32_config(): """Returns the ViT-B/32 configuration.""" config = get_b16_config() config.name = 'ViT-B_32' config.patches.size = (32, 32) return config
78fd7469c4f162df4a6bdaa1f172339ea369a359
3,597,735
def luhn_validation(credit_card_number: str) -> bool: """ Function to luhn algorithm validation for a given credit card number. >>> luhn_validation('4111111111111111') True >>> luhn_validation('36111111111111') True >>> luhn_validation('41111111111111') False """ cc_number = cred...
4ed1cd788b54819ae4caead22bf34975a774dace
3,597,736
def _rescale_score_by_abs(score: float, max_score: float, min_score: float) -> float: """ Normalizes an attribution score to the range [0., 1.], where a score score of 0. is mapped to 0.5. :param score: An attribution score :param max_score: The maximum possible attributio...
a9ab337cc47f2d62de33c267bfe19c9522190db4
3,597,737
import itertools def tokenize_text_to_word_id(stringList, bert_preprocess): """ :param stringList: :param bert_preprocess: :return: """ tok = bert_preprocess.tokenize(tf.constant(stringList)) tok_list = tok.to_list() tok_list_flatten = [list(itertools.chain.from_iterable(_i)) for _i ...
39b837b752a90a0c80f612df82a70d4b01b34093
3,597,738
def citations_per_author(df, author_db): """ !!!! TAKES A LONG TIME --> PARALLELIZATION OR JUST DON'T INTEGRATE? Create an array of citations (one number per paper) for every author in a df. Used later on to compute the author h-index. Input: - df: - author_db: Output: - ...
ded7a3210e1eb63e81658800d0215e8d6ff6c229
3,597,739
def _create_curve_building_tensors(float_leg_start_times, float_leg_end_times, float_leg_daycount_fractions, fixed_leg_end_times, fixed_leg_cashflows, ...
458e4f0c2d615da7b6ee7039d5df0ecb783c081f
3,597,740
def star(num_nodes: int, directed: bool = False) -> NDArray: """ Returns a star graph. Parameters ---------- num_nodes : int The number of nodes directed : bool, optional If set to True, will return a directed graph, by default False Returns ------- NDArray ...
57a4bbf91786099f4375aa65181e46843f9ef693
3,597,741
from typing import List import torch def bootstrap( full_a_scores: List[float], full_b_scores: List[float], num_samples: int = 10_000, test_size: int = 1000, is_pairwise: bool = True, batch_size: int = 10_000, ) -> float: """ Uses bootstrap method to perform the...
dc891074a500ee8f8749625e08f3edc7c9acd0f7
3,597,742
import re def get_installation_cell(notebook, libs): """Return a cell for installing the additional libs""" lib_dict = dict(split_config_str(libs, 2)) lib1_re = re.compile('from ([_\w\d]+) import') lib2_re = re.compile('import ([_\w\d]+)') find_libs = [] for cell in notebook.cells: if ...
ce7eb9a5713d186156c05a693ce83f7175c1b7b5
3,597,743
def store_cloudconvert_credentials( clientID, clientTOKEN ): """ stores the CloudConvert_ API V2 credentials into the SQLite3_ configuration database. :param str clientID: the CloudConvert_ API V2 client ID. This is the *name* on the CloudConvert_ dashboard's API V2 key name. For example, for myself it is ...
b54a2a234e5b5585552b23fc16d78dffdeacff54
3,597,744
def __get_leading_zeros(fl): """Returns the number of leading zeros in a float decimal.""" if fl > 1.0: return 0 else: fl_splitted = str(fl).split(".")[-1] N_unstripped = len(fl_splitted) N_left_stripped = len(fl_splitted.lstrip("0")) return N_unstripped - N_left_stri...
c009a9dcf7f2c57baee3043acf9ec416679fab67
3,597,745
import yaml def load(path): """ :param path: config path :returns dict of {name -> loaded config file} from all liminal.y[a]ml files under given path """ if cached_files.get(path): return cached_files[path] config_entities = {} for file_data in find_config_files(path): w...
12c31adf4520b5c62a4ed1a71a33c39c01225d5b
3,597,746
def kraus_tensor(klist, n): """ Recursive function that produces every (n-fold) tensor product of a list of kraus operators. Parameters ---------- klist: list: a list of numpy.ndarrays, to tensor together n: int: the number of terms that must ultimately be tensored together into ...
2e8f6d2a24ec67936ccdd5b2e1464a3e972525ea
3,597,747
def twist_dict(nested): """ Make count dictionary with {cellbarcode : {taxonomyID : transcriptcount}} """ newdict = {} for ckey, tdict in nested.items(): for tkey, kvalue in tdict.items(): if ckey in newdict: if kvalue in newdict[ckey]: newdict[ckey][k...
81eba31fb7e5b6024b0d20a0d5e70c0f711d6b4d
3,597,748
import requests from bs4 import BeautifulSoup def queryAEC(postcode, extrapage): """ Queries the AEC url and returns soup. If extrapage is empty then we pass the soup to findFollowups before returning. """ url = "https://electorate.aec.gov.au/LocalitySearchResults.aspx?" url += "filter={0}&fil...
514cb9a471ab7636249eb7745c155bb23521e3ba
3,597,749
from typing import Optional def lru_cache_df(maxsize: Optional[int], typed: bool = False): """Least-recently-used cache decorator for pandas Dataframes. Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound f...
9e05bc2ba1f8c108f313ed9355ca5f34e595fdef
3,597,750
def df_to_dictionaries(df, change_names={}, include_index=True): """Returns a list of dictionaries, one dictionary for each row in the DataFrame 'df'. The keys of the dictionary match the DataFrame column names, except for any substitututions provided in the 'change_names' dictionary; {'old_name': 'ne...
f02c97318dda4da6bb082d3a78898584e27d353c
3,597,751
import warnings def _import_module(module_name, warn=True, prefix='_py_', ignore='_'): """Try import all public attributes from module into global namespace. Existing attributes with name clashes are renamed with prefix. Attributes starting with underscore are ignored by default. Return True on succ...
b1e4b9cf741c34aebe2e22e77ba9fc10f20d1682
3,597,753
def _s(word, seq, suffix='s'): """Adds a suffix to ``word`` if some sequence has anything other than exactly one element. word : str The string to add the suffix to. seq : sequence The sequence to check the length of. suffix : str, optional. The suffix to add to ``word`` ...
7ae7a7ac50b6b6ee92718877d242569d7339fd0e
3,597,754
def tri_cube(xx, idx): """ The tri-cube kernel estimated for xx values at indices idx (zero elsewhere) Parameters ---------- xx: float array Values of the function on which the kernel is computed. Typically, these are Euclidean distances from some point x0 (see do_kernel) ...
976d29b7202ee202057d666288ea23ae1ee4a86d
3,597,755
def createParaDomain2D(*args, **kwargs): """API change here .. use createParaMeshPLC instead.""" print("createParaDomain2D: API change: use createParaMeshPLC instead") return createParaMeshPLC(*args, **kwargs)
05d64eace6e80f129e0e4c4aafa0f98b4288caa8
3,597,756
from typing import Optional from typing import List def send_slack_invite(email: str, *, channels: Optional[List[str]] = None, resend: bool = True): """ Send a slack invitation to the provided email :param email: Email to send the invitation to :param channels: Channels for the u...
6bede9b586c1d813f9fc4c016fca145df18b9454
3,597,757
def read_mat_file_body_identification(path=None, channels_img=None,labels_name=None,dim=3,read_img=True,read_label=True,read_info=True): """Especially for network body identification Read mat file which contains image data and label data. Return images data and labels data with shape(x,y.z, channels) ...
43a61e232a3960110e8aa4c1beb92286ab0c7f87
3,597,758
def save_results_hdfs_directory(request, query_history_id): """ Save the results of a query to an HDFS directory. Rerun the query. """ response = {'status': 0, 'message': ''} query_history = authorized_get_query_history(request, query_history_id, must_exist=True) server_id, state = _get_query_handle_and...
8d10ea684a1647743a3728fcfe4042ab64081298
3,597,759
import json def jsonPP(obj): """ Get a pretty stringified JSON """ str = json.dumps(obj, indent=4, separators=(',', ': '), sort_keys=True) return str
5840f63d5579f84667294cddd0887d4233d8c7f7
3,597,760
def list_rows(layout_id): """ Show the page that lists the row definitions for a specified layout and is the entry point for editing them :param layout_id: ID for the layout for which to show the row definitions :return: The HTML for the row definition listing page """ layout = get_layout(layou...
428a0cb72f0474f90b2b6d37775c0b484a485a7b
3,597,761
def cpp_enum_to_int_impl(item): """Returns a C++-function for casting an enum value to an integer. """ cc = cpp.Code() cc += f'int to_int({item.cpp_enum.name} v){{' cc += 'return static_cast<int>(v);' cc += '}' cc += '' return cc
5458c64bc12497687fa06797e91807c24ec44b14
3,597,762
def label2Addr(label, labels): """ Return int address associated with label or None. label is a string, either digits or symbolic. Array labels has labels for all addresses in mem. """ if label.isdigit(): return int(label) if label in labels: return labels.index(label)
27b1fe8edce3aa4ee33f2e7ff25843fa958da620
3,597,763
def package_res_results(popt, pcov, res_number=None, flux_ramp_current_ua=None, parent_file=None, verbose=False): """ Do some parsing of the outputs of the fitting routine, wrap_simple_res_gain_slope_complex() Optionally prints to the console a human-readable blurb Inputs: - (popt, pcov) = (list of ...
8b4d65616b276a05f91603449ab98d69ab0adf4c
3,597,764
def get_analysis_result_with_data(): """Return an analysis result with one anlysis module for groups or samples.""" analysis_result = AnalysisResultMeta().save() analysis_result.set_module_status(MODULE_NAME, 'S') result_wrapper = getattr(analysis_result, MODULE_NAME).fetch() result_wrapper.data = c...
b75151c3a40abddf798ac87555ed2cee5d33a308
3,597,765
import re def _get_ocsp_uri(cert, executable=_DEFAULT_OPENSSL_EXECUTABLE_NAME, openssl_version=_DEFAULT_OPENSSL_VERSION): """Retrieve the OCSP URL from a certificate. Must be given as path on disk.""" _ = openssl_version cert_data = _run_openssl(['x509', '-in', cert, '-text'], executable=executable).decod...
c8b4b08086de280bb9c79200f09be96cebbe0372
3,597,767
def deep_transducer( model: str = 'conformer', quantized: bool = False, **kwargs ): """ Load Encoder-Transducer ASR model. Parameters ---------- model : str, optional (default='conformer') Model architecture supported. Allowed values: * ``'small-conformer'`` - SMALL size Google...
70711302edd0bb7e8e143193f04c8be7d0e5b040
3,597,769
def get_vocabs(datasets): """Build vocabulary from an iterable of datasets objects Args: datasets: a list of dataset objects Returns: a set of all the words in the dataset """ print("Building vocab...") vocab_intents = set() vocab_words = set() vocab_tags = set() f...
f1f284fd58e8139d4ad5d67551bf642a94556fba
3,597,771
def jobs_page(request): """ Renders the jobs page on the admin side URL: /admin/jobs :param request: :return: """ template = get_template('admin_jobs.html') return HttpResponse(template.render({}, request))
b084eae1a31adec69da169484c8f492320cd9ad8
3,597,773
import types from typing import Optional from typing import Collection from typing import Dict import operator def to_bag_of_terms( doclike: types.DocLike, *, by: str = "lemma_", # Literal["lemma_", "lemma", "lower_", "lower", "orth_", "orth"] weighting: str = "count", # Literal["count", "freq", "bi...
5238b5700687e0463c6f7b8bb91dfe3364d92f7a
3,597,774
def fixDict(json_data) -> dict: """Converts JSON data created by hass back into the dict we expect Specifically, the string keys will become numeric if possible""" correctedDict = {} for key, value in json_data.items(): if isinstance(value, list): value = [fixDict(item) if isinst...
acd2feb646fab5df2f77180097faa3cbf01eaeff
3,597,776
def get_model_cls(model_name): """"Selects Vivit model type.""" if model_name == 'vivit_multilabel_classification': return ViViTMultilabelClassificationModel elif model_name == 'vivit_classification': return ViViTClassificationModel elif model_name == 'vivit_multihead_classification': return ViViTMu...
8ffc99e8f03b560fec529e1f4ce5afa91ba8f4da
3,597,778
def mean_squared_error(y_true, y_pred, **args): """Mean squared error based on the `sklearn.metrics.mean_squared_error`_ function. More details here : `Mean squared error`_ .. _sklearn.metrics.mean_squared_error: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html#skl...
01a85494099cc767ace8f3c1258e416602c3f0a3
3,597,779
def _rd_rm_ ( rdir , name , cycle=';*') : """Delete an object from ROOT file/directory >>> rfile.rm( 'h1') >>> rfile.rm('mydir/h1') """ ## try : return _rd_delitem_ ( rdir , name , cycle ) except KeyError : return
ceb2e2d0257effc7afb0a367b31d7c76d6f8afc9
3,597,781
import datasets def fetch_aal_vascular_atlas(target_affine=np.diag((5, 5, 5))): """ Fetch the AAL brain atlas given its resolution. Parameters ---------- target_affine : np.array, (default=np.diag((5, 5, 5))), affine matrix for the produced Nifti images Return ------ mask_full_br...
9ccd18207bd0e2c54957ca0c73375bfbb0c4faea
3,597,783
def parse_bool_param(field): """Converts a url param to a boolean value""" return field.lower() == "true" if field else False
53530b60768be4f2fb9f4a7a62d6b49e4c079eeb
3,597,784