content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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 def get_logger(name, level=logging.DEBUG): """ Returns a logger configured with Rigor formatting """ global __log__ #pylint: disable=W0603 log = None if __log__: log = __log__ else: log = logging.getLogger(name) __log__ = log console = logging.StreamHandler() console.setFormatter(logging...
41e118b382b2cf541d9335b5e6166a563fd8a12d
64,503
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 debugbuilddag(ui, repo, text=None, mergeable_file=False, overwritten_file=False, new_file=False): """builds a repo with a given DAG from scratch in the current empty repo The description of the DAG is read from stdin if not given on the command line...
d88176b2bea470a06f343b4b559aa4ee29ae3b42
64,509
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
import subprocess import sys def execute_command(command, progress_file=None, timeout=None, grace_period=None, capture_stdout=False, merge_stderr=False): """Primary way to start external commands in subprocesses an...
894ab256b2103e444642ce4f9449b56ea64b220e
64,519
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 os def get_test_path(): """ Returns the path to the ``tests`` dir that this module resides in. :rtype: str :returns: The full path to the ``tests/`` dir. """ return os.path.dirname(__file__)
c712ca3d5c727391cab0ae13bd8ebfd736a8cf6f
64,528
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 json import sys def load_config(): """ Loads a config file in the current directory called config.json. """ # Opens the config file and loads as a dictionary. try: with open('config.json', 'r') as f: config = json.load(f) print("Config file loaded.") ...
b6a7d81fc7e610f8ef80bd4ab9371bfeaea67c7b
64,531
def full_min(var): """ .. todo:: WRITEME properly returns a symbolic expression for the value of the minimal element of symbolic tensor. T.min does something else as of the time of this writing. """ return var.min(axis=range(0,len(var.type.broadcastable)))
28df56ceb469b539c032470d8f1548c49de9b11f
64,532
import os def get_meta(root): """ find a file named __meta__.* and return it's parsed contents """ (_, _, filenames) = list(os.walk(root))[0] for filename in filenames: name, fmt = filename.split(".") if name == "__meta__": with open(os.path.join(root, filename), 'r') as f: ...
5357af3ed2ef4421e002bd551c1d818ae2a864b0
64,533
def get_message (connection, timeout): """ Attempt to read a Delta-message from a serial connection, with an optional time-out in seconds """ connection.timeout = timeout # Timeout for serial data read, in seconds data = connection.read(1) # Read one byte if data ...
2da3f21f3c0f8749f80f679e387b6e31851dfb7f
64,534
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 ..._utils import global_status import requests import os import json def get_browse_history(debug = False): """ return a list of working directories for current session """ def remove_duplicates(h_list, max_size = 50): filtered = [] for h in h_list: if h not in filtere...
96b36cba09fd34e9583f95f3f9fd5d9f93d3a6a8
64,540
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
def get_tf_edges(node: Node): """ By TF/NX node find all inputs and return list of all edges. Edge direction represents data flow (from source op to this node). So the resulting list contains all input edges for a given node. Edge attributes: 'in' is index of input port for a given node, 'out' is an...
9c1a2fb4210ee26c8cb2f84cc96ac97e771a7f70
64,545
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
import os def send_file_inline(filename): """Send a file inline, including the original filename. Ref: http://test.greenbytes.de/tech/tc2231/. """ try: response = send_file(filename) except FileNotFoundError: return abort(404) basename = os.path.basename(filename) cont_dis...
fa4f374dd903cc16d3fd97ccc389a2f175a0fb64
64,547
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
import os def split_full_path(full_path, base_dir): """ Given a full path, return: - relative_dir: the part of the path that does not include the base directory and the basename - basename """ fname = os.path.basename(full_path) relative_path = full_path.split(base_dir)[-1...
bfd500d7bf8ca999b2648e0ea168688170835e66
64,553
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 ssc (z, var, grad, m): """ order of variables: p, v, phi_g, mh order of equations (to be consistent with variable order and have diagonals populated) 1) solids and liquids continuity 2) mbe 3) h2o continuity 4) co2 continuity """ Nz = len(z) J = tf.zeros...
a3c7ecfdc5cb769424fe930937db7967701e6bba
64,555
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
from typing import Optional from typing import Tuple from typing import Any from typing import List def make_recurrent( df: pd.DataFrame, time_window: int, order_by: str, partition_by: Optional[str] = None, drop_order_by: bool = True, drop_partition_by: bool = True, ...
0aed1aa537f50530086481f9b2289207ff6c048e
64,568
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
import os def _get_env_var(key: str) -> str: """Return the value of an environment variable accessed by the given key. If a value does not exist, return the key, which is too liberal, but useful when a tenant or username, for example, is stored in literal form in a config (rather than as a placeholder for...
e7e844c42b04cda872e73fb1db7a21d9bc30c896
64,574
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
import subprocess import re def supervisor_status(): """ """ cmd = '''sudo supervisorctl status''' stdout = subprocess.check_output(cmd, shell=True) stdout = stdout.decode('utf-8') procs = stdout.splitlines() # each line is a process result = {} for proc in procs: proc = re.sub...
10611fc558671a87388bee0b23d8d47ec438dec4
64,586
def compact(number): """Convert the number to the minimal representation. This strips the number of any valid separators and removes surrounding whitespace.""" number = clean(number, ' -').upper().strip() if number.startswith('LT'): number = number[2:] return number
20183aec0ed332e2bd73820982485239f1da95c0
64,587
def get_qnet(args, scope=''): """ Wrapper for getting the Gridworld network so don't have to copy and paste the same params each time. """ assert args.batch_size % 8 == 0, "batch_size must be a multiple of 8" with tf.variable_scope(scope, reuse=tf.AUTO_REUSE): return BasicGridworldQnet(...
6d65a76e22c1baf1cd79c5e83a78222d07598871
64,588
import io def writeAvroData(json_data, json_schema): """Encode json into Avro format given a schema. Parameters ---------- json_data : `dict` The JSON data containing message content. json_schema : `dict` The writer Avro schema for encoding data. Returns ------- `_io....
39875652c65e9784c862692f8365d42444dd2d0d
64,589
def get_submodel_name( region_extension, n_features, margin_of_days, iterations, depth, learning_rate, ): """Returns submodel name for a given setting of model parameters """ submodel_name = ( f"{MODEL_NAME}-re_{region_extension}-feat_{n_features}-m_{margin_of_days}-" ...
b63fa3b476828b83d6a96b7e7c8b97d26567378d
64,590
def log_1_plus_abs(mat, target = None): """ Apply log(1+abs(x)) to each element of the matrix mat. """ if not target: target = mat err_code = _cudamat_ext.apply_log_1_plus_abs(mat.p_mat, target.p_mat) if err_code: raise generate_exception(err_code) return target
7d0d5fc1522e168631e501c125a43adf88f17fb8
64,591
from typing import Callable from typing import Iterable from re import T from typing import List def pluralized(fn: ExpressionMethod) -> Callable[[Iterable[T]], List[V]]: """Return a method which maps a set of args onto fn() >>> fn = lambda d: d >>> fn({'id': 1}) {'id': 1} >>> fn_pluralized = plu...
a06ec42f2378dbfd4180efa0c54936c94ffe4f25
64,592
import ctypes import sys def ndarray_from_byte_buffer(pointer, shape, ctype=ctypes.c_byte, dtype=np.uint8): """ Create an ndarray wrapper around a buffer of bytes. Args: pointer: the pointer to the ctypes buffer of bytes to wrap shape: the shape that describes the arrangement of the bytes...
13f6c9d4329f8334a6c9a46c03005fbb7b7f7c38
64,593
import json def audit_input(request): """用户提交的操作信息""" result = {} action = request.POST.get('action') extra_info = request.POST.get('extra_info','') result['user_id'] = request.user.id result['user_name'] = request.user.username result['user_display'] = request.user.display result['ac...
52b08296d9a3417585e1f4e4413de997f7424971
64,594
def parse_csv_log(file): """ Extract queries from workload csv file and return df with fingerprint and corresponding queries """ df = pd.read_csv( file, names=_PG_LOG_COLUMNS, parse_dates=["log_time", "session_start_time"], usecols=[ "log_time", "sessi...
ab4a394f041c780598baaf1cbab1cdf482a0f80e
64,595
import uuid import random def make_repr(): """Create random file representation.""" return f"some/path/{uuid()}", f"some-hash-{uuid()}", tuple(random.randint(0, 100) for _ in range(10))
4743acdd26c90356ff92b42e03679295319662c2
64,596
def db_sync(engine, version=None): """Migrate the database to `version` or the most recent version.""" return migration.db_sync(engine, version=version)
84f99414cd91598e4bb8fe3d69784c012bb19f1e
64,597
def T_No(question): """ Function to encode transitivty of No """ global all_q responses =[] To_add = [q for q in all_q if set(question).issubset(q)] responses += [0] * len(To_add) #result of the array result = [] for q in To_add: result.append(sum(features[symptom] for ...
c3c2f669b2984219314cf926bb9f6dfd99fb38bc
64,598
def ldns_rr_rdata2buffer_wire(*args): """LDNS buffer.""" return _ldns.ldns_rr_rdata2buffer_wire(*args)
953f1b191e021af8d8925087a7c58f7381261c82
64,599