content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def collect_targets_from_attrs(rule_attrs, attrs): """Returns a list of targets from the given attributes.""" result = [] for attr_name in attrs: _collect_target_from_attr(rule_attrs, attr_name, result) return [target for target in result if is_valid_aspect_target(target)]
6be1731049f6970004763f5e9ec7d0a3bde76189
3,652,600
from typing import Tuple def extract_codes(text: str) -> Tuple[str, ...]: """Extract names of warnings from full warning text.""" match = CODES_PAT.search(text) if not match: raise ValueError("No warning code found") return tuple(match.group(1).split(","))
6727049c195197ed2407f30093c362a2c6f35cd4
3,652,601
def task_list(request, pk): """ View to get task list based on user list for forms """ user_model = User.objects.filter(is_staff=False) task_model = Task.objects.filter(user=pk) user_detail = User.objects.get(pk=pk) query = request.GET.get('q') if query: task_model = task_m...
dbb6545ca66a367b2b3e89a494ac8a9bbdbbb341
3,652,602
import json def load_credentials(): """ load_credentials :return: dict """ with open("credentials.json", "r", encoding="UTF-8") as stream: content = json.loads(stream.read()) return content
2f08fc4e897a7c7eb91de804158ee67cd91635d0
3,652,603
def get_utm_string_from_sr(spatialreference): """ return utm zone string from spatial reference instance """ zone_number = spatialreference.GetUTMZone() if zone_number > 0: return str(zone_number) + 'N' elif zone_number < 0: return str(abs(zone_number)) + 'S' else: re...
50f01758f7ee29f1b994d36cda34b6b36157fd9e
3,652,604
def messages_count(name): """ Get message count for queue curl -X GET -H 'Accept: application/json' http://localhost:8080/queues/C13470112/msgs/count curl -X GET -H 'Accept: application/json' 83.212.127.232:8080/queues/C13470112/msgs/count """ conn = get_conn() queue = conn.get_queue(name) count = queue.count...
86abcbc6a9bb81f0ce8a6a19941761c042f5a7e9
3,652,605
def return_intersect(cameraList): """ Calculates the intersection of the Camera objects in the *cameraList*. Function returns an empty Camera if there exists no intersection. Parameters: cameraList : *list* of *camera.Camera* objects A list of cameras from the camera.Camera class, e...
a47613b8d79c4a4535cd5e7e07aa3b26dea019a5
3,652,606
def get_returned_attr_set_node(tree): """ Get the NODE_ATTR_SET containing the attributes which are returned by the module """ # TODO: fix HACK, currently we assume the node containing `imports` is the returned attr set # but this may not always be the case? imports_node = get_imports_node...
f929e4255fcf914ce2d8c2db5ccd74dac5c842d7
3,652,607
from sys import version from datetime import datetime def choose_time_format_method(expression,format): """ :Summary: strftime("%s") is not a valid string formatting method in python, therefore it works on linux servers but not windows. To handle this, this function checks for python version and decid...
dc1a3c3caba2696e43b0e9f2e0d11058d7570f54
3,652,608
def import_measurements(task, subject, gsrn, session): """ Imports measurements for a single MeteringPoint, and starts a start_submit_measurement_pipeline() pipeline for each of the newly imported measurements. :param celery.Task task: :param str subject: :param str gsrn: :param sqlalch...
6f0fc4aec546c5cf7b23bf2471ac625639e9dbbb
3,652,609
import pandas from typing import List def add_agg_series_to_df( df: pandas.DataFrame, grouped_levels: List[str], bottom_levels: List[str] ) -> pandas.DataFrame: """ Add aggregate series columns to wide dataframe. Parameters ---------- df : pandas.DataFrame Wide dataframe containing bo...
7c3b7b526c394c8a24bf754365dbc809476b7336
3,652,610
def conv_relu_pool_forward(x, w, b, conv_param, pool_param): """ Convenience layer that performs a convolution, a ReLU, and a pool. Inputs: - x: Input to the convolutional layer - w, b, conv_param: Weights and parameters for the convolutional layer - pool_param: Parameters for the pooling layer...
d9a32950d1b56b4843938b339c7233e7fc87c5cc
3,652,611
def avg_pixelwise_var(images_seen: np.int16): """ Computes the variance for every pixel p across all images, resulting in a matrix holding the variance for eack pixel p, then calculates the average of that variance across all pixels. This allows us to compensate for different fov sizes. Note: images...
4b6196ddd25c0cd3ad0cd7cb1928b99772aa563f
3,652,612
def get_r2_matrix(ts): """ Returns the matrix for the specified tree sequence. This is computed via a straightforward Python algorithm. """ n = ts.get_sample_size() m = ts.get_num_mutations() A = np.zeros((m, m), dtype=float) for t1 in ts.trees(): for sA in t1.sites(): ...
e6a3eca421c40c9b9bbe218e7f6179eda0e07a00
3,652,613
import os def load_or_run(filepath, fun, *args, **kwargs): """ 계산된 결과 파일이 있으면 로딩하고, 없으면 계산후 저장 ex) res = load_or_run('file_loadorsave', funlongtime, ...., force=False) :param filepath: :param fun: :param force: :return: """ force = kwargs.pop('force', False) compress = kwar...
45a9f0fe1050201f863a9ba5887fe560eaee8b27
3,652,614
def omdb_title( api_key: str, id_imdb: str = None, media: str = None, title: str = None, season: int = None, episode: int = None, year: int = None, plot: str = None, cache: bool = True, ) -> dict: """ Looks up media by id using the Open Movie Database. Online docs: http:...
54efaba216b7de203fe6960f58a8ebb93b980c4c
3,652,615
def get_status(addr): """Get the current status of a minecraft server. addr -- server address Returns an mcstatus object. """ server = MinecraftServer.lookup(addr) try: return server.status() except Exception: return None
9e5a346d3cec803005ef0c65d24f929b56dfa68f
3,652,616
def calculate_losses(estimator, input_fn, labels): """Get predictions and losses for samples. The assumptions are 1) the loss is cross-entropy loss, and 2) user have specified prediction mode to return predictions, e.g., when mode == tf.estimator.ModeKeys.PREDICT, the model function returns tf.estimator.Esti...
1a25519d661a6de185c39bb9c65a23a3eea71971
3,652,617
def text_cleaning(value, stopwords=None): """Applies the four cleaning funtions to a value. Turns value into string, makes lowercase, strips trailing and leading spaces, and removes digits, punctuation, and stopwords Args: value (str): string to be cleaned Returns: str_out (s...
291f4150601b7537cbb4d10cb53598dcb9a83829
3,652,618
def calc_pts_lag(npts=20): """ Returns Gauss-Laguerre quadrature points rescaled for line scan integration Parameters ---------- npts : {15, 20, 25}, optional The number of points to Notes ----- The scale is set internally as the best rescaling for a line scan ...
dc491bc8dd46f81809a0dc06da8c123357736622
3,652,619
def APPEND(*ext, **kw): """Decorator to call XDWAPI with trailing arguments *ext. N.B. Decorated function must be of the same name as XDWAPI's one. """ def deco(api): @wraps(api) def func(*args, **kw): args = list(args) if "codepage" in kw: args.a...
c73dc1b192835a0eefa53f660b1af4626a3ab75c
3,652,620
def stations_within_radius(stations, centre, r): """Returns a list of all stations (type MonitoringStation) within radius r of a geographic coordinate x.""" stations_inside_radius = [] for station, distance in stations_by_distance(stations, centre): # Check if distance is inside the requried radius...
8182bdfc0d46ee64e98358c06b3d4787a0f1fa52
3,652,621
def manage_topseller(request, template_name="manage/marketing/topseller.html"): """ """ inline = manage_topseller_inline(request, as_string=True) # amount options amount_options = [] for value in (10, 25, 50, 100): amount_options.append({ "value": value, "selecte...
e9af634b66a7f7631a0bb7633cc445f05efb615a
3,652,622
from sfepy.base.base import dict_to_struct, debug from sfepy.fem.functions import Function def create_stabil_mat(problem): """Using the stabilization material stub make it the true material.""" # Identity map... ns = {'p' : 'p', 'q' : 'q', 'u' : 'u', 'b' : 'b', 'v' : 'v', 'fluid' : 'f...
a48d8869c4f4d84d86815a8d0c56ecc88ae05814
3,652,623
from typing import Optional def embedded_services(request: FixtureRequest) -> Optional[str]: """ Enable parametrization for the same cli option """ return getattr(request, 'param', None) or request.config.getoption('embedded_services', None)
908a48d9fa8696e6970fe5884632f1b373063667
3,652,624
def vigenere(plaintext,cypher): """Implementation of vigenere cypher""" i = 0 cyphertext = "" for character in plaintext: n = ord(cypher[i%len(cypher)].lower())-97 new_char = rot_char(character, n) cyphertext += new_char if new_char != ' ': i += 1 ret...
2b5cdd839bcfc0e55cdac65f9752cf88bd34c2e2
3,652,625
def get_local_unit_slip_vector_SS(strike, dip, rake): """ Compute the STRIKE SLIP components of a unit slip vector. Args: strike (float): Clockwise angle (deg) from north of the line at the intersection of the rupture plane and the horizontal plane. dip (float): Angle (degrees) ...
dddedaeaabe91137c38bbaa2ec2bb1d42a6629c7
3,652,626
def get_country_code(country_name): """Gets the code of the country given its name""" for code, name in COUNTRIES.items(): if name == country_name: return code
bb4a3eebae0b14fc8207ef4301812d3d305a8dfd
3,652,627
def build_model(cfg, train_cfg=None, test_cfg=None): """Build model.""" if train_cfg is None and test_cfg is None: return build(cfg, MODELS) else: return build(cfg, MODELS, dict(train_cfg=train_cfg, test_cfg=test_cfg))
f47aa433bf2cbd637e9ea2e8e842bab9feb12ab1
3,652,628
def find_instruction_type(opcode: str) -> InstructionType: """Finds instruction type for object instruction Parameters ---------- opcode : str opcode of instruction in hex Returns ------- InstructionType type of instruction using InstructionType enum """ # R type in...
a8f5002834f9e9e847ef4f848a13f6e8037948f6
3,652,629
import string def gen_tier_id(inst, id_base, tier_type=None, alignment=None, no_hyphenate=False): """ Unified method to generate a tier ID string. (See: https://github.com/goodmami/xigt/wiki/Conventions) """ # In order to number this item correctly, we need to decide how many tiers of the same type ...
f21b94677efe25e545d7efd99c68ed1722018c35
3,652,630
def create_temporary_file(filename, contents=""): """ Decorator for constructing a file which is available during a single test and is deleted afterwards. Example usage:: @grader.test @create_temporary_file('hello.txt', 'Hello world!') def hook_test(m): ...
b4ce96e0d239acc379d78b7c13042cea5c0a4fe0
3,652,631
def find_post_translational_modifications(filter=None, page=0, pageSize=100): # noqa: E501 """Find values for an specific property, for example possible taxonomy values for Organism property # noqa: E501 :param filter: Keyword to filter the list of possible values :type filter: str :param page: Nu...
9c9d196a7d0d3e8c3b2725247504cecf822ac541
3,652,632
def random_vector(A, b): """ Generates a random vector satisfying Ax <= b through rejection sampling. """ dimension = A.shape[1] not_feasible = True while not_feasible == True: config.reject_counter = config.reject_counter + 1 if config.reject_counter == config.milestone: ...
e710ef0a3e49fc7834850465f11232df546b944d
3,652,633
from .transform import mapi from typing import Callable def mapi(mapper: Callable[[TSource, int], TResult]) -> Projection[TSource, TResult]: """Returns an observable sequence whose elements are the result of invoking the mapper function and incorporating the element's index on each element of the source."...
e640a1a4b68b9115ca2358502b675e4d6710ea83
3,652,634
def game_to_screen(position): """ Converts coordinates from game view into screen coordinates for mouse interaction """ return (GAME_LEFT + position[0], GAME_TOP + position[1])
2176d74a98db1e226dc960b14db35af303bfe9ec
3,652,635
def get_graph_params(filename, nsize=1): """Load and process graph adjacency matrix and upsampling/downsampling matrices.""" data = np.load(filename, encoding='latin1') A = data['A'] U = data['U'] D = data['D'] U, D = scipy_to_pytorch(A, U, D) A = [adjmat_sparse(a, nsize=nsize) for a in A] ...
5c0671dbe7cd2f56aace9319f78289b1e34defa4
3,652,636
from . import computers def _(dbmodel, backend): """ get_backend_entity for DummyModel DbComputer. DummyModel instances are created when QueryBuilder queries the Django backend. """ djcomputer_instance = djmodels.DbComputer( id=dbmodel.id, uuid=dbmodel.uuid, name=dbmodel.na...
dd9dc5eeb0dcd54816675bd2dc19e5a0fc10a59a
3,652,637
import six def retrieve(filename, conf, return_format='dict', save_to_local=False, delete_remote=False, timeout=60): """Retrieving Processed Session File from server via sFTP 1. Get xml file string from server and return object 2. If save_to_local, save to local file system Args: filename: f...
1ebf550b8a9be3019ed851a5e4571ed9a72f3e44
3,652,638
def get_simulate_func_options( params, options, method="n_step_ahead_with_sampling", df=None, n_simulation_periods=None, ): """Rewrite respy's get_simulation_function such that options can be passed and therefore the seed be changed before any run. Documentation is adapted from :func:`re...
9d77730facb29d460c958033873bb2ce02f5a9ed
3,652,639
import os def read_xspec_log_files(es_dir, out_rel_name, boot_num=2): """ Read in all XSPEC log files (with chatter set to 4) that were generated in sed_fit_bootstrap.sh, and append each bootstrap iteration's values to its sed_pars.Parameter. Parameters ---------- es_dir : str The...
84df2fe905a001877977f6248bafda8e417b0fc5
3,652,640
def get_host_user_and_ssh_key_path(instance_name, project, zone): """Return a tuple of (hostname, username and ssh_key_path).""" output = api.local( 'gcloud compute ssh --project "%s" --zone "%s" %s --dry-run' % (project, zone, instance_name), capture=True) print output m = re.match('/usr/bin...
eabc88808fe0b73e9df507ea0397c3b9eb38a8de
3,652,641
def TDataStd_TreeNode_Find(*args): """ * class methods working on the node =================================== Returns true if the tree node T is found on the label L. Otherwise, false is returned. :param L: :type L: TDF_Label & :param T: :type T: Handle_TDataStd_TreeNode & :rtype: bool ...
6c37e5f05627287eab4c4c13a21d92aa6e4e6a1a
3,652,642
def make_group_corr_mat(df): """ This function reads in each subject's aal roi time series files and creates roi-roi correlation matrices for each subject and then sums them all together. The final output is a 3d matrix of all subjects roi-roi correlations, a mean roi-roi correlation matrix and a roi-r...
4d30136e8ce46e984c0039ddaca26efd04f231b9
3,652,643
def get_tradedate(begin, end): """ get tradedate between begin date and end date Params: begin: str,eg: '1999-01-01' end: str,eg: '2017-12-31' Return: pd.DataFrame """ try: conn = pymysql.connect(**config) cursor = conn.cursor() ...
9464caee65f12b9704e63068e159494baad25e6a
3,652,644
def collect_tweet(update: Update, context: CallbackContext) -> int: """Tweet caption collection for tweet without attachments""" logger.info("'{update.message.text}' tweet type selected") update.message.reply_text("Enter the tweet") return TWEET
6fc25efa4dc10f2316b70ff18f9a5c77b83c1e4a
3,652,645
from typing import Dict def get_unhandled_crictical_errors(req:HttpRequest, n:int): """ Preprocess errors before injection and gets `n` unhandled errors Typical Return Value if `n` errors were found... {"es":[ { "id": "192.168.1.51", "title":"hey there...
ae2afdeda89f9a9d946fa60a8ba5e15277388e50
3,652,646
def ADO_mappings(N, K, level_cutoff): """ ADO (auxilary density operators) are indexed by a N by (K + 1) matrix consisting of non-negative integers. ADO_mappings calculates all possible matrices "ado_index" of size N by (K+1) where np.sum(m) < level_cutoff Parameters ---------- N : int...
a76da5569863ea8d17ec248eb09b2b6e5a300ad2
3,652,647
def f_beta(precision, recall, beta): """ Returns the F score for precision, recall and a beta parameter :param precision: a double with the precision value :param recall: a double with the recall value :param beta: a double with the beta parameter of the F measure, which gives more or less weight to...
be6c2b011c51d58d4b5f943671cd53b45632b48f
3,652,648
import os import tempfile def convert_image_to_dicom(image_file): """Read an image file, convert it to Dicom and return the file path""" # Load pixel array from image. img = Image.open(image_file) if ('RGB' == img.mode) or ('RGBA' == img.mode): # Assuming greyscale image, keep only one channe...
722a5364cd64b5c5261dbb746e24d37e6288f14d
3,652,649
import ntpath, os, yaml def get_cfg(existing_cfg, _log): """ generates """ _sanity_check(existing_cfg, _log) with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream: try: ret = yaml.load(stream) ...
3d69096ebc1b78ad52dcc5b35b225ccfea5ff189
3,652,650
import socket import os import tqdm import urllib import logging def download_alphafold_cif( proteins: list, out_folder: str, out_format: str = "{}.cif", alphafold_cif_url: str = 'https://alphafold.ebi.ac.uk/files/AF-{}-F1-model_v1.cif', timeout: int = 60, verbose_log: bool = False, ) -> tuple...
c70265b920837d23c27ee5732a3a9e155a29a30d
3,652,651
import sys import os def _gecko_path(): """Either get the executable or raise an error""" if sys.platform == "win32": return os.path.join(PCKG_PATH, "win32", "geckodriver.exe") if sys.platform == 'linux': return os.path.join(PCKG_PATH, "linux", "geckodriver") if sys.platform == 'darwin...
a5b82091eca7545781740c3ff4d03da532b818a4
3,652,652
import struct def readShort(f): """Read 2 bytes as BE integer in file f""" read_bytes = f.read(2) return struct.unpack(">h", read_bytes)[0]
1b31c2285d055df3c128e8158dcc67eb6c0a2b18
3,652,653
def get_color(thing): """Get color for thing. :param thing: Thing to get color for. :return: Color tuple if rule exists otherwise None. """ for rule in _COLOR_RULES: color = rule(thing) if color is not None: return color return None
79620c0ec8d5e9a153038b9b6a65f36158dce255
3,652,654
def build_table(infos): """ Builds markdown table. """ table_str = '| ' for key in infos[0].keys(): table_str += key + ' | ' table_str += '\n' table_str += '| ' for key in infos[0].keys(): table_str += '--- | ' table_str += '\n' for info in infos: table_str += ...
8d31e6abc9edd0014acbac3570e4a2bc711baa4a
3,652,655
import six import threading def notify_telegram(title, content, token=None, chat=None, mention_user=None, **kwargs): """ Sends a telegram notification and returns *True* on success. The communication with the telegram API might have some delays and is therefore handled by a thread. """ # test impo...
a736025f5c6a6acff634f325ecbad0e591f30174
3,652,656
def convert_to_dapr_duration(td: timedelta) -> str: """Converts date.timedelta to Dapr duration format. Args: td (datetime.timedelta): python datetime object. Returns: str: dapr duration format string. """ total_minutes, secs = divmod(td.total_seconds(), 60.0) hours, mins = di...
729cde6d2dccea1c8fa36eec506ee8ee6ea34b6e
3,652,657
def get_slot(handler_input, slot_name): # type: (HandlerInput, AnyStr) -> Optional[Slot] """Return the slot information from intent request. The method retrieves the slot information :py:class:`ask_sdk_model.slot.Slot` from the input intent request for the given ``slot_name``. More information on t...
c564f3b82fb21c12b81d1fda0214c330e7355080
3,652,658
from typing import Callable def password_to_key( hash_implementation: Callable[[bytes], TDigestable], padding_length: int ) -> Callable[[bytes, bytes], bytes]: """ Create a helper function to convert passwords to SNMP compliant keys according to :rfc:`3414`. >>> hasher = password_to_key(hashlib.s...
3f638afaa5c950f70edf39ca699701ec1709729e
3,652,659
import re def categorize_tag_key_characters(OSM_FILE = "data\\round_rock.xml", category = 'Summary'): """Categorizes attributes into those with: all lower character, all lower after colon(:), containing special/problem characters and all all others that were not listed in above wh...
4e2f6c6a24a14114ce8f5c8d2855847859ad4d8f
3,652,660
def rotate_left(value, count, nbits, offset): """ Rotate a value to the left (or right) @param value: value to rotate @param count: number of times to rotate. negative counter means rotate to the right @param nbits: number of bits to rotate @param offset: offset of the first b...
ed24a0a958bed1ab1a01c4a858bfba0fd163e2fd
3,652,661
def geo_to_string(value): """ Convert geo objects to strings, because they don't support equality. """ if isinstance(value, list): return [geo_to_string(x) for x in value] if isinstance(value, dict): result = {} for dict_key, dict_value in value.iteritems(): result[dict_key] = geo_to_string(dict_value) ...
9566a980128767ea4b2d651c88d715673e7ef005
3,652,662
import argparse import sys def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description="I'm a snitch", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('FILE1', help='Input file 1', ...
5ff11678d2d45f2cbb51e71841195009bb45a0f2
3,652,663
import http def page_not_found(request, template_name='404.html'): """ Default 404 handler. Templates: `404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ t = loader.get_template(template_name) # You need to create a 404.html t...
de0348f3c3bf963f1614d13ffc32bb79d30437b0
3,652,664
import csv def load_data(filename): """ Load shopping data from a CSV file `filename` and convert into a list of evidence lists and a list of labels. Return a tuple (evidence, labels). evidence should be a list of lists, where each list contains the following values, in order: - Administr...
eb2465d0ebfb7398a3742d8fb79463d3d7b076f0
3,652,665
def instance_mock(cls, request, name=None, spec_set=True, **kwargs): """ Return a mock for an instance of *cls* that draws its spec from the class and does not allow new attributes to be set on the instance. If *name* is missing or |None|, the name of the returned |Mock| instance is set to *request....
ccc60e2f90f63a131059714b3ddb213246807a0b
3,652,666
import functools import torch def auto_fp16(apply_to=None, out_fp32=False): """Decorator to enable fp16 training automatically. This decorator is useful when you write custom modules and want to support mixed precision training. If inputs arguments are fp32 tensors, they will be converted to fp16 aut...
1b3292ce6382f82b210d07ec48557f3c06ed7259
3,652,667
def get_loci_score(state, loci_w, data_w, species_w, better_loci, species_counts, total_individuals, total_species, individuals): """ Scoring function with user-specified weights. :param state: :param loci_w: the included proportion of loci from the original data se...
e5e12bf2f9f76e994289a33b52d4cdc3d641ec8e
3,652,668
def make_per_cell_fastqs( reads, outdir, channel_id, output_format, cell_barcode_pattern, good_barcodes_filename): """Write the filtered cell barcodes in reads from barcodes_with_significant_umi_file fastq.gzs to outdir Parameters ---------- reads...
16f45364e8a081addf7b126c3d5af4fb00de4bdc
3,652,669
def plot_roc_curve(data, cls_name, title='ROC curve'): """ :param data: list [(fpr, tpr), (), ...] :param cls_name: tuple of names for each class :param title: plot title :return: """ def cal_auc(tpr, fpr): return np.trapz(tpr, fpr) def plot_single_curve(fpr, tpr, cls_ind): ...
5b2a56c3f193954173431341185b3bdc53c33c7a
3,652,670
import time def train(elastic_coordinator, train_step, state): """ This is the main elastic data parallel loop. It starts from an initial 'state'. Each iteration calls 'train_step' and returns a new state. 'train_step' has the following interface: state, worker_stats = train_st...
ea7886bba7db96ff85e1687b3b3e24cbc8f8af9d
3,652,671
def make_animation(data_list, **kwargs): """ Creates an animation from list of McStasData objects Parameters ---------- data_list : list of McStasData List of McStasData objects for animation Keyword arguments ----------------- filename : str Filename for saving...
334a04f660018d2a05da1ceadf5ef2fdc8e8cdc6
3,652,672
import torch def softmax_mask(w: torch.Tensor, dim=-1, mask: torch.BoolTensor = None ) -> torch.Tensor: """ Allows having -np.inf in w to mask out, or give explicit bool mask :param w: :param dim: :param mask: :return: """ if mask is N...
6cf295b308040d3ad4019ab8292b37a679fb6e27
3,652,673
from jack.readers.multiple_choice.shared import MultipleChoiceSingleSupportInputModule from jack.readers.natural_language_inference.modular_nli_model import ModularNLIModel from jack.readers.multiple_choice.shared import SimpleMCOutputModule from typing import Union def modular_nli_reader(resources_or_conf: Union[dic...
03032966355fcb3405cbc2f311908d7be1f2485d
3,652,674
def move_box_and_gtt(n_targets=3, time_limit=DEFAULT_TIME_LIMIT, control_timestep=DEFAULT_CONTROL_TIMESTEP): """Loads `move_box_or_gtt` task.""" return _make_predicate_task( n_boxes=1, n_targets=n_targets, include_gtt_predicates=True, include_move_bo...
4ae2377d0449b93d3dc0ff34e18010c7bff004d8
3,652,675
import json def get_body(data_dict, database_id, media_status, media_type): """ 获取json数据 :param media_type: :param media_status: :param data_dict: :param database_id: :return: """ status = "" music_status = "" if media_status == MediaStatus.WISH.value: status = "想看...
4d09b4000c47dc1dc56aa73ca7b176d40f360e97
3,652,676
def _find_full_periods(events, quantity, capacity): """Find the full periods.""" full_periods = [] used = 0 full_start = None for event_date in sorted(events): used += events[event_date]['quantity'] if not full_start and used + quantity > capacity: full_start = event_date...
16c36ce8cc5a91031117534e66c67605e13e3bd4
3,652,677
import random def crop_image(img, target_size, center): """ crop_image """ height, width = img.shape[:2] size = target_size if center == True: w_start = (width - size) / 2 h_start = (height - size) / 2 else: w_start = random.randint(0, width - size) h_start = random...
c61d4410155501e3869f2e243af22d7fc13c10ee
3,652,678
def _histogram( data=None, bins="freedman-diaconis", p=None, density=False, kind="step", line_kwargs={}, patch_kwargs={}, **kwargs, ): """ Make a plot of a histogram of a data set. Parameters ---------- data : array_like 1D array of data to make a histogram o...
cc766f3367c0c7b5c3c1f56c120f8e682c14a8fb
3,652,679
def getGarbageBlock(): """获取正在标记的众生区块 { ?block_id= } 返回 json { "is_success":bool, "data": {"id": , "election_period": "beings_block_id": "votes": "vote_list": "status": "create_time": """ try: beings_block...
9faff268d1f492adde467a100d93e99d0b2cc583
3,652,680
def partition(items, low, high): """Return index `p` after in-place partitioning given items in range `[low...high]` by choosing a pivot (TODO: document your method here) from that range, moving pivot into index `p`, items less than pivot into range `[low...p-1]`, and items greater than pivot into range `[p+1...hig...
23e98f9af46239e74ce990f7c0873159d3dff43e
3,652,681
from typing import Dict import itertools def cluster_confusion_matrix(pred_cluster:Dict, target_cluster:Dict) -> EvalUnit: """ simulate confusion matrix Args: pred_cluster: Dict element: cluster_id (cluster_id from 0 to max_size)| predicted clusters target_cluster: Dict element:cluster_id (c...
b3a5afb5c01cf5cb07c43e3666111d06e9229259
3,652,682
def change_short(x, y, limit): """Return abs(y - x) as a fraction of x, but with a limit. >>> x, y = 2, 5 >>> abs(y - x) / x 1.5 >>> change_short(x, y, 100) 1.5 >>> change_short(x, y, 1) # 1 is smaller than 1.5 1 >>> x = 0 >>> change_short(x, y, 100) # No error, even though...
1d4965650f12c95ba54f1ce38fc63e1e6eb39573
3,652,683
import copy import tqdm def generate_correlation_map(f, x_data, y_data, method='chisquare_spectroscopic', filter=None, resolution_diag=20, resolution_map=15, fit_args=tuple(), fit_kws={}, distance=5, npar=1): """Generates a correlation map for either the chisquare or the MLE method. On the diagonal, the chisq...
1294f1a93a98602ee50e5e52aacea6e678625520
3,652,684
import socket def local_ip(): """find out local IP, when running spark driver locally for remote cluster""" ip = ((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect( ("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(soc...
d45978f3f433adba5cb1181d71cb367ceabd880f
3,652,685
def string_to_int_replacements(setting, item, for_property): """Maps keys to values from setting and item for replacing string templates for settings which need to be converted to/from Strings. """ replacements = common_replacements(setting, item) replacements.update({ '$string_to_int': str...
c6ae6a55fdda2fe13bd3ac7001da528d704e3df7
3,652,686
import os def get_var_path(path): """ get the path stored in the 'app/data' directory :param path: string :return: string """ return os.path.join(VAR_DIR, path)
9341acbdefde801b12229ed3e8275495e5ed37a7
3,652,687
import pathlib import subprocess def GitClone( clone_url: str, destination: pathlib.Path, shallow: bool = False, recursive: bool = False, timeout: int = 3600, ) -> pathlib.Path: """Clone a repository from Github. Args: clone_url: The URL of the repo to clone. destination: The output path. If th...
1c164c0af81cd83d956d66b8fe073cedb0d16a18
3,652,688
import struct def UnpackU32(buf, offset=0, endian='big'): """ Unpack a 32-bit unsigned integer into 4 bytes. Parameters: buf - Input packed buffer. offset - Offset in buffer. endian - Byte order. Return: 2-tuple of unpacked value, new buffer offset. """ ...
061ba5e8c4db891100549d0181475b8915d9fb0a
3,652,689
def get_reset_token(user, expires_sec=1800): """ Create a specify token for reset user password Args: user: expires_sec: Returns: token: string """ hash_token_password = Serializer(APP.config['SECRET_KEY'], expires_sec) return hash_token_password.dumps({'user_name': u...
6477f03ca25a206db18c4a0a59ae0fac1106e262
3,652,690
from typing import Union def _on_error_resume_next(*sources: Union[Observable, Future]) -> Observable: """Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. Examples: >>> res = rx.on_error_resume_next(xs, ys, zs) Returns: ...
ed604de1b566bc73b394143bb0b8bc487646ac1a
3,652,691
def prompt_for_value(field_name: str, field_type): """Promt the user to input a value for the parameter `field_name`.""" print_formatted_text( f"No value found for field '{field_name}' of type '{field_type}'. " "Please enter a value for this parameter:" ) response = prompt("> ") whi...
3483b718f09d5a99a37a9d6086e462acf546cbf3
3,652,692
def move_j(joints, accel, vel): """ Function that returns UR script for linear movement in joint space. Args: joints: A list of 6 joint angles (double). accel: tool accel in m/s^2 accel: tool accel in m/s^2 vel: tool speed in m/s Returns: script: UR script "...
4798c58de190b026a7b4d59378c277880d8c8077
3,652,693
def create_dist_list(dist: str, param1: str, param2: str) -> list: """ Creates a list with a special syntax describing a distribution Syntax: [identifier, param1, param2 (if necessary)] """ dist_list: list = [] if dist == 'fix': dist_list = ["f", float(param1)] elif dist == 'binary'...
19cb93867639bcb4ae8152e4a28bb5d068a9c756
3,652,694
def compute_arfgm(t, qd, p, qw=0.0): """computes relative humidity from temperature, pressure and specific humidty (qd) This might be similar to https://unidata.github.io/MetPy/latest/api/generated/metpy.calc.relative_humidity_from_specific_humidity.html algorithm from RemapToRemo addgm **Arguments:*...
3e74be0b2099774482c32e2a3fbc4e2ee3f339fe
3,652,695
import os def getOutputMeshpath(path, meshtype=None): """Returns the folder path for mesh file export as specified in the GUI. Phobos by default creates a directory 'meshes' in the export path and subsequently creates sub-directories of "export/path/meshes" for every format, e.g. resulting in "export...
39336f2d02a58898d96a3d9a0c22d05716a46b50
3,652,696
def load_data(): """ loads the data for this task :return: """ fpath = 'images/ball.png' radius = 70 Im = cv2.imread(fpath, 0).astype('float32')/255 # 0 .. 1 # we resize the image to speed-up the level set method Im = cv2.resize(Im, dsize=(0, 0), fx=0.5, fy=0.5) height, width = Im...
3caaa20ecb43853910f1d42667bd481bbe62e17d
3,652,697
def create_response_body(input_json): """Create a json response with specific args of input JSON.""" city_name = str(input_json['name']) country_code = str(input_json['sys']['country']) temp_celsius = get_val_unit(input_json, 'main', 'temp', ' °C') wind_speed = get_val_unit(input_json, 'wind', 'spee...
4696f6d6929eea941697bf7aab49d139e4bd6229
3,652,698
import os def get_GESLA_surge_filename(city): """Get the path to the file containing GESLA-2 surge data for ‘city’.""" if city == "Brest": filename = "brest-brest-france-refmar_SkewSurges.txt" elif city == "La Rochelle": filename = "la_rochelle_la_palli-la_rochelle_la_palli-france-refmar_S...
e08fde26c527b6126cf7b9a7eb3ae720abc8ff19
3,652,699