content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def load_sktime_ts_file(path, normalize=True): """ Load a dataset from .ts files Parameters ---------- path : string Path to the folder containing the .ts file. Dataset name should be specified at the end of path to find files as "dataset_TRAIN.ts" and "dataset_TEST.ts" ...
7b1a56ac15ce6f145e88e706dbb76d9ce85b725f
64,470
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ reprompt_text = "" session_attributes = {} card_title = "Welcome" speech_output = "This skill grabs temperature data from your raspberry pi. " should_end_session = "...
a4a773a39ca3015442716f4003ffb6e834945549
64,471
def parse_bql_string_pos_1(string): """Return ``(phrase, pos)`` for the first BQL phrase in `string`. May not report parse errors afterward. """ for phrase, pos in parse_bql_string_pos(string): return (phrase, pos) return None
c444a0a7cd827b3be07bccb83689f6a8ab6b4153
64,472
def keyjar_init(instance, key_conf, kid_template=""): """ Initialize KeyJar. Configuration of the type: keys = [ {"type": "RSA", "key": "cp_keys/key.pem", "use": ["enc", "sig"]}, {"type": "EC", "crv": "P-256", "use": ["sig"]}, {"type": "EC", "crv": "P-256", "use": ["enc"]} ]...
c134c97d8b09fc8506a551425732c417463952a5
64,473
def mnist_model(input_shape): """Creates a MNIST model.""" model = tf.keras.models.Sequential() model.add( tf.keras.layers.Conv2D( 32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu')) model.add(tf.keras.layers.Max...
26c42d1b24ec6cdb7b17c57e073fc41e2bf8e050
64,474
def index(): """Display the single page app""" images = [] uploads_ref = firestore_client.collection(u'uploads') uploads = uploads_ref.stream() for upload in uploads: images.append(upload.to_dict()) return render_template('index.html', images=images, qotd=getquote())
0c32203ae5b428eefb99286b17aee2f9f25db44e
64,475
def get_pos_trans_misc_minimal(observation): """ No toes_l, talus_l and pros_foot_r """ observation_array = [] body_keys = ["body_pos"] for body_key in body_keys: for body_part in ["pelvis", "head", "torso", "tibia_l", "pros_tibia_r", "femur_l", "femur_r", "calcn_l...
ccb9768798114ebd70924ebdb11d19fa9955694e
64,476
def _read_split(ext): """ Reads the train/test/val splits :param ext: string for "train", "val", or "test" :return: """ with open('{}/{}.txt'.format(SPLITS, ext), 'r') as f: return [_fix_fn(fn) for fn in f.read().splitlines()]
ae79aceec73dbad223a757c091580425268a7e92
64,477
def _get_available_extension_urls(): """ Get download urls for all the CLI extensions compatible with the installed development CLI. :return: list of 3-tuples in the form of '(extension_name, extension_file_name, extensions_download_url)' """ all_pub_extensions = list_available_extensions(show_details=...
e658b415c8c618d73ee32625d243663c99807f6c
64,478
def poly_relation(a, b): """Describe 2 polygons relation""" rels = { 'a contains b': a.contains(b), 'a crosses b': a.crosses(b), 'a disjoint b': a.disjoint(b), 'a intersects b': a.intersects(b), 'a touches b': a.touches(b), 'a within b': a.within(b), 'a co...
ae008f812f0bf31e2f4ad2384a3390ad381730ad
64,479
def pass_community_schema(f): """Decorator retrieving a community schema.""" @wraps(f) def inner(self, community_id, schema_version_nb, *args, **kwargs): try: if schema_version_nb.isdigit(): version_nb = int(schema_version_nb) community_schema = Community...
8774b59b3ef858670e6c806e19140b599a5938da
64,480
def top_sentences(query, sentences, idfs, n): """ Given a `query` (a set of words), `sentences` (a dictionary mapping sentences to a list of their words), and `idfs` (a dictionary mapping words to their IDF values), return a list of the `n` top sentences that match the query, ranked according to idf...
3c0481bbeef4ef47307ee259b835d8d91dcf47e7
64,481
def get_alias_movie_by_aliasof(sapo_id): """Gets the alias of movie given its alias id""" return db.movie_aliases.find({'alias_of': sapo_id})
ff6718d523b019de4ba1fa37f6b783d26e068ae6
64,482
from unittest.mock import patch def property_mock(request, cls, prop_name, **kwargs): """ Return a mock for property *prop_name* on class *cls* where the patch is reversed after pytest uses it. """ _patch = patch.object(cls, prop_name, new_callable=PropertyMock, **kwargs) request.addfinalizer(...
3b2348143d4fea998254fd3623ae6c91332d5a91
64,483
from typing import Union def __compute_lnIMi_IMj_Rup_params( mu_lnIMi_Rup: Union[pd.Series, pd.DataFrame], sigma_lnIMi_Rup: Union[pd.Series, pd.DataFrame], corr_coeff: Union[float, pd.Series], im_j: float, ): """Helper function, computes mu and sigma for the conditional (univariate) lnIMi|IMj,...
bc34abf86d982600c57f7fa68283d594338febc9
64,485
def generator_address_code(address=None): """ 生成地址码 :param address: :return: """ address_code = '' if address is not None: for key, val in data.get_address_code().items(): if val == address: address_code = key break if address_code != ...
189a9c3621020ccb4c13e36bf7d194086d5a03f8
64,486
import urllib def construct_url(query, pageSize, cursorMark): """ This function constructs a url that searches through the europepmc website and returns the results in json format. """ query_string = urllib.parse.quote(query) url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query="...
8ba97c665a259427bfc2a5c500418784855da888
64,487
def validate_sample_pgx_attributes_for_sampleSet(queryDict): """ validate the sample PGx attribuets for sample set item creation/update return a boolean isValid and a text string for error message, None if input passes validation Note: Input length will not be validated since maxLength has been specifie...
1543aeb221a4d1558718a12c5b76be742a0d662b
64,488
from itertools import chain def make_inverse_connectivity(conns, n_nod, ret_offsets=True): """ For each mesh node referenced in the connectivity conns, make a list of elements it belongs to. """ iconn = [[] for ii in xrange( n_nod )] n_els = [0] * n_nod for ig, conn in enumerate( conns ):...
baf319dc2b2516ea82e8a38f1892c9c514842214
64,489
def assign_targets_to_anchors(anchors, annotations, positive_overlap=0.5, background_threshold=0.4): """ Assign ground truth boxes to default boxes. Args: anchors: Default boxes. annotations: Ground truth boxes representing an object in the image. positive_...
6e3d889c7421120866e6668db4012f53c432c113
64,490
def ts_to_date(date_string): """Convert a datetime string (UTC) into a pretty date string""" date_rep = date_string try: date = parse(date_string) date_rep = date.strftime('%b %d %H:%M:%S %Y') except ValueError: pass return date_rep
5d99d1c9caa895984e2f57f6ddaf371d89766b86
64,491
from typing import OrderedDict from typing import List def iet_insert_C_decls(iet, func_table): """ Given an Iteration/Expression tree ``iet``, build a new tree with the necessary symbol declarations. Declarations are placed as close as possible to the first symbol use. :param iet: The input Iter...
fb27ab33e2b807c0ec7c8f4a7b15d42db1b12679
64,492
def load_dfs(f_list, par_list, lh5_group='', idx_list=None, verbose=True): """ Build a pandas dataframe from lh5 data Given a list of files (can use wildcards), a list of lh5 columns, and optionally the group path, return a pandas DataFrame with all values for each parameter. Parameters ------...
f687ba2725aeb1b727ac6c660776342cddbc0d2e
64,493
def get_pmpjpe_metric( shapes_specs): """Returns vectorized PMPJPE metric.""" x_spec = shapes_specs[0] def pmpjpe(gt_x, cur_x): # gt_x: (17, 3), cur_x: (x_shape,) cur_x_pose = unpack_and_unparam(cur_x, x_spec)[0] return single_pmpjpe(gt_x, cur_x_pose) pmpjpe_batch = vmap.vmap(pmpjpe, ['gt_x',...
cde55fcfe2bc88b24ad391bfcd5942fc94c0d281
64,494
def get_peak_points(heatmaps): """ :param heatmaps: numpy array (N,15,96,96) :return:numpy array (N,15,2) """ N, C, H, W = heatmaps.shape # print("N") # print("C") all_peak_points = [] for i in range(N): peak_points = [] for j in range(C): yy, xx = np.whe...
3b5ad0184d490d1fc556eeb7deaedcba6052e039
64,495
def get_format_from_width(width, unsigned = True): """ Returns a PortAudio format constant for the specified `width`. :param `width`: The desired sample width in bytes (1, 2, 3, or 4) :param `unsigned`: For 1 byte width, specifies signed or unsigned format. :raises ValueError...
bf8d9249c463c94e64c036b9665ea827d49ab60d
64,496
def get_dollar_amount(x): """Changes string into the equivalent float in U.S. dollars and returns it.""" x = x.strip(' ') x = x.replace(',', '') x = x.replace('+', '') x = x.replace('est.', '') #Case: Empty String if x == '': return float(0) #Corner Case: Contains the s...
71d3f11ab843940e14731f4b400aea86c1a75beb
64,497
def get_sigmas(dist_X, target_perplexity): """ Finds the sigma for each row of the distance matrix based on the target perplexity. :param dist_X: the pairwise distance matrix :param target_perplexity: the specified perplexity value :return: a vector of sigma values corresponding to each row of the d...
a7e625f4f96941b3d5fac4c81df4ae4caa0964a8
64,498
def get_hardware_info(**output_dict): """ Get the serial number/service tag of the node Does not directly output anything on its own, used in merge_dictionary function """ hw_dict = {} response_json = output_dict['GetHardwareInfo'] for node in response_json['result']['nodes']: ...
15969315bbf0d41d5d0066ca1c0dfe51c7fcbf19
64,499
from typing import Dict def get_changed_images(images: Images) -> Dict[str, str]: """The original json format is {"image": "tag"}, so the output artifact is produced here. The latest version is {PR_NUMBER}-{SHA1} """ return {k: v[-1] for k, v in images.items()}
95abbec29c40fae2c8ebf08892adc8d68d2b92c7
64,500
def select_target_point(state, target_pt_num=1024): """get target point cloud from scene point cloud """ point_state = state[0][0] target_mask = get_target_mask(point_state) point_state = point_state[:4, target_mask] gripper_pc = point_state[:4, :6] point_num = min(point_state.shape[1], target...
dd26931a1472b5af681e5ad10280d847018c2cec
64,501
import time import random import hashlib import struct def slow_calculate(value): """Some weird voodoo magic calculations""" time.sleep(random.randint(1, 3)) data = hashlib.md5(str(value).encode()).digest() ans = sum(struct.unpack('<' + 'B' * len(data), data)) return ans
126b4f308b7ce6a2e448f18e7e91f4786e4aacce
64,502
import logging from datetime import datetime import numpy def intervalAvgHelper(input, patientDict, hrDict): """ Validates input and then returns average hr since a datetime :returns: -1 if not successful, otherwise the average hr """ if(not isinstance(input, type({}))): logging.error("di...
e58e03c4a41aaacd533b2ad53f632490a1b4b76a
64,504
def remove_news_article(news_article): """ Process will remove news articles that have been seen already and removed Data is fetched again to make sure all data is present """ log.info("Processing notifications, news article removed") add_seen_news_article(news_article) nation_location, loc...
e4c56daf75a5f9da73e0af1144ad07b194e8a881
64,505
def get_phrase_based_on_NN(node, text, parent_id): """ Get a phrase based on the input noun node. :param node: Root of the tree (should be a noun). :param text: Text of the sentence. :parent_id: Id of the parent node. :return: Phrase extracted (a dictionary of tokens). """ MODS = ['amod'...
e507b0a9bdaa91511df9d74a4f78568787ad3797
64,506
import typing import random def get_user_input(colours: typing.Tuple[int, ...], message: str, code_length: int) -> Code: """Asks user to input a colour code. :param colours: All possible colours to choose from. :param message: Message to display. :param code_length: Expected seq_length of the code. ...
a7a08f15b44b2f0edda874fa1f01cd26cf486e4a
64,507
import json def period_students(request, pk): """ Return all active students from period's section and level, with corresponding Training if existing (JSON) """ period = get_object_or_404(Period, pk=pk) students = Student.objects.filter( archived=False, klass__section=period.section, k...
a7f81f40e9860a3c34bc398041471f32eb1c0cdc
64,508
def get_sorted_indices(some_list, reverse=False): """Get sorted indices of some_list Parameters ---------- some_list : list Any list compatible with sorted() reverse : bool Reverse sort if True """ return [ i[0] for i in sorted( enumerate(some_lis...
6e207f4079cd3800fd26269725f5385250b76112
64,510
from pathlib import Path def _get_talairch_lta(fs_subject_dir): """Fetch pre-computed transform from infant_recon_all""" xfm = Path(fs_subject_dir) / "mri" / "transforms" / "niftyreg_affine.lta" if not xfm.exists(): raise FileNotFoundError("Could not find talairach transform.") return str(xfm...
a83caf9f34d7aa0be8ba9b592a14ea1ade82fff9
64,511
def list_all(): """ List all (AJAX) """ items = [] for i, item in enumerate(Key.objects()): items.append({ 'id': i, 'value': item.value, 'added': item.added.strftime("%Y-%m-%d %H:%M:%S"), 'pos': item.pos, 'status': item.status, ...
f8ed0ada439daf6f152e588b3c1b3f3540f0e737
64,512
def zd_sinebell(data,wide=1.0,x0=0.0,slope=1.0): """ Zero Diagonal band with sinebell function Parameters: * data Array of spectral data. * wide Diagonal band half width in points. * x0 Diagonal starting location in points. * slope Diagonal slope. """ window = 1-np.sin(np...
e133da2da0b6f24b078af3c746a1075e25fbeae8
64,513
def excel_index(column): """ Takes a string and returns what column it would be in Excel. """ # Not needed but will insure the right values. There are different # ASCII values for uppercase and lowercase letters. letters = list(column.upper()) # This works like this: LOL = 8514 # 26^2 * 12(L) + ...
224d7f370468e232a68a8205cf101e8dcb959829
64,514
def read_state(state, addr, req_len): """Read an element in the device state as an array. Args: state: The top-level state variable addr: Starting address (int) req_len: Requested length (int) Returns: An array containing the requested values, or an empty ...
b36c7a43dd961525e15caeda19ffa5957b1882ec
64,515
import typing from typing import Optional import scipy def rfft( df: pd.DataFrame, output: typing.Literal[None, "magnitude", "angle", "complex"] = None, nfft: Optional[int] = None, norm: typing.Literal[None, "unit", "forward", "ortho", "backward"] = None, optimize: bool = True,...
30a16abae07d16c702c7aa0bdd0b59622bbf3168
64,516
def parse_sites(content_io, namespace): """parses information contained in site elements (including seriesCatalogs) out of a waterml file; content_io should be a file-like object """ content_io.seek(0) site_elements = [ ele for (event, ele) in etree.iterparse(content_io) if ele.tag =...
4cdc29cc6749e4b52b52da2986f34125815a66be
64,517
def _align_pairwise(s1, s2, mprobs, psub, TM, local, return_score=False, **kw): """Generic alignment with any substitution model and indel model""" [p1, p2] = [makeLikelihoodTreeLeaf(seq) for seq in [s1, s2]] [p1, p2] = [pairwise.AlignableSeq(leaf) for leaf in [p1, p2]] pair = pairwise.Pair(p1, p2) ...
ca66a2a81f2d4f18befab83197ea45f77b8415a4
64,518
def shift_cyc_matrix(X, shift=0): """Cyclic shift of features matrix along first dimension Args: X: Feature respresentation shift: Number of bins to be shifted Returns: X_cyc: Cyclically shifted feature matrix """ #Note: X_cyc = np.roll(X, shift=shift, axis=0) does to work ...
f56e927821032b18ac214d072cc2d8fa63e76d97
64,520
def lowest_y_k_bounds( x_non_decreasing, y_non_increasing, upper: bool, jitter=1e-50, ): """ Returns the upper (or lower) bounds of the rate-of-change that would make a given element have (among) the lowest y of all. :param x_non_decreasing: :param y_non_decreasing: :param upper: bool :param jitte...
419a4b63c3c0abcede2dd01bf57ac1e775efe8a2
64,521
from datetime import datetime def _adjustLogsort(logsort_list, fps, start_frame, end_frame): """ Adjusts frame number according to the given start and end frames, and replaces logsort image with given image names. """ def _getTime(time): """ Returns datetime object from given format: HH:MM:SS:sss...
e09f66a10e2ae829a3a4b63d309aeb9d7e653262
64,522
from pathlib import Path import importlib def get_pipeline(task_type) -> tasks.Pipeline: """ Get the pipeline Task from task type - returns None if the task is not found :param task_type: string that should match the module name :return: """ if isinstance(task_type, Path): task_type = ...
5a72b09d38b98ea997aac65e7ac070fbbd736b82
64,523
def getRShiftAndMultiplierFromQScale(Qscale, qdm=False, max_multiplier=127): """ Qscale: 2^rshift * m0(mutlipiler) qdm mode: qdm is true reference to [arxiv 1712.05877] choose the int32 value nearest to 2^31 * M0, M0 in [0.5, 1] this value is always at...
25806edefca5fd9165f5aa442df82738031d0dd8
64,524
import random def get_action_using_lookahead_heuristic(state: int, depth: int, start: int, goal: int, moves_made: int, ...
7978ee40f03b3a515f8332fced4a900c329c6d52
64,525
def _to_numeric(value): """Try to convert a string to an integer or a float. If not possible, returns the initial string. """ try: value = int(value) except: try: value = float(value) except: pass return value
baf3315a4c390ac80a616c2a69ea8e398c1d031a
64,526
def compute_files(hive_holder, output, settings): """ given the current hive_holder, compute the files that have to be saved in disk return: {BlockCellName: StrOrBytes to be saved in disk} param output: something that supports info, warn, error """ new_files = {} for block_cell_name, (cell, con...
c94812fc73d0ac3522ee4424aa018e11bb9543c9
64,527
import secrets def test_regster(): """register""" global name try: name = "lox_test_"+str(secrets.token_hex(8)) resp = req.post(URL+"api/register", data={"name": name, "age": 28, "gender": 1}, files={'voice': open('test.wav', 'rb')} ) # print(resp.text) # print(resp.status_code) if resp.status_...
c751b6c68fc3983bdb6349631c5b7b5e151089cc
64,529
def find_specification_label_in_feature(feature): """Analyse a Biopython feature to find a DnaChisel Specification in it. The specification should start with either "@" or "~", in the feature's field "label" or "note". """ for labelfield in ["label", "note"]: if labelfield not in feature.qu...
918c78ad046c9acf474e2465410b7139af9e6936
64,530
import pandas import math import numpy def cross_verify_2(verify_cnt: int, df_feature: pandas.DataFrame, df_result: pandas.DataFrame, merged_columns_size: int, params, fun): """ n 折交叉验证 :param merged_columns_size: :param verify_cnt: 交叉验证的折数 :param df_result: 训练用结果 :param df_...
38783fabe22827887068f2d92a6de842e8bcd656
64,535
def gp_tuple_to_dict(gp_tuple): """Convert a groupings parameters (gp) tuple into a dict suitable to pass to the ``grouping_parameters`` CompoundTemplate.__init__ kwarg. """ params = [{'min': 1}, {'max': 1}, {'name': None}, {'possible_types': None}, {'is_separator': False}, {'inner_sep...
5db98d0530dc177685e0bcfefad94a1f6718aed9
64,536
import re def check_section_sort_order(file_path, sect_lines): """Check the sort order of the lines of a section""" # Find out lines of sub_sections and analyze them result = True filtered_lines = [] subsection_lines = [] for raw_line in sect_lines: line = raw_line.rstrip() if ...
afc88307e8db7f258b82e073207e3a7aa6302095
64,537
def read(infile): """Read a PDB structure from a filename or stream, returning an (atoms, cell, title) tuple""" if isinstance(infile, str): infile = open(infile) title = "" cell = None atoms = [] for line in infile: if line.startswith("END"): break elif ...
497f52f5d33151d3773b3befbbd987a1192bd334
64,538
def extract_ave(e, summ_list): """Average rouge between ith sentence and human summaries.""" agg = scoring.BootstrapAggregator() e_trunc = p2s_eval.get_summary_truncated( p2s_eval.get_summary_first_sentence(e), p2s_eval.TRUNC_LEN) # get_summary_first_sentence may not be necessary for s in summ_list...
7c0719e7beb78c261ad54a8fd4a0a2a606630c81
64,539
from typing import List from typing import Union def get(dataset_id: str = None, tags: List[str] = []) -> Union[Dataset, List[Dataset]]: """Get a dataset identified by `dataset_id` or a list of all the datasets Keyword Arguments: dataset_id {str} -- id of the dataset (default: {None}) tags {L...
9d76687518560247f6440a429d5c823973b381c6
64,541
from typing import Optional def convert_int_or_none(val: Optional[int]) -> Optional[int]: """Convert to an int or None.""" return int(val) if val is not None else val
1920243d7465df6f2f3f9e6fdbd2424bbad165b4
64,542
def _calculation_loop(**kwargs): """Iteratively calculates gamma at increasing distances.""" dose_valid = kwargs['dose_evaluation'] >= kwargs['lower_dose_cutoff'] gamma_valid = np.ones_like(kwargs['dose_evaluation']).astype(bool) running_gamma = np.inf * np.ones_like(kwargs['dose_evaluation']) if kw...
a4785706054c2ecef7fe4427fbee3e31572ce59a
64,543
from io import StringIO import json def get_app_urls(app_name): """Get all of the urls for the given app name. Uses django-extensions management command show_urls to get the entire project's urls, and then pulls out only the ones that are for the module of app_name. """ output = StringIO() ca...
31f9f3054e155ee7bf163ed801ccd4037b6fbef1
64,544
import collections def backward_step(activations, targets, layers, cost_grad_func): """ 后向传播,取损失函数在每一层的梯度 """ param_grads = collections.deque() output_grad = None for layer in reversed(layers): log('begin to backward_step:', str(layer)) Y = activations.pop() # 交叉熵损...
f20651e537a851a1f0597698e5ef081381978f3a
64,546
def _do_change_language(request, lang_code, current_url): """change the language and returns redirect URL""" if lang_code and check_for_language(lang_code): # path is the locale-independent url path = strip_locale_path(current_url)[1] article_class = get_article_class() try: ...
be31970f29eedf2ee7f1237adc192d8d1bd9d00d
64,548
def call(method, **params): """ This function calls methods from the NAPALM driver object. Available methods: ============================== ===== ===== ====== ======= ====== ====== ===== ========= _ EOS JunOS IOS-XR FortiOS IBM NXOS IOS Plurib...
d54fda481b90e763697a3d05207f0f0f46a21ae2
64,549
def to_utf8(input) -> bytes: """Return a utf8 encoded byte sequence of the Unicode ``input`` or its string representation. Returns: :py:bytes byte sequence. """ if isinstance(input, str): value = input.encode('utf-8') elif isinstance(input, bytes): value = input else: ...
d7eab18ffa244858b90895199988ab829355c6e5
64,550
def get_xform(src, dst): """get the transform between the two input arrays :param src: source points :type src: numpy array :param dst: destination points :type dst: numpy array :return: transform matrix :rtype: numpy array """ return cv2.getPerspectiveTransform(src, dst)
ed7df501424744439f81a4b52957fa753673f0a5
64,551
def calculate_lux(r, g, b): """Calculate ambient light values""" # This only uses RGB ... how can we integrate clear or calculate lux # based exclusively on clear since this might be more reliable? illuminance = (-0.32466 * r) + (1.57837 * g) + (-0.73191 * b) return illuminance
00b1e26fb10cef79ae32808e355f93209190dfe5
64,552
def contact_infectivity_quarantine_self_50(): """ Real Name: b'contact infectivity quarantine self 50' Original Eqn: b'contact infectivity asymptomatic self 50*(1-isolation effectiveness 50)' Units: b'1/Day' Limits: (None, None) Type: component b'' """ return contact_infectivity_asy...
a7c57f231804daaba79431053a9f5a67d53be9c2
64,554
def count_path_dynamic(m, n): """Count number of paths with dynamic method.""" # create 2d array to store values paths = [[0 for x in range(n)] for y in range(m)] # set num of paths on edges to one for i in range(m): paths[i][0] = 1 for i in range(n): paths[0][i] = 1 # calcu...
3232de0e5ff31071b11cbda3c5899ba7649a9a5e
64,556
import time def now_ts(): """当前时间戳""" return time.time()
b7b6cfec2be556df83abe7d511a15d573e0ae24a
64,557
def complex_accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in ...
cd04906c999c08d083bdca42ee5b4bbf4aa5b686
64,558
def compute_relative_errors( qs_a: np.ndarray, qs_b: np.ndarray, distances: np.ndarray, robot: Robot ) -> np.array: """Compute the relative errors of a given set of position combinations.""" return list(map(compute_relative_error, qs_a, qs_b, distances, repeat(robot)))
dad0b44422743ef4561198cf167eea63f45a7a6f
64,559
def main_phase_2(ipr_src_file, ipr_src_mod_file, output_file, logger): """ :param ipr_src_file: :param ipr_src_mod_file: :param output_file: :param logger: """ logger.info('Loading Data from .xlsx files') # Original Dataset ipr = open_workbook(ipr_src_file) ipr_sheet = ipr.sheet...
bb1e42a493729bd9c504509360a4943b583e3cb0
64,560
def _get_ticket(ticket_id: TicketID) -> DbTicket: """Return the ticket with that ID. Raise an exception if the ID is unknown or if the ticket has been revoked. """ ticket = ticket_service.get_ticket(ticket_id) if ticket.revoked: raise TicketIsRevoked(f'Ticket {ticket_id} has been revok...
621a3b75bdeacb1656d2106c61b7f35e00359770
64,561
def commit_info_for_installation(metadata_info): """ Returns a dictionary with commit info and changes in old and current environment """ info = { 'commit_message': metadata_info['commit_message'], 'time': metadata_info['time'], 'package_not_found': {}, 'package_changed':...
d2575e79e70e06c36da7dc68700e99dc8cf1ca28
64,562
def parse_object(repo, objectish): """Parse a string referring to an object. :param repo: A `Repo` object :param objectish: A string referring to an object :return: A git object :raise KeyError: If the object can not be found """ return repo[objectish]
6606eb58a1aab94a6071bf18221dbec63e2ef6da
64,563
def get_rounds(number): """ :param number: int - current round number. :return: list - current round and the two that follow. """ num_list = [number, (number+1), (number+2)] return num_list
80646e7045f167c37c87987a0cd14920bf08c1a4
64,564
import copy def matula_beck(ADT,ordering=False,degeneracy=False): """An algorithm proposed by David W. Matula, and Leland L. Beck to find k core of a graph ADT. The implementation is based upon their original paper called "Smallest-last ordering and clustering and graph coloring algorithms". """ ...
5e0daab94d205369221b79d87467e0d4ab40399d
64,565
import logging from datetime import datetime def crop_by_time(paths, times, timestamps, time_fmt=TIME_FMT_TRIMMED, args=ARGS): """Interactively crop files according to dates.""" dt0_orig = times[0] dtx_orig = times[-1] dt0 = times[0] dtx = times[-1] # Dialog ...
603cb4bbb94da207d90b02beedce234442b9db1f
64,566
def load_dataframe(foldername): """Load pandas df from storage.""" return pq.read_table(datafolder+foldername).to_pandas()
bd0cc8a44b73495f48a311959dd3022d6c29c2d8
64,567
def get_one(token, contact_id, customerid=None): """ Gets the contact with the given contact ID Returns the data for the contact in a dictionary format from the original JSON that is gathered from NodePing :type token: string :param token: NodePing API token :type contact_id: string :param ...
fc0ed51613a64e2169b0fa402c02aa86de9cf835
64,569
def mobilenet_v2_decode(cfg, num_classes, se=False, se_reduction=-1, dropout_rate=0.0): """ Constructs a MobileNetV2 architecture from decoding cfg. """ return MobileNetV2_Decode(cfg, num_classes, se=se, se_reduction=se_reduction, dropout_rate=dropout_rate)
89017bcad934d60a3efce5ab05b5d0e9ab0437bd
64,570
def lsb(array: np.ndarray, bits: int = 4) -> np.ndarray: """ Extract the least significant bits from the array :param array: The array from which the least significant bits are extracted. :param bits: Number of the least significant bits to be extracted. :return: The least significant bits stored i...
ec274822c8bf4cb1a345ab893e32e2bca2a93e45
64,571
from sklearn.datasets import load_iris as dataset def load_scikit_dataset(name:str = 'iris')->'df': """ Load sample dataset from scikit-learn. name -- name of dataset to be loaded (default 'iris'). return -- dataset in a df. """ # import library function try: if name is 'iris': ...
cc21d4c0c620e802a1f9f60c1a6422035df4e5fa
64,572
def winter_rain_ratio(pr, prsn=None, tas=None): """Ratio of rainfall to total precipitation during winter The ratio of total liquid precipitation over the total precipitation over the winter months (DJF. If solid precipitation is not provided, then precipitation is assumed solid if the temperature is below...
8422e6a21dff48466c45f041fdd4ca9b5c70de1e
64,573
def set_up_local_cluster(backend='local', n_processes=None, single_thread=False): """The variable backend determines the type of cluster used. The default value 'local' uses the multiprocessing package. The ipyparallel option is also available. The resulting variable dview expresses...
a62f4984e1f7e291a572978b9c575561a1880b6d
64,575
def set_entity_type_resolver(schema): """Set type resolver aware of ChannelContext on _Entity union.""" entity = schema.get_type("_Entity") def resolve_entity_type(instance, info): # Use new strategy to resolve GraphQL Type for `ObjectType` if isinstance(instance, ChannelContext): ...
ccc7f69d8dcba3db6a6f431c85f2b64d7610bc14
64,576
def get_key_combination(): """ Get key combinations from config """ tmp_list = [] key_combinations = config['key_combinations'] for items in key_combinations: s = set() for item in items: if len(item) == 1: ele = keyboard.KeyCode(char=item) else: ...
ee71496a4f455078ebb629677f87c2fa2753c23d
64,577
from unittest.mock import Mock def create_mock_search_app( current_mapping_hash='mapping-hash', target_mapping_hash='mapping-hash', read_indices=('test-index',), write_index='test-index', bulk_batch_size=1000, queryset=None, ): """Creates a mock search app.""" m...
5b542f6ee8d31c1c40510be6876b8d8e9d981d2f
64,578
def get_skincluster(target): """ [pm] スキンクラスターをひとつだけ取得 Args: target (PyNode): スキンクラスターを持つオブジェクト Returns: SkinCluster: """ return get_skinclusters(target)[0]
731bc4d88b767e6ba93007852ec1fbec4a3a8f22
64,579
def elision_normalize(s): """Turn unicode characters which look similar to 2019 into 2019.""" return s.replace("\u02BC", "\u2019").replace("\u1FBF", "\u2019").replace("\u0027", "\u2019").\ replace("\u1FBD", "\u2019")
a7b0f2ba14d0fcbb2cd1cc97b8ce858051d35709
64,580
def last_five(matches, requested_team, purpose): """ Function that displays results for last 5 games. Params: matches(list) contains all information about requested team requested_team(string) holds value of a id of the requested team purpose(string) like "console" Example of ...
f9b20caa8204c34b7e0bf018052d2497f0f18fc7
64,581
def compare(value1, value2, comparison): """ Compare 2 values :type value1: object :param value1: The first value to compare. :type value2: object :param value2: The second value to compare. :type comparison: string :param comparison: The comparison to make. Can be "is", "or", "and". ...
8f8869d54d55959625a89377db39220b50e1b0d3
64,582
def mergeDataframes(datasets): """ Merge Datasets into Dataframe. """ return pd.concat(datasets)
b76ed11b24083a3ccfd55faeeff71ea9006446f5
64,583
def create_context(name: str, which: str, index: int) -> Context: """Create a context that can identify this integration.""" # Use a hash for the name because otherwise the context might become # too long (max len == 36) to fit in the database. name_hash = _short_hash(name) return Context(id=f"{_DOM...
34a2568422d75084f6e03cfc1cced4bdc1abaad8
64,584
def constrain_to_range(s, min_val, max_val): """ Make sure that a value lies in the given (closed) range. :param s: Value to check. :param min_val: Lower boundary of the interval. :param max_val: Upper boundary of the interval. :return: Point closest to the input value which lies in the given r...
d2017580bab60ba444cbf40f570b16763de81969
64,585