content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def fetch_preset(output_filename=None, nproc=8, add_structure=True): """ Fetches preset list of docs determined via trial and error, An initial query via the frontend on 06/28/2019 showed 12870, and subsequent sampling of ids from 8000-25000 yielded all 12820. Successful query ids were ...
ca2073d5f12f2c09f0aea5596c7d9919277a17ce
16,800
import sys def parse_args(): """Function to read CCB-ID command line arguments Args: None - reads from sys.argv Returns: an argparse object """ # create the argument parser parser = args.create_parser(description='Apply a CCB-ID species classification model to cs...
a2a7ff8a7f1fa4cd757bbd0cc0bd6a33a84e1032
16,801
import typing def compute_accuracy(data): """Return [wpm, accuracy].""" prompted_text = data["promptedText"][0] typed_text = data.get("typedText", [""])[0] start_time = float(data["startTime"][0]) end_time = float(data["endTime"][0]) return [typing.wpm(typed_text, end_time - start_time), ...
c10b5d681392c71967b86f12d33be3edc1361446
16,802
from typing import IO def write_file(filename: str, content: str, mode: str = "w") -> IO: """Save content to a file, overwriting it by default.""" with open(filename, mode) as file: file.write(content) return file
5d6b7ac1f9097d00ae2b67e3d34f1135c4e90946
16,803
def get_minimum_integer_attribute_value(node, attribute_name): """ Returns the minimum value that a specific integer attribute has set :param node: str :param attribute_name: str :return: float """ return maya.cmds.attributeQuery(attribute_name, min=True, node=node)[0]
ce36c252478e9cb5d5e5ade3e2d70716d206748a
16,804
import numpy as np import yt import string def get_star_locs(plotfile): """Given a plotfile, return the location of the primary and the secondary.""" ds = yt.load(plotfile) # Get a numpy array corresponding to the density. problo = ds.domain_left_edge.v probhi = ds.domain_right_edge.v dim ...
429758abd92d4eff7a1948278bbe8c348ba83862
16,805
def get_list(_list, persistent_attributes): """ Check if the user supplied a list and if its a custom list, also check for for any saved lists :param _list: User supplied list :param persistent_attributes: The persistent attribs from the app :return: The list name , If list is custom or not """...
497fa8427660bafa3cc3023abf0132973693dc6e
16,806
import socket import re def inode_for_pid_sock(pid, addr, port): """ Given a pid that is inside a network namespace, and the address/port of a LISTEN socket, find the inode of the socket regardless of which pid in the ns it's attached to. """ expected_laddr = '%02X%02X%02X%02X:%04X' % (addr[3], a...
4d47d9de118caa87854b96bf759a75520b8409cb
16,807
from typing import List from typing import Tuple import logging def get_edges_from_route_matrix(route_matrix: Matrix) -> List[Tuple]: """Returns a list of the edges used in a route according to the route matrix :param route_matrix: A matrix indicating which edges contain the optimal route :type route_mat...
32e84bc782cdf3939affa881f0c2cf23ff81eeee
16,808
def nicer(string): """ >>> nicer("qjhvhtzxzqqjkmpb") True >>> nicer("xxyxx") True >>> nicer("uurcxstgmygtbstg") False >>> nicer("ieodomkazucvgmuy") False """ pair = False for i in range(0, len(string) - 3): for j in range(i + 2, len(string) - 1): if ...
7c543bbd39730046b1ab3892727cca3a9e027662
16,809
from typing import Union def multiple_choice(value: Union[list, str]): """ Handle a single string or list of strings """ if isinstance(value, list): # account for this odd [None] value for empty multi-select fields if value == [None]: return None # we use string formatting ...
aae54f84bc1ccc29ad9ad7ae205e130f66601131
16,810
def Jnu_vD82(wav): """Estimate of ISRF at optical wavelengths by van Dishoeck & Black (1982) see Fig 1 in Heays et al. (2017) Parameters ---------- wav : array of float wavelength in angstrom Returns ------- Jnu : array of float Mean intensity Jnu in cgs units ...
287dbf88d7a5ba58ca8792cd78ff61393df3aae2
16,811
def _coexp_ufunc(m0, exp0, m1, exp1): """ Returns a co-exp couple of couples """ # Implementation for real if (m0 in numba_float_types) and (m1 in numba_float_types): def impl(m0, exp0, m1, exp1): co_m0, co_m1 = m0, m1 d_exp = exp0 - exp1 if m0 == 0.: ...
11df0f4c06edb758945b7a86940edd4975c47c85
16,812
def get_lorem(length=None, **kwargs): """ Get a text (based on lorem ipsum. :return str: :: print get_lorem() # -> atque rerum et aut reiciendis... """ lorem = ' '.join(g.get_choices(LOREM_CHOICES)) if length: lorem = lorem[:length] return lorem
a3ece5c011d69e0a532bcb4b91fa6583dd028c1d
16,813
import warnings def try_get_graphql_scalar_type(property_name, property_type_id): """Return the matching GraphQLScalarType for the property type id or None if none exists.""" maybe_graphql_type = ORIENTDB_TO_GRAPHQL_SCALARS.get(property_type_id, None) if not maybe_graphql_type: warnings.warn( ...
70c4406b9cd08b3de6e48a473e62869470f579b1
16,814
import requests def get(path): """Get GCE metadata value.""" attribute_url = ( 'http://{}/computeMetadata/v1/'.format(_METADATA_SERVER) + path) headers = {'Metadata-Flavor': 'Google'} operations_timeout = environment.get_value('URL_BLOCKING_OPERATIONS_TIMEOUT') response = requests.get( attribut...
044db931369de13e6c16db9007fe4bad28a940a8
16,815
def greedy_helper(hyper_list, node_dict, fib_heap, total_weight, weight=None): """ Greedy peeling algorithm. Peel nodes iteratively based on their current degree. Parameters ---------- G: undirected, graph (networkx) node_dict: dict, node id as key, tuple (neighbor list, heap node) as value. He...
b2c0f3e91e6c9a80a8396dc104abc804af8875e5
16,816
def CleanFloat(number, locale = 'en'): """\ Return number without decimal points if .0, otherwise with .x) """ try: if number % 1 == 0: return str(int(number)) else: return str(float(number)) except: return number
03ccc3bfe407becf047515b618621058acff37e7
16,817
def ssd_bboxes_encode(boxes): """ Labels anchors with ground truth inputs. Args: boxex: ground truth with shape [N, 5], for each row, it stores [y, x, h, w, cls]. Returns: gt_loc: location ground truth with shape [num_anchors, 4]. gt_label: class ground truth with shape [num_an...
1e0a07c1305fe2b1ba99f535609d2d52d72befa8
16,818
def _get_partial_prediction(input_data: dt.BatchedTrainTocopoData, target_data_token_ids: dt.NDArrayIntBO, target_data_is_target_copy: dt.NDArrayBoolBOV, target_data_is_target_pointer: dt.NDArrayBoolBOV ) -> ...
1a0fdc53e4e49bf3d0c0824eca6ba381d7a72f1f
16,819
from tqdm import tqdm_notebook as tqdm from tqdm import tqdm from tqdm import tqdm as tqdm def get_energy_spectrum_old(udata, x0=0, x1=None, y0=0, y1=None, z0=0, z1=None, dx=None, dy=None, dz=None, nkout=None, window=None, correct_signal_loss=True, remove_undersampled_r...
aa29358215897f3bcb630d2c62b679d2b6ebef88
16,820
def createDefaultClasses(datasetTXT): """ :param datasetTXT: dict with text from txt files indexed by filename :return: Dict with key:filename, value:list of lists with classes per sentence in the document """ classesDict = {} for fileName in datasetTXT: classesDict[fileName] = [] ...
8bec5768710a929c21f75fa70865e25f340409f6
16,821
def getGlobals(): """ :return: (dict) """ return globals()
0fa230d341ba5435b33c9e6a9d9f793f99a74238
16,822
from typing import Iterable from typing import List def split_text_to_words(words: Iterable[str]) -> List[Word]: """Transform split text into list of Word.""" return [Word(word, len(word)) for word in words]
6317e794a5397da44be96216308573ae9d5a788f
16,823
import khorosjx def init_module_operation(): """This function imports the primary modules for the package and returns ``True`` when successful.""" khorosjx.init_module('admin', 'content', 'groups', 'spaces', 'users') return True
d6cbc3b94d4b4005d301d9b597bb7086e211bfa2
16,824
def connect_to_rds(aws, region): """ Return boto connection to the RDS in the specified environment's region. """ set_progress('Connecting to AWS RDS in region {0}.'.format(region)) wrapper = aws.get_api_wrapper() client = wrapper.get_boto3_client( 'rds', aws.serviceaccount, ...
cdfaa984c6795c7e03f0d8b3e3620f6de757fcbb
16,825
def export_graphviz(DecisionTreeClassificationModel, featureNames=None, categoryNames=None, classNames=None, filled=True, roundedCorners=True, roundLeaves=True): """ Generates a DOT string out of a Spark's fitted DecisionTreeClassificationModel, which can be drawn with any library capable...
eb4484136fbbe92537a3f030375f6ac80081befd
16,826
def _get_next_sequence_values(session, base_mapper, num_values): """Fetches the next `num_values` ids from the `id` sequence on the `base_mapper` table. For example, if the next id in the `model_id_seq` sequence is 12, then `_get_next_sequence_values(session, Model.__mapper__, 5)` will return [12, 13, 14, ...
63ad9e5e55228dd873ee2c5d9080d223c89e1bc6
16,827
def overview(request): """ Dashboard: Process overview page. """ responses_dict = get_data_for_user(request.user) responses_dict_by_step = get_step_responses(responses_dict) # Add step status dictionary step_status = get_step_completeness(responses_dict_by_step) responses_dict_by_step['...
4ac165cf5b4bf7de6f060d6649935f25fcf5a0a9
16,828
def _guess_os(): """Try to guess the current OS""" try: abi_name = ida_typeinf.get_abi_name() except: abi_name = ida_nalt.get_abi_name() if "OSX" == abi_name: return "macos" inf = ida_idaapi.get_inf_structure() file_type = inf.filetype if file_type in (ida_ida.f_ELF...
bb2cb2f0c294f2554ec419ee1bdea665abaf6957
16,829
def create_conf(name, address, *services): """Create an Apple TV configuration.""" atv = conf.AppleTV(name, address) for service in services: atv.add_service(service) return atv
0326a4c21b39ef12fe916f3a3fbee34af52c12a2
16,830
def log_transform(x): """ Log transformation from total precipitation in mm/day""" tp_max = 23.40308390557766 y = np.log(x*(np.e-1)/tp_max + 1) return y
61783d103db36ed668e494f557550caef611b84a
16,831
from datetime import datetime import requests import json def get_flight(arguments): """ connects to skypicker servive and get most optimal flight base on search criteria :param arguments: inputs arguments from parse_arg :return dict: flight """ api_url = 'https://api.skypicker.com/flights?v=3...
690b7bd170b8b83f4b83f5c0ce98da919134107c
16,832
def use_ip_alt(request): """ Fixture that gives back 2 instances of UseIpAddrWrapper 1) use ip4, dont use ip6 2) dont use ip4, use ip6 """ use_ipv4, use_ipv6 = request.param return UseIPAddrWrapper(use_ipv4, use_ipv6)
c33d74b6888124413d1430e4873140475db4748e
16,833
import torch def radius_gaussian(sq_r, sig, eps=1e-9): """Compute a radius gaussian (gaussian of distance) Args: sq_r: input radiuses [dn, ..., d1, d0] sig: extents of gaussians [d1, d0] or [d0] or float Returns: gaussian of sq_r [dn, ..., d1, d0] """ return torch.exp(-sq...
cd5bb2bb85641b1200ce67cb7eb52bc1705cd0a1
16,834
from typing import List from typing import Dict from typing import Any def index_papers_to_geodata(papers: List[Paper]) -> Dict[str, Any]: """ :param papers: list of Paper :return: object """ geodata = {} for paper in papers: for file in paper.all_files(): for location in f...
f892d84e3dc8f239885b5c4110c931b088922bcc
16,835
def _get_all_prefixed_mtds( prefix: str, groups: t.Tuple[str, ...], update_groups_by: t.Optional[t.Union[t.FrozenSet[str], t.Set[str]]] = None, prefix_removal: bool = False, custom_class_: t.Any = None, ) -> t.Dict[str, t.Tuple...
2387fb3f2aa0416ad9837f6c1b4c27488d406fea
16,836
import hashlib def _extract_values_from_certificate(cert): """ Gets Serial Number, DN and Public Key Hashes. Currently SHA1 is used to generate hashes for DN and Public Key. """ logger = getLogger(__name__) # cert and serial number data = { u'cert': cert, u'issuer': cert.ge...
caa22f85fa26a3f386b33c52fff6562c8e9714ea
16,837
from functools import reduce def cartesian_product(arrays): """Create a cartesian product array from a list of arrays. It is used to create x-y coordinates array from x and y arrays. Stolen from stackoverflow http://stackoverflow.com/a/11146645 """ broadcastable = np.ix_(*arrays) broadca...
552b898a9187df637cc5f10b49e6a1fe004af95c
16,838
def advanced_split(string, *symbols, contain=False, linked='right'): """ Split a string by symbols If contain is True, the result will contain symbols The choice of linked decides symbols link to which adjacent part of the result """ if not isinstance(string, str): raise Exception('Strin...
3e46fcc0c3fa6ab99b9d4d45cf950d9ad3f03ac1
16,839
def _get_resource_info( resource_type="pod", labels={}, json_path=".items[0].metadata.name", errors_to_ignore=("array index out of bounds: index 0",), verbose=False, ): """Runs 'kubectl get <resource_type>' command to retrieve info about this resource. Args: ...
b9a98fe469eb7aa5fcfb606db0948cb53410ddec
16,840
def rotate_line_about_point(line, point, degrees): """ added 161205 This takes a line and rotates it about a point a certain number of degrees. For use with clustering veins. :param line: tuple contain two pairs of x,y values :param point: tuple of x, y :param degrees: number of degrees t...
c5954604d6f7852e66fe7b19f53193271582619d
16,841
def arith_relop(a, t, b): """ arith_relop(a, t, b) This is (arguably) a hack. Represents each function as an integer 0..5. """ return [(t == 0).implies(a < b), (t == 1).implies(a <= b), (t == 2).implies(a == b), (t == 3).implies(a >= b), (t == 4).implies(a > b), ...
8b06d545e8d651803683b36facafb647f38fb2ff
16,842
import logging def initialise_framework(options): """This function initializes the entire framework :param options: Additional arguments for the component initializer :type options: `dict` :return: True if all commands do not fail :rtype: `bool` """ logging.info("Loading framework please ...
e62b34189e330fdaea7ec6c81084616bd015a587
16,843
def get_registration_form() -> ConvertedDocument: """ Вернуть параметры формы для регистрации :return: Данные формы профиля + Логин и пароль """ form = [ gen_field_row('Логин', 'login', 'text', validate_rule='string'), gen_field_row('Пароль', 'password', 'password'), ...
76bcab98d840523e94234c456cb1ccbd2b1f9129
16,844
def get_docker_stats(dut): """ Get docker ps :param dut: :return: """ command = 'docker stats -a --no-stream' output = st.show(dut, command) return output
cd994701c622ce9ea1f6f123f24b9913aa02698d
16,845
import argparse import os def parse_commandline_arguments(): """Parses command line arguments and adjusts internal data structures.""" # Define script command line arguments parser = argparse.ArgumentParser(description='Run object detection inference on input image.') parser.add_argument('-w', '--wor...
fdefe92824917b18b5aff89c13362ed5dbca0be5
16,846
import os def fetch_latency(d: str, csim: bool = False): """Fetch the simulated latency, measured in cycles.""" tb_sim_report_dir = os.path.join( d, "tb" if not csim else "tb.csim", "solution1", "sim", "report" ) if not os.path.isdir(tb_sim_report_dir): return None tb_sim_report =...
881078f338f5dee611725ab8a06331f09e1ca45c
16,847
def enthalpyvap(temp=None,pres=None,dvap=None,chkvals=False, chktol=_CHKTOL,temp0=None,pres0=None,dvap0=None,chkbnd=False, mathargs=None): """Calculate ice-vapour vapour enthalpy. Calculate the specific enthalpy of water vapour for ice and water vapour in equilibrium. :arg temp: Temper...
dadc59bf28272de3a298b89cb13901825fd58c95
16,848
async def get_eng_hw(module: tuple[str, ...], task: str) -> Message: """ Стандартный запрос для английского """ return await _get_eng_content('zadanie-{}-m-{}-z'.format(*module), task)
15e5425173c643074dde08c6753ffcd333414565
16,849
def _choose_split_axis(v: Variable) -> Axis: """ For too-large texture `v`, choose one axis which is the best one to reduce texture size by splitting `v` in that axis. Args: v: Variable, whose size is too large (= this variable has :code:`SplitTarget` attribute) Returns: axis """ ...
b48acb753dc357464103e963a2c1d5470051cf11
16,850
import json def get_image_blobs(pb): """ Get an image from the sensor connected to the MicroPython board, find blobs and return the image, a list of blobs, and the time it took to find the blobs (in [ms]) """ raw = json.loads(run_on_board(pb, script_get_image, no_print=True)) img = np.flip(np.tran...
5d563aeb490c5c1d509e442a3f7210bcfd9d6779
16,851
def classification_report(y_true, y_pred, digits=2, suffix=False): """Build a text report showing the main classification metrics. Args: y_true : 2d array. Ground truth (correct) target values. y_pred : 2d array. Estimated targets as returned by a classifier. digits : int. Number of dig...
6158c82879b2894c96479bb96f986e348ef02b00
16,852
def tidy_conifer(ddf: DataFrame) -> DataFrame: """Tidy up the raw conifer output.""" result = ddf.drop(columns=["marker", "identifier", "read_lengths", "kraken"]) result[["name", "taxonomy_id"]] = result["taxa"].str.extract( r"^(?P<name>[\w ]+) \(taxid (?P<taxonomy_id>\d+)\)$", expand=True ) ...
88e55855d5f9ca8859a0e058a593aadd44774387
16,853
import os def load(name=None): """ Loads or initialises a convolutional neural network. """ if name is not None: path = os.path.join(AmfConfig.get_appdir(), 'trained_networks', name) else: path = AmfConfig.get('model') if path is not None and os.path.isfile(path): ...
cdd052a8a41fcb662ebd26aee51cdc05439be419
16,854
import collections def get_duplicates(lst): """Return a list of the duplicate items in the input list.""" return [item for item, count in collections.Counter(lst).items() if count > 1]
8f10226c904f95efbee447b4da5dc5764b18f6d2
16,855
def relu(x, alpha=0): """ Rectified Linear Unit. If alpha is between 0 and 1, the function performs leaky relu. alpha values are commonly between 0.1 and 0.3 for leaky relu. Parameters ---------- x : numpy array Values to be activated. alpha : float, optional Th...
f18b331ef66d14a29e1ad5f14b610af583ea7b3a
16,856
def build_unique_dict(controls): """Build the disambiguated list of controls Separated out to a different function so that we can get the control identifiers for printing. """ name_control_map = UniqueDict() # collect all the possible names for all controls # and build a list of them ...
931b90a34e151550c399b314d368a54e3c816796
16,857
def serialize_thrift_object(thrift_obj, proto_factory=Consts.PROTO_FACTORY): """Serialize thrift data to binary blob :param thrift_obj: the thrift object :param proto_factory: protocol factory, set default as Compact Protocol :return: string the serialized thrift payload """ return Serializer...
f6845b7539da82dc0555e11b0013db034d297e70
16,858
from typing import Optional def signal( fn: Optional[WorkflowSignalFunc] = None, *, name: Optional[str] = None, dynamic: Optional[bool] = False, ): """Decorator for a workflow signal method. This is set on any async or non-async method that you wish to be called upon receiving a signal. I...
8e6f3581590a7a429b4e5e838241328deb817e96
16,859
from matplotlib.colors import LinearSegmentedColormap def cmap_RdBu(values, vmin = None, vmax = None): """Generates a blue/red colorscale with white value centered around the value 0 Parameters ---------- values : PandasSeries, numpy array, list or tuple List of values to be used for creating...
b6bb207a8a1cccf13b87212125f74287b2a3cc9a
16,860
def _add_noise(audio, snr): """ Add complex gaussian noise to signal with given SNR. :param audio(np.array): :param snr(float): sound-noise-ratio :return: audio with added noise """ audio_mean = np.mean(audio**2) audio_mean_db = 10 * np.log10(audio_mean) noise_mean_db = snr - audio...
4f77e7a2893dc0bdcaf5e170c5e17371127b80d5
16,861
from tvm.relay.testing import mlp def mlp_net(): """The MLP test from Relay. """ return mlp.get_net(1)
4e48dfb04bab1434bd581b7fc6cd5e2257c88022
16,862
def build_ind_val_dsets(dimensions, is_spectral=True, verbose=False, base_name=None): """ Creates VirtualDatasets for the position or spectroscopic indices and values of the data. Remember that the contents of the dataset can be changed if need be after the creation of the datasets. For example if one o...
8876a9e61fd51a1e517adc7fb210172dc28e1b1e
16,863
def groupByX(grp_fn, messages): """ Returns a dictionary keyed by the requested group. """ m_grp = {} for msg in getIterable(messages): # Ignore messages that we don't have all the timing for. if msg.isComplete() or not ignore_incomplete: m_type = grp_fn(msg) ...
9ebf63cfe81e8c8b6f19d90c725415cafdbcd636
16,864
import math def regular_poly_circ_rad_to_side_length(n_sides, rad): """Find side length that gives regular polygon with `n_sides` sides an equivalent area to a circle with radius `rad`.""" p_n = math.pi / n_sides return 2 * rad * math.sqrt(p_n * math.tan(p_n))
939ff5de399d7f0a31750aa03562791ee83ee744
16,865
def dbl_colour(days): """ Return a colour corresponding to the number of days to double :param days: int :return: str """ if days >= 28: return "orange" elif 0 < days < 28: return "red" elif days < -28: return "green" else: return "yellow"
46af7d57487f17b937ad5b7332879878cbf84220
16,866
def create_model(data_format): """Model to recognize digits in the MNIST data set. Network structure is equivalent to: https://github.com/tensorflow/tensorflow/blob/r1.5/tensorflow/examples/tutorials/mnist/mnist_deep.py and https://github.com/tensorflow/models/blob/master/tutorials/image/mn...
d6fe45e5cfef5246a220600b67e24cddceeebd3a
16,867
def run_noncentered_hmc(model_config, num_samples=2000, burnin=1000, num_leapfrog_steps=4, num_adaptation_steps=500, num_optimization_steps=2000): """Given a (centred) model, this function transform...
95065fb8c8ee778f0d300b46f285f8f3bb026aed
16,868
import collections def get_project_apps(in_app_list): """ Application definitions for app name. Args: in_app_list: (list) - names of applications Returns: tuple (list, dictionary) - list of dictionaries with apps definitions dictionary of warnings """ apps = [] wa...
4e9be8ffddf44aba740414a8ee020376eda3a761
16,869
def read(G): """ Wrap a NetworkX graph class by an ILPGraph class The wrapper class is used store the graph and the related variables of an optimisation problem in a single entity. :param G: a `NetworkX graph <https://networkx.org/documentation/stable/reference/introduction.html#graphs>`__ :retur...
cb5db29d210d944047dbdf806ecfaaa274d517e8
16,870
def slog_det(obs, **kwargs): """Computes the determinant of a matrix of Obs via np.linalg.slogdet.""" def _mat(x): dim = int(np.sqrt(len(x))) if np.sqrt(len(x)) != dim: raise Exception('Input has to have dim**2 entries') mat = [] for i in range(dim): row ...
20b4016653d83303ac671a5d2641d4c344393b0a
16,871
def make_optimiser_form(optimiser): """Make a child form for the optimisation settings. :param optimiser: the Optimiser instance :returns: a subclass of FlaskForm; NB not an instance! """ # This sets up the initial form with the optimiser's parameters OptimiserForm = make_component_form(optimis...
745c4a9c4268d31687215f4acec709a5eacfcbf0
16,872
def prepare_for_evaluate(test_images, test_label): """ It will preprocess and return the images and labels for tesing. :param original images for testing :param original labels for testing :return preprocessed images :return preprocessed labels """ test_d = np.stack([preprocessing_for_te...
abe60fc558c6cc2c951a4efee758d2746608d8d1
16,873
def ab_group_to_dict(group): """Convert ABGroup to Python dict. Return None if group is empty.""" d = {'name': '', 'emails': [], 'is_group': True, 'is_company': False} d['name'] = group.valueForProperty_(AB.kABGroupNameProperty) for person in group.members(): identifier = group.distributionIden...
49f86b7ee4c4b4ce7f9f8c3db1811439e5fa5926
16,874
async def async_setup(hass, config): """Set up the PEVC modbus component.""" hass.data[DOMAIN] = {} return True
cde898e2904f8e9cfcf60d260ee2476326877dd9
16,875
from typing import Any def deserialize_value(val: str) -> Any: """Deserialize a json encoded string in to its original value""" return _unpack_value( seven.json.loads(check.str_param(val, "val")), whitelist_map=_WHITELIST_MAP, descent_path="", )
d01ce83488ea743aae298b15d1fe5f4faac6adbc
16,876
import binascii import os def gen_signature(priv_path, pub_path, sign_path, passphrase=None): """ creates a signature for the given public-key with the given private key and writes it to sign_path """ with salt.utils.files.fopen(pub_path) as fp_: mpub_64 = fp_.read() mpub_sig = sign_...
b3bc99fc0faf38cc83e7d441417147d9fc127b66
16,877
import six import collections def stringify(value): """ PHPCS uses a , separated strings in many places because of how it handles options we have to do bad things with string concatenation. """ if isinstance(value, six.string_types): return value if isinstance(value, collections.It...
1ca24ff986f3cd02c845ad0e11b8b1cfd3c7f779
16,878
def read_requirements_file(path): """ reads requirements.txt file """ with open(path) as f: requires = [] for line in f.readlines(): if not line: continue requires.append(line.strip()) return requires
ab224bd3adac7adef76a2974a9244042f9aedf84
16,879
def vsa_get_all(context): """ Get all Virtual Storage Array records. """ session = get_session() return session.query(models.VirtualStorageArray).\ options(joinedload('vsa_instance_type')).\ filter_by(deleted=can_read_deleted(context)).\ all()
3568997b060fbeab115ec79c2c0cba77f78c6cba
16,880
import os import glob import logging def find_files_match_names_across_dirs(list_path_pattern, drop_none=True): """ walk over dir with images and segmentation and pair those with the same name and if the folder with centers exists also add to each par a center .. note:: returns just paths :param lis...
3ee8b79ccce1c7b873037bb59067acbb893df047
16,881
import threading def thread_it(obj, timeout = 10): """ General function to handle threading for the physical components of the system. """ thread = threading.Thread(target = obj.run()) thread.start() # Run the 'run' function in the obj obj.ready.wait(timeout = timeout) # Clean u...
02ed60a560ffa65f0364aa7414b1fda0d3e62ac5
16,882
def _subsize_sub_pixel_align_cy_ims(pixel_aligned_cy_ims, subsize, n_samples): """ The inner loop of _sub_pixel_align_cy_ims() that executes on a "subsize" region of the larger image. Is subsize is None then it uses the entire image. """ n_max_failures = n_samples * 2 sub_pixel_offsets = np...
f96a2bc9b4c55976fd4c49da3f59afa991c53ff1
16,883
def obj_setclass(this, klass): """ set Class for `this`!! """ return this.setclass(klass)
4447df2f3055f21c9066a254290cdd037e812b64
16,884
def format(number, separator=' ', format=None, add_check_digit=False): """Reformat the number to the standard presentation format. The separator used can be provided. If the format is specified (either 'hex' or 'dec') the number is reformatted in that format, otherwise the current representation is kept...
6890ed398eb7c173540c0392b9ed8ef66f8d170b
16,885
def parse_equal_statement(line): """Parse super-sequence statements""" seq_names = line.split()[1:] return seq_names
ee0de00a990ac10c365af16dccf491b7ea8ed785
16,886
def B5(n): """Factor Variables B5.""" return np.maximum(0, c4(n) - 3 * np.sqrt(1 - c4(n) ** 2))
bc2fbd91e337310fe5d4326d55440ce2055da650
16,887
def y_yhat_plots(y, yh, title="y and y_score", y_thresh=0.5): """Output plots showing how y and y_hat are related: the "confusion dots" plot is analogous to the confusion table, and the standard ROC plot with its AOC value. The y=1 threshold can be changed with the y_thresh parameter. """ # The ...
82a8154bd618cc1451a44b2b42fca0407e9979cb
16,888
def _derive_scores(model, txt_file, base_words): """ Takes a model, a text file, and a list of base words. Returns a dict of {base_word: score}, where score is an integer between 0 and 100 which represents the average similarity of the text to the given word. """ with open(txt_file, 'r') as...
9c377b5dec742f5ba174f780252fd78d162a8713
16,889
import os def verifyRRD(fix_rrd=False): """ Go through all known monitoring rrds and verify that they match existing schema (could be different if an upgrade happened) If fix_rrd is true, then also attempt to add any missing attributes. """ global rrd_problems_found global monitorAggregato...
485842bcf262059125b9d9d6af91bb7c97b82704
16,890
def features_ids_argument_parser() -> ArgumentParser: """ Creates a parser suitable to parse the argument describing features ids in different subparsers """ parser = ArgumentParser(add_help=False, parents=[collection_option_parser()]) parser.add_argument(FEATURES_IDS_ARGNAME, nargs='+', ...
df24ebaff182c88c7ad6cf38e2e4a5784d54a48b
16,891
def isolate_blue_blocks(image, area_min=10, side_ratio=0.5): """Return a sequence of masks on the original area showing significant blocks of blue.""" contours, _ = cv2.findContours( blue(image).astype(np.uint8) * 255, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE ) rects = [] for c in contours: ...
7cd6e895750f208e18c60a48d2bc0e8d1710d6c0
16,892
from typing import Union from io import StringIO from pathlib import Path from typing import Optional from typing import Dict from typing import Callable from typing import List from typing import Tuple def read_gtf( filepath_or_buffer: Union[str, StringIO, Path], expand_attribute_column: bool = True, inf...
c7478d88ce5d6d6e823bf28c965f366b9b8d1522
16,893
from whoosh.filedb.filestore import FileStorage from sys import version def version_in(dirname, indexname = None): """Returns a tuple of (release_version, format_version), where release_version is the release version number of the Whoosh code that created the index -- e.g. (0, 1, 24) -- and format_version...
25b9f2416fa5d0213b24785aedbd5afd43edfba6
16,894
def trimAlphaNum(value): """ Trims alpha numeric characters from start and ending of a given value >>> trimAlphaNum(u'AND 1>(2+3)-- foobar') u' 1>(2+3)-- ' """ while value and value[-1].isalnum(): value = value[:-1] while value and value[0].isalnum(): value = value[1:] ...
e9d44ea5dbe0948b9db0c71a5ffcdd5c80e95746
16,895
def hrm_job_title_represent(id, row=None): """ FK representation """ if row: return row.name elif not id: return current.messages.NONE db = current.db table = db.hrm_job_title r = db(table.id == id).select(table.name, limitby = (0, 1)).first() ...
ca3d2bfb4056b28b712f4cbf37c8c91d840c0161
16,896
def is_empty_array_expr(ir: irast.Base) -> bool: """Return True if the given *ir* expression is an empty array expression. """ return ( isinstance(ir, irast.Array) and not ir.elements )
dcf3775e7544ad64e9a533238a9549ed21dc3393
16,897
def get_raw_entity_names_from_annotations(annotations): """ Args: annotated_utterance: annotated utterance Returns: Wikidata entities we received from annotations """ raw_el_output = annotations.get("entity_linking", [{}]) entities = [] try: if raw_el_output: ...
482be69ef5fec52b70ade4839b48ae2f4155033b
16,898
def nextPara(file, line): """Go forward one paragraph from the specified line and return the line number of the first line of that paragraph. Paragraphs are delimited by blank lines. It is assumed that the current line is standalone (which is bogus). - file is an array of strings - line is the...
a104042225bc9404a5b5fe8f5410a3021e45f64d
16,899