content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import sys def has_newer_fw( current_fw, bundled_fw ): """ :param current_fw: current FW version of a device :param bundled_fw: bundled FW version of the same device :return: True if the bundled version is newer than the current one """ current_fw_digits = current_fw.split( '.' ) bundled_f...
22daa7346981bdeed394518993dcbbb6b7835c23
3,644,800
def is_idaq(*args): """ is_idaq() -> bool Returns True or False depending if IDAPython is hosted by IDAQ """ return _ida_kernwin.is_idaq(*args)
5d18067b31be9c165a847815eb0bab92f89b0381
3,644,801
import requests import yaml def get_stats_yaml(): """grab national stats yaml from scorecard repo""" nat_dict = {} try: nat_yaml = requests.get(COLLEGE_CHOICE_NATIONAL_DATA_URL) if nat_yaml.ok and nat_yaml.text: nat_dict = yaml.safe_load(nat_yaml.text) except AttributeError...
045eeba3bfc42fa9e1821728260fd4d33e216731
3,644,802
import scipy def signal_interpolate(x_values, y_values, desired_length, method="quadratic"): """Interpolate a signal. Interpolate (fills the values between data points) a signal using different methods. Parameters ---------- x_values : list, array or Series The samples corresponding to t...
f3b20589591d2fed6054bbfc236894be70ddb598
3,644,803
from sys import modules def check_module(feature): """ Checks if a module is available. :param feature: The module to check for. :returns: ``True`` if available, ``False`` otherwise. :raises ValueError: If the module is not defined in this version of Pillow. """ if not (feature in modules...
c00680a135a2464cfb9a04ebae348c74d3c80271
3,644,804
def get_original(N: int = 64) -> np.ndarray: """radontea logo base image""" x = np.linspace(-N / 2, N / 2, N, endpoint=False) X = x.reshape(1, -1) Y = x.reshape(-1, 1) z = logo(X, Y, N) return np.array((z) * 255, dtype=np.uint16)
2bab08961d444f6ecfa097258872d02ae185944b
3,644,805
from typing import List def get_sql_update_by_ids(table: str, columns: List[str], ids_length: int): """ 获取添加数据的字符串 :param table: :param columns: :param ids_length: :return: """ # 校验数据 if not table: raise ParamError(f"table 参数错误:table={table}") if not columns or not isin...
ac70aa43aea4fad06ac2fd521239687040143b28
3,644,806
import os import nibabel as nib import numpy as np import torch def extract_roi( input_img, masks_location, mask_pattern, cropped_input, roi_list, uncrop_output, ): """Extracts regions of interest defined by masks This function extracts regions of interest from preprocessed nifti image...
434e7115032c7b4575b5fe8f046df4a6d3c49db8
3,644,807
import random import sympy def add_X_to_both_sides(latex_dict: dict) -> str: """ https://docs.sympy.org/latest/gotchas.html#double-equals-signs https://stackoverflow.com/questions/37112738/sympy-comparing-expressions Given a = b add c to both sides get a + c = b + c >>> latex_dict = {} ...
2ab0af9acbb09dcace00575a58afb66cebf2a07c
3,644,808
def init_var_dict(init_args, var_list): """Init var with different methods. """ var_map = {} _, max_val = init_args for i, _ in enumerate(var_list): key, shape, method = var_list[i] if key not in var_map.keys(): if method in ['random', 'uniform']: var_map[...
05a3bece9598426010466c27ce794eb7d2aea937
3,644,809
def get_member_name(refobject): """ return the best readable name """ try: member_name = refobject.__name__ except AttributeError: member_name = type(refobject).__name__ except Exception as error: logger.debug('get_member_name :'+str(error)) member_name = str(refobj...
103dfb1110ef8372e76b5ef734e842528d2b8f16
3,644,810
import os import warnings def _check_path(path=None): """ Returns the absolute path corresponding to ``path`` and creates folders. Parameters ---------- path : None, str or list(str) Absolute path or subfolder hierarchy that will be created and returned. If None, os.getcwd() is us...
2a1b18ac39cfd2573432911cd1aa6dfa5a740709
3,644,811
import warnings def _eval_bernstein_1d(x, fvals, method="binom"): """Evaluate 1-dimensional bernstein polynomial given grid of values. experimental, comparing methods Parameters ---------- x : array_like Values at which to evaluate the Bernstein polynomial. fvals : ndarray Gr...
5561d4099bd07b0fc75dcbf47c53f5ff589e2d9d
3,644,812
def exp_bar(self, user, size=20): """\ Returns a string visualizing the current exp of the user as a bar. """ bar_length = user.exp * size // exp_next_lvl(user.lvl) space_length = size - bar_length bar = '#' * bar_length + '.' * space_length return '[' + bar + ']'
575d475d602d0fdd4ded9eb2a139484c5d78887e
3,644,813
def linear(input_, output_size, scope=None, stddev=0.02, with_w=False): """Define lienar activation function used for fc layer. Args: input_: An input tensor for activation function. output_dim: A output tensor size after passing through linearity. scope: variable scope, if None...
8a5a4b06598d9c3c799c4a82d07a9d3d11962f23
3,644,814
from pathlib import Path import json import hashlib import math def generate_patches(patch_cache_location, axis, image_input_channels, brain_mask_channel, classification_mask, patch_size, k_fo...
d8dc0d1312acff05bfdbc56192ee3c7caeb65c86
3,644,815
def _parse_locals_to_data_packet(locals_dict): """ Takes the locals object (i.e. function inputs as a dict), maps keys from. TODO retire this function, its pretty hacky :param locals_dict: :return: parsed locals object """ if 'self' in locals_dict: locals_dict.pop('self') if 'kwa...
1d7c6e3bcc3ee86d42717690d3739cc624279bb6
3,644,816
from typing import Union from typing import Sequence from typing import List def query_user_joins(user_group: Union[User, Sequence[User], None]) \ -> List[JoinRecord]: """ :param user_group: User or user group as an iterable of users. :return: """ # Input validation user_list = [user_g...
5481e4512b7b28b0832f9fec00ef0cf4e7cfd5de
3,644,817
import os def is_running(process): """Returns True if the requested process looks like it's still running""" if not process[0]: return False # The process doesn't exist if process[1]: return process[1].poll() == None try: # check if the process is active by sending a dummy sig...
7dc002da5bbd87c5d8d8745fd49e6723478186c4
3,644,818
def rec_test(test_type: str): """ Rec test decorator """ def decorator(f): @wraps(f) def w(*args, **kwargs): return f(*args, **kwargs) # add attributes to f w.is_test = True w.test_type = test_type try: w.test_desc = f.__doc__.lstr...
94eca60bd4d3f96fd3346da5bcc2b70c3a167ace
3,644,819
def display_convw(w, s, r, c, fig, vmax=None, vmin=None, dataset='mnist', title='conv_filters'): """ w2 = np.zeros(w.shape) d = w.shape[1]/3 print w.shape for i in range(w.shape[0]): for j in range(w.shape[1]/3): w2[i, j] = w[i, 3*j] w2[i, j + d] = w[i, 3*j+1] w2[i, j + 2*d] = w[i, 3*j+...
87742ea0831f731e800385134379ce1b786b834f
3,644,820
def get_optional_list(all_tasks=ALL_TASKS, grade=-1, *keys) -> list: """获取可选的任务列表 :param keys: 缩小范围的关键字,不定长,定位第一级有一个键,要定位到第二级就应该有两个键 :param all_tasks: dict,两级, 所有的任务 :param grade: 字典层级 第0层即为最外层,依次向内层嵌套,默认值-1层获取所有最内层的汇总列表 :return: """ optional_list = [] # 按照指定层级获取相应的可选任务列表 if grade ...
ee54e65e724520d8ed9e3d994811c26ed2205add
3,644,821
def process_genotypes(filepath, snp_maf, snp_list=None, **kwargs): """ Process genotype file. :param filepath: :param snp_maf: :param snp_list: get specified snp if provided :param bool genotype_label: True if first column is the label of specimen, default False :param bool skip_none_rs: Tr...
501aa7b648d970b21dff1a4bd98102680e5ea774
3,644,822
import sys import subprocess def check_output(*cmd): """Log and run the command, raising on errors, return output""" print >>sys.stderr, 'Run:', cmd return subprocess.check_output(cmd)
e7108876e45a59a80785b9be696c71f1b4a5fe1e
3,644,823
def table_exists(conn, table_name, schema=False): """Checks if a table exists. Parameters ---------- conn A Psycopg2 connection. table_name : str The table name. schema : str The schema to which the table belongs. """ cur = conn.cursor() table_exists_sql =...
c9b698afbe795a6a73ddfb87b2725c3c4205f35e
3,644,824
import re def _dict_from_dir(previous_run_path): """ build dictionary that maps training set durations to a list of training subset csv paths, ordered by replicate number factored out as helper function so we can test this works correctly Parameters ---------- previous_run_path : str, Pa...
32d49b6ec6a8472a3864fc95cc52502a63038cdc
3,644,825
def aggregate_pixel(arr,x_step,y_step): """Aggregation code for a single pixel""" # Set x/y to zero to mimic the setting in a loop # Assumes x_step and y_step in an array-type of length 2 x = 0 y = 0 # initialize sum variable s = 0.0 # sum center pixels left = int(ceil(x_step[x]))...
d9cdad36c7eeff3581310d13bedce204e7431560
3,644,826
def simplify_datatype(config): """ Converts ndarray to list, useful for saving config as a yaml file """ for k, v in config.items(): if isinstance(v, dict): config[k] = simplify_datatype(v) elif isinstance(v, tuple): config[k] = list(v) elif isinstance(v, np.ndarr...
f3e8ae76e04479ed9b1b5fbd450edec20342e5a9
3,644,827
def _strict_random_crop_image(image, boxes, labels, is_crowd, difficult, masks=None, sem_seg=None, min_object_...
749107213a8bf34d2b159d38657a9c63af6699c3
3,644,828
def aggregate_by_player_id(statistics, playerid, fields): """ Inputs: statistics - List of batting statistics dictionaries playerid - Player ID field name fields - List of fields to aggregate Output: Returns a nested dictionary whose keys are player IDs and whose values a...
c137fc8820f8898ebc63c54de03be5b919fed97a
3,644,829
import pickle def loadStatesFromFile(filename): """Loads a list of states from a file.""" try: with open(filename, 'rb') as inputfile: result = pickle.load(inputfile) except: result = [] return result
cc2f64a977ff030ec6af94d3601c094e14f5b584
3,644,830
import tkinter def get_configuration_item(configuration_file, item, default_values): """Return configuration value on file for item or builtin default. configuration_file Name of configuration file. item Item in configuation file whose value is required. default_values dict of...
c077989d2d90468a80b27f32a68b827fbdb49b92
3,644,831
import os import logging def tflite_stream_state_external_model_accuracy( flags, folder, tflite_model_name='stream_state_external.tflite', accuracy_name='tflite_stream_state_external_model_accuracy.txt', reset_state=False): """Compute accuracy of streamable model with external state using TFLite...
d0209ef72ea6f29f5410b2c493f5286685b88e53
3,644,832
def sexa2deg(ra, dec): """Convert sexagesimal to degree; taken from ryan's code""" ra = coordinates.Angle(ra, units.hour).degree dec = coordinates.Angle(dec, units.degree).degree return ra, dec
3a016b1163c6ceda403cfe5c8d24467d1646c7aa
3,644,833
from theano import compile, shared import theano.tensor from theano.tensor import as_tensor_variable, TensorType def verify_grad(fun, pt, n_tests=2, rng=None, eps=None, out_type=None, abs_tol=None, rel_tol=None, mode=None, cast_to_output_type=False): """Test a gradient by Finite Di...
9fe5d2a8605b29d97f40d6830efeca6542a98603
3,644,834
import os def get_filenames(): """ get file names given path """ files = [] for file in os.listdir(cwd): if file.endswith(".vcf"): fullPath = cwd + file files.append(fullPath) return files
4f18e104f21e284e603d88fc96f2407932908356
3,644,835
import re def is_mismatch_before_n_flank_of_read(md, n): """ Returns True if there is a mismatch before the first n nucleotides of a read, or if there is a mismatch before the last n nucleotides of a read. :param md: string :param n: int :return is_mismatch: boolean """ is_mismatc...
1e41c67e29687d93855ed212e2d9f683ef8a88d7
3,644,836
from typing import Dict def get_county() -> Dict: """Main method for populating county data""" api = SocrataApi('https://data.marincounty.org/') notes = ('This data only accounts for Marin residents and does not ' 'include inmates at San Quentin State Prison. ' 'The tests timeser...
62fd267141e3cdcb3f5b81b78be2aafb1322335b
3,644,837
from typing import List import logging def optimize_player_strategy( player_cards: List[int], opponent_cards: List[int], payoff_matrix: Matrix ) -> Strategy: """ Get the optimal strategy for the player, by solving a simple linear program based on payoff matrix. """ lp = mip.Model("player_strat...
49e04138daea3c78f117e2372e54419384c70810
3,644,838
import traceback def address_book(request): """ This Endpoint is for getting contact details of all people at a time. We will paginate this for 10 items at a time. """ try: paginator = PageNumberPagination() paginator.page_size = 10 persons = Person.objects.all() ...
88ec5613a7433128a2d06665319a6e3fd83f870f
3,644,839
def decrement_items (inventory, items): """ :param inventory: dict - inventory dictionary. :param items: list - list of items to decrement from the inventory. :return: dict - updated inventory dictionary with items decremented. """ return add_or_decrement_items (inventory, items, 'minus')
253339e3a8f9ff49e69372dc99d8b8f626a3b98b
3,644,840
def global_ave_pool(x): """Global Average pooling of convolutional layers over the spatioal dimensions. Results in 2D tensor with dimension: (batch_size, number of channels) """ return th.mean(x, dim=[2, 3])
3f681e39041762ee2ca8bc52c542952eebd9b97c
3,644,841
import joblib def train_models(models, train_data, target, logger, dask_client=None, randomized_search=False, scoring_metric=None): """Trains a set of models on the given training data/labels :param models: a dictionary of models which need to be trained :param train_data: a dataframe containing all pos...
619565639eb4e59d5b639e3f687b43002c716800
3,644,842
import operator def get_output(interpreter, top_k=1, score_threshold=0.0): """Returns no more than top_k classes with score >= score_threshold.""" scores = output_tensor(interpreter) classes = [ Class(i, scores[i]) for i in np.argpartition(scores, -top_k)[-top_k:] if scores[i] >= score_thresho...
69c4e956cee796384fa74d12338f3fb2cc90ba31
3,644,843
def bag_of_words_features(data, binary=False): """Return features using bag of words""" vectorizer = CountVectorizer( ngram_range=(1, 3), min_df=3, stop_words="english", binary=binary ) return vectorizer.fit_transform(data["joined_lemmas"])
55ed963df31c2db79eaab58b585ad264a257c241
3,644,844
import time def duration(func): """ 计时装饰器 """ def wrapper(*args, **kwargs): print('2') start = time.time() f = func(*args, **kwargs) print(str("扫描完成, 用时 ") + str(int(time.time()-start)) + "秒!") return f return wrapper
c55a941574a92cbe70c9b265eaa39563b91ab45a
3,644,845
def enumerate_assignments(max_context_number): """ enumerate all possible assignments of contexts to clusters for a fixed number of contexts. Has the hard assumption that the first context belongs to cluster #1, to remove redundant assignments that differ in labeling. :param max_context_number:...
881723e2ca6a663821979a9029e03bb4f35195dc
3,644,846
def KL_monte_carlo(z, mean, sigma=None, log_sigma=None): """Computes the KL divergence at a point, given by z. Implemented based on https://www.tensorflow.org/tutorials/generative/cvae This is the part "log(p(z)) - log(q(z|x)) where z is sampled from q(z|x). Parameters ---------- z : (B, N...
6d509607b3d4d6c248544330af06f2ef92fc3739
3,644,847
def get_order_discrete(p, x, x_val, n_full=None): """ Calculate the order of the discrete features according to the alt/null ratio Args: p ((n,) ndarray): The p-values. x ((n,) ndarray): The covaraites. The data is assumed to have been preprocessed. x_val ((n_val,) ndarray): All possible...
de8f05d7a882c2917e618bf315a45969f55dbd16
3,644,848
def _read_txt(file_path: str) -> str: """ Read specified file path's text. Parameters ---------- file_path : str Target file path to read. Returns ------- txt : str Read txt. """ with open(file_path) as f: txt: str = f.read() return txt
5f0657ee223ca9f8d96bb612e35304a405d2339e
3,644,849
import os def init_statick(): """Fixture to initialize a Statick instance.""" args = Args("Statick tool") return Statick(args.get_user_paths(["--user-paths", os.path.dirname(__file__)]))
11c7c4a0ddfc0dcb0d4838aaabb6f130ecc6b11d
3,644,850
def dedupe(entries): """ Uses fuzzy matching to remove duplicate entries. """ return thefuzz.process.dedupe(entries, THRESHOLD, fuzz.token_set_ratio)
d5d56f2acc25a107b5f78eefc4adc71676712f98
3,644,851
import binascii def generate_openssl_rsa_refkey(key_pub_raw, # pylint: disable=too-many-locals, too-many-branches, too-many-arguments, too-many-statements keyid_int, refkey_file, key_size, encode_format="", password="nxp", ...
ca3acdcf4fe615378f2f7088d015a7acbc58b7ff
3,644,852
import select async def fetch_ongoing_alerts( requester=Security(get_current_access, scopes=[AccessType.admin, AccessType.user]), session=Depends(get_session) ): """ Retrieves the list of ongoing alerts and their information """ if await is_admin_access(requester.id): query = ( ...
721deaac7cca5f6589417f07d66a83111a062134
3,644,853
def breweryBeers(id): """Finds the beers that belong to the brewery with the id provided id: string return: json object list or empty json list """ try: # [:-1:] this is because the id has a - added to the end to indicate # that it is for this method, removes the last charact...
f2d8824ad49ffeeec68077cb5e0ed143f4603d4e
3,644,854
def min_max_date(rdb, patient): """ Returns min and max date for selected patient """ sql = """SELECT min_date,max_date FROM patient WHERE "Name"='{}'""".format(patient) try: df = pd.read_sql(sql, rdb) min_date, max_date = df['min_date'].iloc[0].date(), df['max_date'].iloc[0].date() ex...
7f08f42bd7dd9742bef300f5f7009807e47b7f23
3,644,855
def integrate(f, a, b, N, method): """ @param f: function to integrate @param a: initial point @param b: end point @param N: number of intervals for precision @param method: trapeze, rectangle, Simpson, Gauss2 @return: integral from a to b of f(x) """ h = (b-a)/(N) if method == "...
e716733160fd46943de3518e573215b3cf058113
3,644,856
def sum_naturals(n): """Sum the first N natural numbers. >>> sum_naturals(5) 15 """ total, k = 0, 1 while k <= n: total, k = total + k, k + 1 return total
0ef1ff7e8f0f2df522c73d6d4affc890ba4ad2fa
3,644,857
def load_data(data_map,config,log): """Collect data locally and write to CSV. :param data_map: transform DataFrame map :param config: configurations :param log: logger object :return: None """ for key,df in data_map.items(): (df .coalesce(1) .write .csv(f'{co...
2b690c4f5970df7f9e98ce22970ce3eb892f15bc
3,644,858
import yaml import os import time import torch def get_config(config_file, exp_dir=None, is_test=False): """ Construct and snapshot hyper parameters """ # config = edict(yaml.load(open(config_file, 'r'), Loader=yaml.FullLoader)) config = edict(yaml.load(open(config_file, 'r'), Loader=yaml.FullLoader)) # crea...
69d57ecf8538e1ca89124b148b068ec58098e046
3,644,859
import logging def _filter_credential_warning(record) -> bool: """Rewrite out credential not found message.""" if ( not record.name.startswith("azure.identity") or record.levelno != logging.WARNING ): return True message = record.getMessage() if ".get_token" in message: ...
bc9d2a96ccadfbdb297af86bbdf0f80ab8d2dafa
3,644,860
import importlib def import_module_from_path(mod_name, mod_path): """Import module with name `mod_name` from file path `mod_path`""" spec = importlib.util.spec_from_file_location(mod_name, mod_path) mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod
18891db514b4f1e41bce6de69f5b66fbf51d06e5
3,644,861
def preprocessing(text, checkpoint_dir, minocc): """ This time, we cannot leave the file as it is. We have to modify it first. - replace "\n" by " \n " -> newline is a word - insert space between punctuation and last word of sentence - create vocab, but only for those words that occur more than once...
f3dd597ac144d1c52ca2a65852ef59f2cee63d8b
3,644,862
def dwave_chimera_graph( m, n=None, t=4, draw_inter_weight=draw_inter_weight, draw_intra_weight=draw_intra_weight, draw_other_weight=draw_inter_weight, seed=0, ): """ Generate DWave Chimera graph as described in [1] using dwave_networkx. Parameters ---------- m: int ...
cec6232d1f3413b6cedd74d909e8d9fa03d9b43f
3,644,863
def extract_first_value_in_quotes(line, quote_mark): """ Extracts first value in quotes (single or double) from a string. Line is left-stripped from whitespaces before extraction. :param line: string :param quote_mark: type of quotation mark: ' or " :return: Dict: 'value': extracted value; ...
4f614cbbb3a1a04ece0b4da63ea18afb32c1c86b
3,644,864
def dynamic(graph): """Returns shortest tour using dynamic programming approach. The idea is to store lengths of smaller sub-paths and re-use them to compute larger sub-paths. """ adjacency_M = graph.adjacency_matrix() tour = _dynamic(adjacency_M, start_node=0) return tour
06d1adcadc6456aa29a7c0d176329f9d1569bf58
3,644,865
import yaml def read_login_file(): """ Parse the credentials file into username and password. Returns ------- dict """ with open('.robinhood_login', 'r') as login_file: credentials = yaml.safe_load(login_file) return credentials
16ef8a74c9523ac0809e80995069c3bbc0e8f8c0
3,644,866
def flatten(ls): """ Flatten list of list """ return list(chain.from_iterable(ls))
afab4515644ce340a73f5a5cf9f97e59fa8c4d7e
3,644,867
def gaussian_kernel(size, size_y=None): """ Gaussian kernel. """ size = int(size) if not size_y: size_y = size else: size_y = int(size_y) x, y = np.mgrid[-size:size+1, -size_y:size_y+1] g = np.exp(-(x**2/float(size)+y**2/float(size_y))) fwhm = size fwhm_aper = photut...
6752c4fc9355507d3b411515b8c687dc02b81d2b
3,644,868
from typing import Any def parse_property_value(prop_tag: int, raw_values: list, mem_id: int = 0) -> Any: """ Parse property raw values :param prop_tag: The property tag, see 'PropertyTag' enum :param raw_values: The property values :param mem_id: External memory ID (default: 0) """ if pr...
fc8d54a3f8b8ca762acdc5f6123749236e4eaeb3
3,644,869
from typing import Optional from typing import Iterator from typing import List from typing import Tuple def scan_stanzas_string( s: str, *, separator_regex: Optional[RgxType] = None, skip_leading_newlines: bool = False, ) -> Iterator[List[Tuple[str, str]]]: """ .. versionadded:: 0.4.0 Sc...
f68694ce344b738f23b689b74d92f7ab4c20b237
3,644,870
def format_dependency(dependency: str) -> str: """Format the dependency for the table.""" return "[coverage]" if dependency == "coverage" else f"[{dependency}]"
981a38074dbfb1f332cc49bce2c6d408aad3e9e2
3,644,871
def _addSuffixToFilename(suffix, fname): """Add suffix to filename, whilst preserving original extension, eg: 'file.ext1.ext2' + '_suffix' -> 'file_suffix.ext1.ext2' """ head = op.split(fname)[0] fname, ext = _splitExts(fname) return op.join(head, fname + suffix + ext)
2fc0a16f6f8b8be1f27fd7ff32673ed79f84fccb
3,644,872
import re def parse_into_tree(abbr, doc_type = 'html'): """ Преобразует аббревиатуру в дерево элементов @param abbr: Аббревиатура @type abbr: str @param doc_type: Тип документа (xsl, html) @type doc_type: str @return: Tag """ root = Tag('', 1, doc_type) parent = root last = None token = re.compile(r'([\+>...
8bb0ecaa9b2a2e9ce41882b8f140442f28f3c922
3,644,873
import os import csv def map_pao1_genes(gene_list): """Takes a list of PAO1 genes and returns the corresponding PA14 names.""" pa14_pao1_mapping = dict() mapping_path = os.path.join(os.getcwd(), 'data', 'ortholuge_pa14_to_pao1_20190708.tsv') with open(mapping_path) as mapping: reader = csv.rea...
675cf26d259bee1f6ff148f1a4ad2a71b8253ef5
3,644,874
def banner(): """Verify banner in HTML file match expected.""" def match(path, expected_url=None, expected_base=None): """Assert equals and return file contents. :param py.path.local path: Path to file to read. :param str expected_url: Expected URL in <a href="" /> link. :param ...
54777fe767075561cbb20c3e7ab88ca209fa8c87
3,644,875
import tqdm import operator def rerank(x2ys, x2cnt, x2xs, width, n_trans): """Re-rank word translations by computing CPE scores. See paper for details about the CPE method.""" x2ys_cpe = dict() for x, ys in tqdm(x2ys.items()): cntx = x2cnt[x] y_scores = [] for y, cnty in sorte...
57d9c5012341acf89e92ffd6df29688af5d6965f
3,644,876
def ParallelTempering(num_sweeps=10000, num_replicas=10, max_iter=None, max_time=None, convergence=3): """Parallel tempering workflow generator. Args: num_sweeps (int, optional): Number of sweeps in the fixed temperature sampling. num_replicas (int, optional):...
48b62b2814f67b66823fc1c35024eaab6cde7591
3,644,877
def get_document_info(file): """ Scrape document information using ChemDataExtractor Scrapers :param file: file path to target article :type file: str :return: list of dicts containing the document information """ if file.endswith('.html'): file_type = 'html' elif file.endswith(...
5d5697ce9a7916920c938a3cff17fdeda8b5f81b
3,644,878
def qlog(q): """ Compute logarithm of a unit quaternion (unit norm is important here). Let q = [a, qv], where a is the scalar part and qv is the vector part. qv = sin(phi/2)*nv, where nv is a unit vector. Then ln(q) = ln(||q||) + qv / ||qv|| * arccos(a / ||q||) Therefore for a unit quaternion, t...
80e01568cc5fe2ab2c7d11bdd642906374992985
3,644,879
from datetime import datetime def trx(): """Response from ADN about current transaction APPROVED/DECLINED and showing Receipt of transaction""" trx = web.trxs[-1] trx.shoppingCartUuid = request.args.get('shoppingCartUuid', default = "", type = str) trx.mediaType = request.args.get('mediaType', default...
4ffa01c2d6682a6320870ac158f564c37aa5a32e
3,644,880
def get_counts_by_domain(df): """ Parameters: df (pandas.Dataframe) - form of `get_counts_df` output Returns: pandas.Dataframe """ columns = ['study', 'study_label', 'domain_code', 'domain_label'] df2 = df.groupby(columns, as_index=False)[["count", "subjects"]].max() retur...
544aaa734858209c36c84d87bb6beb05761a5194
3,644,881
def batch_cosine_similarity(x1, x2): """ https://en.wikipedia.org/wiki/Cosine_similarity """ mul = np.multiply(x1, x2) s = np.sum(mul, axis=1) return s
6ed5e4ca426cc61d25dd272f92ba9220186bfd8e
3,644,882
def plot(ax, x, y): """Plot """ return ax._plot(x, y)
90cc2616d21e3c1239524437f653f85602c1984b
3,644,883
def concatenatePDFs(filelist, pdfname, pdftk='pdftk', gs='gs', cleanup=False, quiet=False): """ Takes a list or a string list of PDF filenames (space-delimited), and an output name, and concatenates them. It first tries pdftk (better quality), and if that fails, it tries ghostscr...
3e138e84db9650af3afbbab4d904dc3a4cb581c9
3,644,884
def get_module_offset( process_id: int, process_name: str ) -> Address: """Returns an Adress with the base offset of the process. Args: process_id (int): PID process_name (str): Name of the process. Case does not matter. Returns: Address: Adress with the base offset of the ...
09e0775213e4a32f1ea786ad9d1184e7f4dbd7cf
3,644,885
from typing import Sequence def sequence_to_header(sequence: Sequence[Bytes]) -> Header: """ Build a Header object from a sequence of bytes. The sequence should be containing exactly 15 byte sequences. Parameters ---------- sequence : The sequence of bytes which is supposed to form th...
b1c4040b216162777e33bbbab0f7774b8b02af91
3,644,886
def makeASdef(isd_id, as_id_tail, label, public_ip, is_core=False, is_ap=False): """ Helper for readable ASdef declaration """ return ASdef(isd_id, _expand_as_id(as_id_tail), label, public_ip, is_core, is_ap)
19bc51a648ac558f524f29744e1574a245e50cf2
3,644,887
from netneurotools.utils import check_fs_subjid from netneurotools.datasets import fetch_fsaverage from netneurotools.datasets.utils import _get_data_dir import os def _get_fs_subjid(subject_id, subjects_dir=None): """ Gets fsaverage version `subject_id`, fetching if required Parameters ---------- ...
ce4599ab875c7a33aa71cb9bc07143a04b6b2643
3,644,888
def EnableTrt(mod, params=None, trt_version=None): """Converts the "main" function in the module into one that can be executed using TensorRT. If any of the operators are not supported by the TensorRT conversion, the unmodified program will be returned instead. Parameters ---------- mod: Module...
c3cac75de48e2c2a9af30ce427bc57d86a56dbc4
3,644,889
import cupy def _setup_cuda_fft_resample(n_jobs, W, new_len): """Set up CUDA FFT resampling. Parameters ---------- n_jobs : int | str If n_jobs == 'cuda', the function will attempt to set up for CUDA FFT resampling. W : array The filtering function to be used during resamp...
34a949250239b5334650b89d6566b81460079591
3,644,890
def sentensize(text): """Break a text into sentences. Args: text (str): A text containing sentence(s). Returns: list of str: A list of sentences. """ return nltk.tokenize.sent_tokenize(text)
ae16aff476842c8e0fc2fa2506b68ad60dc603f0
3,644,891
def tokenize(texts, context_length=77): """ Returns the tokenized representation of given input string(s) Parameters ---------- texts : Union[str, List[str]] An input string or a list of input strings to tokenize context_length : int The context length to use; all CLIP models use...
1fe73425cb30f0f6fbce6caa740f118ee9591347
3,644,892
def _int64_feature_list(values): """Wrapper for inserting an int64 FeatureList into a SequenceExample proto, e.g, sentence in list of ints """ return tf.train.FeatureList(feature=[_int64_feature(v) for v in values])
edf4605c1dd9ad45d3a2508122b85213657f56cb
3,644,893
def read_relative_pose(object_frame_data: dict) -> tf.Transform: """ Read the pose of an object relative to the camera, from the frame data. For reasons (known only to the developer), these poses are in OpenCV convention. So x is right, y is down, z is forward. Scale is still 1cm, so we divide by 10...
dae13aa0a10db2133f87c399ec90113ef157a210
3,644,894
import select def upsert_task(task_uuid: str, task: Task) -> Task: """Upsert a task. It is used to create a task in the database if it does not already exists, else it is used to update the existing one. Args: task_uuid: The uuid of the task to upsert. task: The task data...
7fbf296377fb1e4e59b7c9884c6191ff2b0a273b
3,644,895
def shuffle_entries(x, entry_cls, config=None, value_type=sgf2n, reverse=False, perm_size=None): """ Shuffle a list of ORAM entries. Randomly permutes the first "perm_size" entries, leaving the rest (empty entry padding) in the same position. """ n = len(x) l = len(x[0]) if n & (n-1) !=...
827506de7e572b1df1b210ccfb990db5839b5273
3,644,896
import os import random import logging import sys def file(input_file): """Import colorscheme from json file.""" theme_name = ".".join((input_file, "json")) user_theme_file = os.path.join(CONF_DIR, "colorschemes", theme_name) theme_file = os.path.join(MODULE_DIR, "colorschemes", theme_name) util....
9439f44c6d71b52d800fd95f0269e46f0185a8fa
3,644,897
import json def entities(request): """Get entities for the specified project, locale and paths.""" try: project = request.GET['project'] locale = request.GET['locale'] paths = json.loads(request.GET['paths']) except MultiValueDictKeyError as e: log.error(str(e)) ret...
686f9298302d30e89ad0d34ed4c0c96d22fd455d
3,644,898
import json def info(request, token): """ Return the HireFire json data needed to scale worker dynos """ if not settings.HIREFIRE_TOKEN: return HttpResponseBadRequest( "Hirefire not configured. Set the HIREFIRE_TOKEN environment variable on the app to use Hirefire for dyno scaling...
7164d7f19b14ef601480484d6182f4b62cc250bf
3,644,899