content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def is_reviewed(protein_id): """Return True if the UniProt ID corresponds to a reviewed entry. Parameters ---------- protein_id : str The UniProt ID to check. Returns ------- True if it is a reviewed entry, False otherwise. """ return _strip_isoform(protein_id) in um.unipro...
684c22dedc79282fd7a6b58a2c6175079f508ab9
60,358
def matrix_compile(main: list, sub: list, pos: int): """ Compile sub-matrices into a main matrix. """ n = len(sub) total = len(main) if len(main) != 2 * n: print("ERROR: Cannot merge matrices of incompatible dimension. Stop.") return None results = [] if pos == 0: ...
0ee10948b1e4597dcf34176942b20d119aa12396
60,359
import logging def good_from(station: int, missing_days: int = 4, tabname: str = "readings", data: tuple = None) -> dict: """ Determines from which year we have almost consecutive data for each value. "Almost" will be assessed by the number of days where thae value is not available. A year is almost compl...
84d618b829efe0bb9d9ea6c82c1bd0230e820b36
60,360
def getGroups(datestring): """Utility function to get the parts of the datestring as a dict.""" if not isinstance(datestring, basestring): raise ParseError("Expecting a string %r" % datestring) m = ISO8601_REGEX.match(datestring) if not m: raise ParseError("Unable to parse date string %r" % datestring) ...
6d659ec4ba039b2efdb3b2bdecfb7244e91da5e8
60,361
import math def get_news(n: int = 100) -> pd.DataFrame: """Scrapes news from "https://www.coingecko.com/en/news?page={}" [Source: CoinGecko] Parameters ---------- n: int Number of news, by default n=100, one page has 25 news, so 4 pages are scraped. Returns ------- pandas.DataFram...
541f975ea37f9c92875395043481d567cdf9c041
60,362
def get_variables(hoc, obj, vartype=int(0)): """Get the variables associated with an object. :param hoc: is a hoc object such as would be obtained when importing neuron. :param obj: is the object from which to retrieve its variable names. This can be a Section, Segm...
9d304031bb0cf8bc553b12f688435220aaf842d3
60,363
def wtype(): """Returns the "window type" of $w. Important notes: * "window type" is not a tk concept; rather, Tk refers to a window's "class"; see "winfo class" for more on this context * "window type" is made up by me, and consists of a matching symbol; presently (2021-10-09), I...
31b97f3247f5e32fca761d14decb94a6ed3e7aeb
60,364
from re import I def compute_matrix_from_ops_two_qubit(ops, wire_order): """Given a list of two-qubit operations, construct its matrix representation.""" mat = qml.math.kron(I, I) for op in ops: if len(op.wires) == 1: if op.wires == qml.wires.Wires(wire_order[0]): mat...
3b326d0af015559a0112f31735c8208f632ddc28
60,365
def get_attribute_by_name(cls, group_name, attr_name, verbose_name=False, case_insensitive=False): """ Return the attribute of :obj:`Model` class :obj:`cls` with name :obj:`name` Args: cls (:obj:`class`): Model class group_name (:obj:`str`): name of attribute group attr_name (:obj:`str`...
9f0addc5ca0019366b934c9b88ba3bca11d3d082
60,366
def interface_r(polarization, n_i, n_f, th_i, th_f): """ reflection amplitude (from Fresnel equations) polarization is either "s" or "p" for polarization n_i, n_f are (complex) refractive index for incident and final th_i, th_f are (complex) propegation angle for incident and final (in radian...
baeaed3438725ac6492714bfca4221249476d226
60,367
def alignUnalignedSeqsFromFile(filename,WorkingDir=None,SuppressStderr=None,\ SuppressStdout=None): """Aligns unaligned sequences from some file (file should be right format) filename: string, the filename of the file containing the sequences to be aligned in a valid format. """ app = Clust...
60b3079a775597638cb47bd70993569f87d8657f
60,368
import math def C_26Al(depth, erosion, exposure, density, inheritance, P_0=35.): """ A model for profiles of 26Al concentration vs. depth. Notes ----- The following parameters are used (Braucher et al. 2003) 26Al radioactive decay: log(2) / 0.72e6 Contribution...
e15450f301c3e24a66337b87a48fbf90f350dc73
60,370
import time def Subdue(params, graph): """ Top-level function for Subdue that discovers best pattern in graph. Optionally, Subdue can then compress the graph with the best pattern, and iterate. :param graph: instance of Subdue.Graph :param params: instance of Subdue.Parameters :return: patter...
635be5cab9fcccaec040b268b0a21042dd07ca52
60,372
def func_proDATA(inlist): """ Pre-process input DATA list Parameter: inlist: 2D nested list sublist in an array [ symbol deltaTbM deltaTM deltaPM deltaVM nickName(as many as you can) ] Return: 3D nested list in a format, [ ...
2221a5399db0d6896ef8f7fb303834f91f654aed
60,373
import ibeis def find_installed_tomcat(check_unpacked=True, strict=True): """ Asserts that tomcat was properly installed Args: check_unpacked (bool): (default = True) Returns: str: tomcat_dpath CommandLine: python -m ibeis find_installed_tomcat Example: >>> ...
1c5488bc528207641826dc14f277ea0604357cbd
60,374
def get_tokens_of_doc(doc): """分词获得token""" sent_list = split_doc(doc) tokens = [] for sent in sent_list: tmp_tokens = tokenizer.segment(sent.strip()) for token in tmp_tokens: tokens.append(str(token).split('/')[0].strip()) return tokens
82b854411f56435634241fec3b76bb9e124ad58a
60,375
def normalize(img: np.ndarray, div255=True, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) -> np.ndarray: """ normalize using standard pytorch model normalization parameters expects RGB image with 0-255 pixels as input returns float type """ img = img.astype(float) if d...
6a835950494b824b918cb4b9bd4bf85e2f9723d9
60,376
def upper_case(string, **kwargs): """ 大写命名法 eg:USER_NAME """ return case_convert.upper_case(string, **kwargs)
1539031c0626d11b42ebc5583e84cf6e18f108f5
60,377
def response_for_courses_list(all_courses): """ Return the response for when courses are requested by the user. :param courses: :return: """ return make_response(jsonify({ 'status': 'success', 'courses': all_courses }))
a5af95a709dfe8dd3e7b19dfddbcf3aa99ecb3de
60,378
def move_ara_files(source_dir, dest_dir): """ old name of the collect_text_files function; renamed because the name does not reflect what function does; old name kept for backward compatibility """ return collect_text_files(source_dir, dest_dir)
7730715d1d77d1ed93b574f131bd5e114a09dad8
60,379
def normalize_and_dedupe_with_counts(dirty_urls): """ Takes a list of URLs, takes a count of them, sanitises them and returns a count of the sanitised URLs. Output is namedtuple of count pre-cleaning, count post-cleaning, and then the list of URLs. """ urls_entered = len(dirty_urls) cl...
02ab7c2365f8f3e5329baa8f4f9628003665b60f
60,380
def get_country_code(country_name): """根据指定的国家,返回pygal使用的两个字母的国别码""" for code, name in COUNTRIES.items(): if name == country_name: return code if country_name == "Hong Kong SAR, China": return 'hk' if country_name == "Korea, Dem. People’s Rep.": retur...
4f0b5c28027f409638004464b8af3a1c304c7a66
60,381
from fsspec import get_filesystem_class def can_be_local(path): """Can the given URL be used wih open_local?""" try: return getattr(get_filesystem_class(get_protocol(path)), "local_file", False) except (ValueError, ImportError): # not in registry or import failed return False
918646e65907d59bad1d40e8b5238865356e9fdf
60,383
def create_hdmedians_multiple_band_mosaic(dataset_in, clean_mask=None, no_data=-9999, dtype=None, intermediate_product=None, ...
3d9697325169693cebdc1a7c8f15d0d9e2080c3b
60,384
def get_ti16_config(): """Returns the ViT-S/16 configuration.""" config = get_base_config() config.update(dict( patch_size=(16, 16), hidden_size=192, intermediate_size=768, num_attention_heads=3, representation_size=192 )) return config
9ba8c89d858e4960944ef06cba1e81dfe04e3f8a
60,385
def lookup_unique_task_from_func(task_func, default_pipeline_name="main"): """ Go through all pipelines and match task_func to find a unique task Throw exception if ambiguous """ def unique_task_from_func_in_pipeline(task_func, pipeline): if task_func in pipeline.lookup: if len(...
39b70af87e019fc948563fcda20597b57e3bb292
60,386
def data_to_nameCat(LOC, quota, rank, CCA): """ Returns a dictionary of the category of a CCA """ final_dic = {} dic_quota = quota.dic #dictionary cat = "" for category, dic_CCAs in dic_quota.items(): #for each category for cca, quota in dic_CCAs.items(): #for each cca ...
96de92f435f8257425887d21c42d6b2a1359d747
60,388
def GenerateRSAKey(passphrase=None, key_length=2048): """Generate an RSA key and return tuple of pem strings for (priv,pub) keys.""" if passphrase is not None: passphrase_cb = lambda: passphrase else: passphrase_cb = None key = RSA.gen_key(key_length, 65537) priv_key = key.as_pem(passphrase_cb) bio ...
c40b0879f998875e3bea17af864daa37f98c27d5
60,390
def get_parsed_url(test_item): # type: (AnyMagpieTestItemType) -> ParseResult """ Obtains the parsed URL result from the test class web application implementation. """ app_or_url = get_app_or_url(test_item) if isinstance(app_or_url, TestApp): app_or_url = get_magpie_url(app_or_url.app.re...
ea57174e89349b43b66bebd0068f8e13e1173d82
60,391
def transformer_revnet_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder"): """A stack of transformer layers. Args: encoder_input: a Tensor encoder_self_attention_bias: bias Tensor for self...
b049e40bf3cdd08e476663e7494f426fa3339ea0
60,392
import utool as ut def inverable_unique_two_lists(item1_list, item2_list): """ item1_list = aid1_list item2_list = aid2_list """ unique_list1, inverse1 = np.unique(item1_list, return_inverse=True) unique_list2, inverse2 = np.unique(item2_list, return_inverse=True) flat_stacked, cumsum = ...
85b032e927be2615e3927f6f14b2bfa1ea5842f5
60,393
def sanitize_host(host): """Return the hostname or ip address out of a URL""" for prefix in ['https://', 'http://']: host = host.replace(prefix, '') host = host.split('/')[0] host = host.split(':')[0] return host
f00a79804624076c75e9b90c0da5b03888067a42
60,394
def compute_CCC(matrix, CCC_params): """ Compute causal complexity estimates for all pairs of rows of input matrix Estimates are derived as per 4 models: ETCP, ETCE, LZP and CCC Parameters ---------- matrix : np.ndarray, 2d, uint32 MxN matrix, C(M,2) rowpairs, with each row of length N...
28f3c3135cd354007e6d12979277528d6257fdcf
60,395
def team_user_names_query(after_cursor=None, team_name=None) -> gql: """A GraphQL query to get the list of user names within each organisation team. Args: after_cursor ([type], optional): Is the pagination offset value gathered from the previous API request. Defaults to None. team_name ([type],...
ab9a02b498c9f194002b03c28f45cf3f0545414b
60,396
def cut_rod_extend(p, n): """重构解""" r = [0] s = [0] for i in range(1, n + 1): res_r = 0 # 收益的最大值 res_s = 0 # 收益最大时对应方案的左边不切割部分的长度 for j in range(1, i + 1): if p[j] + r[i - j] > res_r: res_r = p[j] + r[i - j] res_s = j r.append...
e37d3300d2b79b1542dac46a723b0bff9668de09
60,397
def create_regions(algorithms: str, hash_file: HashFile): """ :param algorithms: the type of the algorithm to create the region :param hash_file: the hash file object """ if algorithms == "FIXED-SIZE": return create_fixed_regions(hash_file, 4) if algorithms == "CONTENT-DEFINED": ...
ae942c80c4fd22e9bb1addd49525542c41831f83
60,398
def _get_one_dimensional_median_and_error_bar( posterior, key, fmt=".2f", quantiles=(0.16, 0.84) ): """Calculate the median and error bar for a given key Parameters ---------- key: str The parameter key for which to calculate the median and error bar fmt: str, ('.2f') A format s...
11a2630720c0968e16e484388ebb48c9b8c0ec35
60,399
from multi_mesh.components.plotter import create_projection def find_good_projection( name: str = "default", central_longitude: float = 0.0, central_latitude: float = 0.0, satellite_height: float = 10000000.0, lat_extent=(-90.0, 90.0), lon_extent=(-180.0, 180.0), ): """ Function which ...
88b57ed8910d7dad5f0c2b2f641353def3f7bbc4
60,400
import torch def vectorize(ex, model): """Torchify a single example.""" word_dict = model.word_dict # Index words word_idx = [word_dict[w] for w in ex['sent']] if len(word_idx) == 0: print(ex) if model.args.model_type == 'cnn': pad = max(model.args.kernel_sizes) - 1 w...
7ec144048a4dd2cd61edab2b9c5de8697cbabc5b
60,401
def edit_sub(request, proj='', srt1='', id1='', srt2='', id2=''): """Edit subitem - let op: theoretisch kan dit bij edit_item() in """ # try: # do we have form data? data = request.POST # except AttributeError: # data = {} obj1 = funcs.get_object(srt1, id1) # my.rectypes[srt1].objects....
cae5ed830326f6ffd7ec83bcba549721da859a6e
60,402
def main(output, effective_tld_filename): """ effective_tld_filename is the effective TLD file to parse. A C++ array of { domain, exception, wild } entries representing the eTLD file is then printed to output. """ def boolStr(b): if b: return "true" return "false" for etld in getEffectiveT...
189449f07847d3121c46a5cf19795dba3f20bb98
60,403
def byte_convert_(number, original, new, printed=False): """Convert from one suffix to another suffix.""" if original == '': if new == '': None elif new == 'kb': number = number/1_000 elif new == 'mb': number = number/1_000_000 elif new == 'gb'...
ca5a12308e13fc46dd9bd1de91a7cde8207749e1
60,404
def filter_none(data, split_by_client=False): """This function filters out ``None`` values from the given list (or list of lists, when ``split_by_client`` is enabled).""" if split_by_client: # filter out missing files and empty clients existing_data = [ [d for d in client_data if d ...
7cc88ecdf7aba245f56598ee1094fed7c1f9f4f7
60,405
def cal_dist(weights, codes, keys_list=[-1, 0, 1]): """ Compute Distribution of CODES and generate results for PyPlot Args: weights (list): codes (list): keys_list (list): optional Returns: dist_dict (dict): a list of weights for each key """ dist_dict = dict.fromke...
52eb2bd39e0e403ecf130f486c34c51f7b71cd26
60,407
def plot_contours(clf, xx, yy, **params): """Plot the inverese-transformed decision boundaries for a classifier. Parameters ---------- ax: matplotlib axes object clf: a classifier xx: meshgrid ndarray yy: meshgrid ndarray params: dictionary of params to pass to contourf, optional ""...
615b453323a30b01bd7b3531c1915c201006e313
60,409
def test_funding_reorg_remote_lags(node_factory, bitcoind): """Nodes may disagree about short_channel_id before channel announcement """ # may_reconnect so channeld will restart; bad gossip can happen due to reorg opts = {'funding-confirms': 1, 'may_reconnect': True, 'allow_bad_gossip': True} l1, l2...
5be31fc732cc2ec6fab59ca2586c93a9094dffd0
60,410
def print_num(n): """ there must be a package that does this better. oh well""" if n >= 1000000000: return "{}{}".format(round(float(n) / 1000000000, 2), "B") elif n >= 1000000: return "{}{}".format(round(float(n) / 1000000, 2), "M") elif n >= 1000: return "{}{}".format(round...
7a6e241a60d81515b03e29de595cd192afde7d9a
60,411
def process_row(row): """Split a row into the original sentence, its corresponding summary and its rating. Args: row: a row in the MS dataset tsv file. Returns: current_original_sentence: the original sentence of the row current_shortened_sentences_list: a list of summaries corresponding to...
bff7a139e34e150210da73928a1dce1c51cfa8c2
60,412
def update_system(system): """ :param system: Dictionary with all the information of the system Dictionary system already has the indexes of the excited molecules 1. Looks for the neighbourhood of every centre. 2. Chooses a process for every exciton (KMC). This path variables include: dict(centre, p...
1981423d878e1ba5490f4d68ebc2f57989e31d4a
60,413
def relu(Z): """Applies relu function to an array/value Arguments --------- Z: float/int/array_like Original Value Returns ------- A: same shape as input Value after applying relu function """ return np.maximum(Z, 0)
6319f41a73b61911c5c72051cd80f2832b679932
60,414
import inspect def calculate_median(dataframe, *args, display=True, to_csv=False, to_html=False) -> DataFrame: """ This function calculates the median of all *numeric* columns within a Pandas dataframe. Alternately, users can specify a list of columns for which they would want to calculate the median. If ...
abccfc2cafd8ae241031f78dba30d4dd53c75c87
60,415
def have_double_impl(math_name): """ Check whether we have an implementation of the math function in libc for type double (e.g. logf or logl may not be available, but log may be). """ return math_suffix(math_name, double) in libc_math_funcs
76bf591fbe64f4a04805bbd485ff85c91de5fd83
60,416
def translate_name(name): """ 因为老数据的缘故,导致有些人名错了,需要翻译一下 :param name: 成员或组合名 :return: """ name_dict = { 'ruru_dambara': 'ruru_danbara', 'memi_tamura': 'meimi_tamura', 'chisaki_morito_m': 'chisaki_morito', 'musubu_funaki_a': 'musubu_funaki' } return name_dic...
52b852e9ecd2b1ac4b02288198f2c84986a1ed17
60,417
from typing import Union from typing import Iterable from datetime import datetime def query_unexpired_records(*, users: Union[User, Iterable[User]]=None, types: Union[RecordType, Iterable[RecordType]]=None ): """ :param users...
0c32b9a90e5f0f3b2892102db7484963cb2d4b0b
60,419
from bs4 import BeautifulSoup import re import logging def skip_team(soup: BeautifulSoup) -> bool: """Skip team if no players meet the minimum :param soup: BeautifulSoup object for a team :returns: True if the team should be skipped, False otherwise """ pattern = re.compile("No players meet the m...
023a0a0076f8751f5447acd30e09ac239736e751
60,421
def _battin_second_equation(u, h1, h2): """Battin's second equation. Parameters ---------- u: float The dependent variable. h1: float The first of the h coefficients. h2: float The second of the h coefficients. Returns ------- y: float The dependent ...
a00a6fe572b22cc4e27330667189325223d208fd
60,422
def compute_pca(data2d): """ Compute PCA using sklearn :param data2d: 2d array. PCA will be computed on non-zeros values. :return: coordsrc: 2d array: centered non-zero coordinates\ pca: object: PCA result.\ centermass: 2x1 array: 2d coordinates of the center of mass """ # round...
1bdbe46c4b709e1a72755ce1b9bfc630b52f886b
60,424
def le(n, alpha, beta=0): """ Draw from the Levy-stable ensemble :param n: size of random matrix :param alpha: parameter controlling the asymptotic power law of the distribution tails, between 0 and 2 :param beta: skew of the distribution, between -1 and 1 :return: random n by n matrix, drawn f...
90ae6fc4437acd29ca7125458a8923dce904da1a
60,425
def run_database_command(client, command): """ Run a database command using the "mysql -e" command :param client: String :param command: String database command :return: """ return mode.run_command( helper.get_command(client, 'mysql') + ' ' + generate_mysql_credentials( c...
c256dbcc5a1fe5a8fbdb41eef373570052bc5ede
60,426
def get_kw_active(df): """ returns the df with only enabled keyword status """ return select_col_equals(df,'Keyword state','enabled')
38a4bfa4c46a443e2b12c73b6d18055c771ad99b
60,427
import urllib def _urlencode(items): """A Unicode-safe URLencoder.""" try: return urllib.urlencode(items) except UnicodeEncodeError: return urllib.urlencode([(k, smart_str(v)) for k, v in items])
5a5e0d90e695433ba3774221d835e44b6e8ad749
60,428
def LLV(x: pd.Series, n: int): """ talib.MIN() """ LLV = [np.NAN] * (n - 1) for index in range(len(x)): if index < n - 1: continue else: window = x[index - n + 1:index + 1] LLV.append(min(window)) return pd.Series(LLV)
9a4591d841c5dbd8cbe704f695e65a2cf5b1a429
60,430
from typing import List def find_max_consecutive_ones(numbers: List[int]) -> int: """https://leetcode.com/problems/max-consecutive-ones/""" current_sum, max_sum = 0, 0 for value in numbers: current_sum += value if not value: max_sum = max(max_sum, current_sum) curr...
4b2f343553ff4756e21fe13d0b569e78add5b95d
60,431
def _amplitudeFromPeak(peak, x, y, radius, x_0=10, y_0=10): """ This function can be used to estimate an Airy disc amplitude from the peak pixel, centroid and radius. """ rz = jn_zeros(1, 1)[0] / np.pi r = np.sqrt((x - x_0) ** 2 + (y - y_0) ** 2) / (radius / rz) if r == 0.: return peak ...
a8af3d20fa069e5289feeede93c9969edbb1e88f
60,432
def get_user(token): """Find user authenticated by token or return None.""" return USERS.get(token)
c24deed25ec58c3c4495da46815a3e81e18a09d7
60,433
import urllib import json from datetime import datetime def by_location_id(id): """ retrieve next appointment by location id """ raw = urllib.request.urlopen(SCHED_URL + str(id)).read() appt = json.loads(raw.decode('utf-8')) ts = None if len(appt) > 0: ts = datetime.datetime.strptime(a...
7a8a90c11c75ca98529bd266c283fd2cb2b85b66
60,434
def sieve(limit): """ Returns a list of prime numbers up to but not including the given number. """ array = [True] * limit array[0] = array[1] = False primes = [] for (number, prime) in enumerate(array): if prime: primes.append(number) ...
2b31d824cf8058044fa58de62d88cadf2f473c17
60,435
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up LoadShedding as config entry.""" suburb = Suburb( id=entry.data.get("suburb_id"), name=entry.data.get("suburb"), municipality=entry.data.get("municipality"), province=entry.data.get("province...
e6efcd2f3eadb8b893ea9e9f616323f7d4caa0c0
60,436
from typing import List from typing import Tuple def key_exists(key: str, list_keys: List) -> Tuple[int, bool]: """ Finds a dict which has `key` defined from a list `list_keys` Args: key: the key to find list_keys: list of dicts Returns: index of key if found, whether the key...
65d0dbb35be5773a6435d639ab218ebe05638c7b
60,437
def combined_threshold_4(color_img, show_dbg=False): """Applies different methods to find the thresholds in the image.""" hls = cv2.cvtColor(color_img, cv2.COLOR_RGB2HLS) s_channel = hls[:, :, 2] gray = cv2.cvtColor(color_img, cv2.COLOR_RGB2GRAY) sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0) # Take th...
c8554a9c7fc4123bdd4e39ca57dab2600632c762
60,438
def mod_rand_invertible(p): """Return a random invertible element modulo p for p > 1""" assert p > 1 while True: a = randint(1, p - 1) # Check with the Euclidean algorithm if a is invertible a2, a1 = p, a while a1 > 0: a2, a1 = a1, a2 % a1 # Now a is in...
a0fdf33721a26bbca6517e98318e72d963a686f8
60,439
def normed_duration(catalog): """ One-line description Full description Parameters ---------- Returns ------- Examples -------- """ return (catalog['T']/day_hrs)/(catalog['period'])**(1/3.0)
ccdecf9aa4d90f05b8d00ca67bbea621ad604c0b
60,440
def total_ordering_from_cmp(cls): """Class decorator that fills in missing ordering methods from __cmp__. This lets us take a class defined for Python 2's ordering system (using __cmp__) and use it with minimal changes -- just a decorator -- in Python 3. This implementation is adapted from the Python 2 versio...
41d40e6175185a6314ef02fa7bdc58b416957706
60,441
from typing import Any from typing import Optional from typing import Callable def unmarshal_dict( obj: dict, cls: Any, allow_extra_keys: bool=True, ctor: Optional[Callable]=None, ): """ Unmarshal @obj into @cls Args: obj: The dict to unmarshal into @cls cls: ...
fde5db1f612f10266a5ec091e9052f7810f56713
60,442
def make_label_df(labels, behavior_subj, psychometric_params): """Turns labels into a parsed df""" label_df = pd.DataFrame(data={"stim_id": labels}) morphs.data.parse.stim_id(label_df) label_df["behave_data"] = False for dim, dim_group in label_df.groupby("morph_dim"): if dim in psychometri...
d7e9cc36c81570d22cc19132fc0213cf828757c8
60,446
def dwolla_get_url(url): """ A helper method for the DwollaClient to retreive any url Args: url (str): the url to retreive Returns: response """ try: result = DwollaClient.instance().token.get(url) return result.body except Exception as e: logger.err...
44a4ba68389a3d9017766f05bacb953d0a639947
60,447
from typing import Optional from typing import List from typing import Tuple def cat1_gt_cat2( df: pd.DataFrame, cat1: str, cat2: str, drop_levels: Optional[List[str]] = None ) -> Tuple[bool, pd.MultiIndex]: """ Checks that values from subset where `category == cat1` are greater than the values from s...
b3b105e2d2664575c6ea76e7897d8de97a1f570e
60,448
def extract_all(session_path, save=False, bpod_trials=False, settings=False): """Extract all datasets from habituationChoiceWorld Note: only the datasets from the HabituationTrials extractor will be saved to disc. :param session_path: The session path where the raw data are saved :param save: If True, ...
67a6ad5b5f4587b82176d33da9414d12c933fac2
60,449
def compute_norm_metrics(gradient): """Compute the metrics""" l1 = np.linalg.norm(gradient, ord=1) l2 = np.linalg.norm(gradient) Min = np.linalg.norm(gradient, ord=-np.inf) ## min(abs(x)) Max = np.linalg.norm(gradient, ord=np.inf) ## max(abs(x)) Mean = np.average(gradient) Skewness = skew(...
7adf9a26eddd56373ddbadf0688411bed11a1749
60,450
def perform_wavelet_transf(f, Jmin, dir, filter = "9-7",separable = 0, ti = 0): """"" perform_wavelet_transf - peform fast lifting transform y = perform_wavelet_transf(x, Jmin, dir, filter = "9-7",separable = 0, ti = 0); Implement 1D and 2D symmetric wavelets with symmetric boundary treatements, using ...
fbcfd39bd9564f9040a72436923133beeebac77d
60,451
def create_channel(n_or_buffer=1): """Create a new channel. As a conveinence, if n_or_buffer is a positive integer then creates a blocking buffer for the new channel. """ buf = n_or_buffer if isinstance(n_or_buffer, int): buf = create_blocking_buffer(n_or_buffer) elif buf.maxsize < ...
5ebb051159d46c4c5f81e9822b83c470ddeb7ca7
60,454
def filter(src): """Filter a comments and blank lines out of heredoc-style source string""" lines = src.strip().split("\n") lines = [L.split("#")[0].strip() for L in lines] # filter comments lines = [L for L in lines if len(L) > 0] # filter empty lines return lines
b77ee55f27835a4ba1210b08274969ee060c6c35
60,455
def lower_convex_hull ( bs ) : """Get lower convex hull for BSpline >>> bspline = ... >>> lower = bspline.lower_convex_hull () >>> lower = lower_convex_hull ( bspline ) - for all values of x: bspline(x) >= lower ( x ) """ return Ostap.Math.lower_convex_hull ( bs.bspline() )
55f6271ff34ad7c8c518ca708b0b9a8778126558
60,457
import random def death_with_chance(p_death: float) -> bool: """ Takes a float between 0 and 1 and returns a boolean if the player has survived (based on random chance) Returns True if death, False if survived """ return p_death > random.random()
ad2a88727369e703cee6c345882c873db2104827
60,458
from datetime import datetime def make_timestamp(): """ Generate a timestamp of the current time. returns: datetime.datetime: The current time. """ return datetime.datetime.now()
77999688b1af5982a3d4293b92b27549f6e6b1d2
60,459
def _radix_length(num: int) -> int: """Finds the number of digits for a number""" if num == 0: return 1 digits: int = 0 while num != 0: digits += 1 num = int(num / 10) return digits
3df84020aae22c7287596103c3615bb039d3e59f
60,460
import imp def _pip_install(): """If `pip` isn't installed, install it""" try: # Check if `pip` installed imp.find_module('pip') return True except ImportError: # If not installed, install it get_pip = """do shell script "python '{0}/get-pip.py'" """.format( ...
2083507180c3e8e28397bc83c5d642512f756b68
60,461
def service(): """ Returns an instance of the service """ return Clickstream()
eb3a28f47f0604778c193968cb4cf86c391bf732
60,462
def enabled(mapper, args) -> bool: """Determine if hooks are enabled for the current method.""" if not settings.HOOKS_ENABLED: return False if mapper is None: return False if mapper.manual: return False if args and isinstance(args[0], str): if args[0] in {"Meta", "...
520651b3d1109cc2044b5af001d36b0b63eabbc2
60,463
from typing import List from typing import Tuple from typing import Dict from typing import Union from typing import Callable def optimize_huggingface_model( model: PreTrainedModel, tokenizer: PreTrainedTokenizer, input_texts: List[str], batch_size: int, max_input_sizes: List[Tuple[int, ...]], ...
1cf643afb0b5710f87a7faa9a834061ec01a4bdb
60,464
def cli(ctx, result_id, file_path): """Download a result to a file Output: None """ return ctx.gi.result.download(result_id, file_path)
09a4a3d6ceab783e248ae53274c0bff8ad1fd249
60,465
def dummy_encode(df): """ Encode any dataframe column of type category or object. --- df: pandas dataframe """ columnsToEncode = list( df.select_dtypes(include=['category', 'object'])) df1 = df.copy() for feature in columnsToEncode: le = LabelEncoder() try: ...
6c65383f78727d62175a76aafbaf0140cfee6d8d
60,466
def main(reactor, jid, secret): """ Connect to the given Jabber ID and return a L{Deferred} which will be called back when the connection is over. @param reactor: The reactor to use for the connection. @param jid: A L{JID} to connect to. @param secret: A C{str} """ return Client(reactor...
59544915c9b83ae8cdee3d30a5ce1916f0978bcc
60,467
from pathlib import Path from typing import List def get_schema_metadata_error_messages(file_path: Path) -> List[str]: """Return a list of error messages for the table schema at file_path Undefined behaviour if the table schema is valid """ s = Schema(descriptor=file_path) return [err.message for...
9fe78512e188c14253fc86a60d45ff488bbef519
60,468
def create_holiday_calendar( weekend_mask=None, holidays=None, start_year=None, end_year=None): """Creates a holiday calendar. Note: providing bounds for the calendar, i.e. `holidays` and/or `start_year`, `end_year` yields a better-performing calendar. Args: weekend_mask: Boolean `Tensor` ...
fc76a842a293da3e03bad1d95813d1c49a317bc7
60,469
import copy def get_object_vector_to(cls, search_cls, subtype, avoid=None): """ Returns a list of all possible paths to the given class. Only searches classes that are subtype of the given class. """ # Does the name point to this class? Then we are done. if search_cls == cls: return [(...
a1b56bd59e96b4765cb0e75e496dc77eea94fa17
60,470
from typing import Any from typing import Optional import json import hashlib def gethash( value: "Any", hashtype: str = "sha256", encoding: str = "utf-8", json_encoder: "Optional[json.JSONEncoder]" = None, ) -> str: """Return a hash of `value`. Can hash most python objects. Bytes and bytearr...
cdec65a96b068ded153f86af29af53d68fe7b822
60,471
def subplot(nrows, ncols, plot_number, **kwargs): """ Returen a subplot axes positioned by the given grid definition. :param nrows, nrows: (*int*) Whree *nrows* and *ncols* are used to notionally spli the figure into ``nrows * ncols`` sub-axes. :param plot_number: (*int) Is used to identif...
8d60d315aab7ad77513225848e592fc0f96faae6
60,472
def sub(a: PipeNumeric, b: PipeNumeric) -> PipeNumeric: """ Pipeline node which subtracts b from a. :param a: parameter a :param b: parameter b :return: PipeNumeric """ if a.get_type() == b.get_type(): number_type = a.get_type() if isinstance(number_type, num.FloatingNumberTy...
6ce937bfad1ac96e7ebd5412f6707070996e0241
60,473
def get_raw_hcor(thing: dict) -> dict: """For an RAW hsilo-like dict, get only the non hmeta part. This function requires at leat one key that seems an hmeta, but if more than one exists, will also return None. Args: thing (dict): An HSilo-like dictionary Returns: dict: An dict wi...
8247758ef8c223158c6daca69334034bc3a7bc5b
60,474