content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Sequence import fnmatch def _should_ignore(fd_name: str, patterns: Sequence[str]) -> bool: """Return whether `fd_name` should be ignored according to `patterns`. Examples -------- >>> fd_name = "google/protobuf/empty.proto" >>> pattern = "google/protobuf/*" >>> _should_igno...
8bf698afddbda869e26ebcaa98e1f4e950117c08
34,300
def unc_inertia_eval(awg, afg, bout, bi, mw, ed, out_xml): """ Unconventional aircraft Moment of Inertia analysis main function. It dvides the cases defined and evaluates them calling the function in the with_fuse_geom subfolder. Source: An introduction to mechanics, 2nd ed., D. Kleppner ...
cff3ebe8f0e613c5742c3d16bae29dfcc0998d2a
34,301
import json def str2body(v): """ convert str to json data or keep original string :param v: :return: """ try: return json.loads(v) except: return v
5785d9dca1d1120a4827feb93382d1d0bf68519a
34,302
from datetime import datetime def get_default_law_key(): """ Default key needs to be unique timestamp until changed """ x = str(datetime.now()) key = x[5:25] return key
569d1ff7cc9c6d0e95dded80c1e068ff885e95c7
34,303
def _evaluate_Delaunay_component( subgraph_RE_comp: nx.Graph, subgraph_R_comp: nx.Graph, subgraph_E_comp: nx.Graph, num_R: int, ): """ Phase 3 Evaluates given graph-connected component. :param subgraph_RE_comp: Delaunay graph of the component containing R and E points.. :param subgra...
98f12800201cf89f3a92c07d93d9b446e019ec60
34,304
def calculate_fees(sat_per_vbyte: int, num_p2wkh_inputs: int, num_np2wkh_inputs, num_channels: int, has_change=False) -> int: """Calculates the size (in vbytes) of a transaction and determines the fee.""" # see also https://github.com/btcsuite/btcwallet/tree/master/wallet/txsizes/size.go ...
c75335c9aa9c722e5c8e3493075828c67c2f9f19
34,305
import imp from importlib.machinery import SourceFileLoader import importlib.util import types import os import sys def load_module(path, module_name=None): """Load python module from file Args: path: python file path module_name: import as `module_name` name. If none, use `path[:-3]` """ ...
3914e335793b7af8619a8f0ee6e9556cd2faa084
34,306
def abcd_normalize(A=None, B=None, C=None, D=None): """Check state-space matrices and ensure they are two-dimensional. If enough information on the system is provided, that is, enough properly-shaped arrays are passed to the function, the missing ones are built from this information, ensuring the corre...
2292347708f93570d96062d6e94058e55c96b112
34,307
import subprocess def RunGetOutput(cmd, chk_err=True, log_cmd=True): """ Wrapper for subprocess.check_output. Execute 'cmd'. Returns return code and STDOUT, trapping expected exceptions. Reports exceptions to Error if chk_err parameter is True """ if log_cmd: LogIfVerbose(cmd) try...
82ca20f83d29323930b179525a0cf167e3d9221a
34,308
def extract_full_symbol(full_symbol: str): """ :return: (symbol, exchange) """ tmp = full_symbol.split(' ') if len(tmp) < 4: return "unknwonsymbol", Exchange.SHFE symbol = tmp[2] + tmp[3] exchange_str = tmp[0] ex = Exchange(exchange_str) if ex in [Exchange.SHFE, Exchange.DCE,...
7e031bfb969215092765a33cdb93377a6c98d922
34,309
def remove(user_id): """User removing""" user = User.query.get(user_id) db.session.delete(user) db.session.commit() flash('User "%s" successfully remove' % user.name, 'success') return redirect(url_for('backend.index'))
33ced3d0e54a3edcc04e89440faca6778dd65944
34,310
from typing import Dict from typing import List from typing import Tuple def phonemes_to_sentences( arpabet: Dict[str, List[List[str]]], data: Tuple[List[list], ...], print_every: int, of: int, ) -> Tuple[str, ...]: """Convert list of phoneme lists to sentences.""" data = [ ( ...
25f21e79f5029a80adeb4bd277c273db1e0caf31
34,311
import random def submit(): """ Submit one name. """ # TODO captcha try: if request.form.get('name'): # egg name = _process_name(request.form.get('name')) database.add_name(name) elif request.form.get('fullname'): name = _process_name...
482048aea25583de3a4431871ea2eb6c52f24c5e
34,312
def butter_bandpass_filter(flux, lowcut, fs, order=3): """ Apply a Butterworth high-pass filter. Args: flux (array): The flux array. lowcut (float): The frequency cut off. fs (array): The frequency array. order (Optional[int]): The order of the Butterworth filter. Default ...
aed17a9f43292a5c7274e3ad0d708aabf14e4404
34,313
def main(filepath=None): """execution starts here""" # print("main():") if filepath==None: filepath = r"C:\Program Files\7-Zip\7z.exe" print("Getting Metadata From File: " + filepath) parser = hachoir.parser.createParser(str(filepath)) metadata = hachoir.metadata.extractMetadata(parser)...
eb6f8d3086cd3e527be7a7d2f4c79453fed2f21c
34,314
def calculate_background_gradient(u, v, w, weights, u_back, v_back, Cb=0.01): """ Calculates the gradient of the background cost function. For each u, v this is given as 2*coefficent*(analysis wind - background wind). Parameters ---------- u: Float array Float array with u component of ...
bab0558148faf3694c7b5c4db174af69c70fd526
34,315
def read_embedding_vocabularies(filenames): """ Reads every vector embedding file in the given collection of filenames, and returns the union of their vocabularies. (The files are assumed to be hdf5 files containing dataframes, and the vocabularies are their indices. """ result = pd.Inde...
17c72725cc8fe06ac000a00eb76fc19bb98e6dc5
34,316
def sorted_keys(lut: dict) -> list: """returns sorted lut keys if env_flags[sorted] is set to True""" if env_flags['sorted'] is True or str(env_flags['sorted']).lower() == 'true': return sorted(lut.keys(), key=lambda x: x) return lut.keys()
db801d14096af85de679ccf26c7ef3045b992a69
34,317
def sigmax(dim=2): """Qiskit wrapper of sigma-X operator. """ if dim == 2: return ops.sigmax() else: raise Exception('Invalid level specification of the qubit subspace')
a27ec81ad0396167c6207120a031375816b463ec
34,318
def is_relative_path(p): """ Return True if path is relative """ p = p.replace('\\', '/') if p and p[0] == '/': return False if sabnzbd.WIN32 and p and len(p) > 2: if p[0].isalpha() and p[1] == ':' and p[2] == '/': return False return True
0368ea2588344f90eb915f7144f0b60145b13b74
34,319
import types def setting_keybord( is_admin: bool, language: str, session_timeout: int ) -> types.InlineKeyboardMarkup: """انشاء كيبورد الاعدادات المعطيات: is_admin (bool): هل الكيبورد مرسل لادمن language (str): لغة االكيبورد session_timeout (int): وقت الجلسة المخرجات: ...
c53f2dd95dae6bb972789ab81d1d15ba6ddb5be4
34,320
def IoU(bbox1, bbox2): """Compute IoU of two bounding boxes Args: bbox1 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of the bounding box, and (w, h) are width and height of the box. bbox2 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of the bou...
dfb7aabac557a4ca71fe989da94e3775233d734b
34,321
import multiprocessing import time import csv def query_GTEx_service( snps, genes, to_query, p_values, num_processes, output_dir): """Queries GTEx for eQTL association between SNP and gene. Args: snps: The dictionary of SNP fragments returned from proce...
82700c806ca82ec723620ac61926a8d6c74ec82c
34,322
def filter_red_pen(rgb, output_type="bool"): """ Create a mask to filter out red pen marks from a slide. Args: rgb: RGB image as a NumPy array. output_type: Type of array to return (bool, float, or uint8). Returns: NumPy array representing the mask. """ result = ( ...
33f78f9048754e306fbd1a9a783eff79a7442ed8
34,323
import shutil def project_delete(request, project_slug): """ Make a project as deleted on POST, otherwise show a form asking for confirmation of delete. """ project = get_object_or_404(request.user.projects.live(), slug=project_slug) if request.method == 'POST'...
0bd8bd63a51892438fb321487d8538630fe21854
34,324
def compose_left(*funcs): """Compose sync and async functions to operate in series. Returns a function that applies other functions in sequence. The returned function will be an async function iff at least one of the functions in the sequence is async. Functions are applied from left to right so t...
ea02215c46b369cea993dc5565937807e76b584f
34,325
def squarefree_part(x, timeout_duration=20, use_ecm=True): """return the squarefree part of x or 'NO DATA (timed out)'""" F = squarefree_and_factorization( x=x, timeout_duration=timeout_duration, use_ecm=use_ecm ) if isinstance(F, str): return F else: return F[0]
3143aa9032b65f22631488a7f8dd96b0ae71cb4c
34,326
def unix_time_to_id(unix_time): """ Converts the given unix time to id. Parameters ---------- unix_time : `int`, `float` The unix time to convert to id. Returns ------- id_ : `int` """ return (floor(unix_time*1000.)-DISCORD_EPOCH)<<22
50b40ab1e23971b8ba44cfdd6546158b42415d66
34,327
def method_withBadName_with_bad_params_on_single_line(myBadlyNamedParam, my_other_Bad_name): """Provide parameters with bad names on single line.""" return myBadlyNamedParam + my_other_Bad_name
10857c53fb36ef96ebfc4cd10b52b412b600836a
34,328
async def async_setup_platform( hass, config, async_add_devices, discovery_info: object = {} ): """Set up Loxone Sensor from yaml""" value_template = config.get(CONF_VALUE_TEMPLATE) if value_template is not None: value_template.hass = hass # Devices from yaml if config != {}: # ...
36a896270e448b50121d685aa3048006b7246abe
34,329
from datetime import datetime def build_cal_args(args): """Determine the year/month. Return list [year] or [year, month]""" t = datetime.date.today() m, y = t.month, t.year x = None if len(args) == 0: # no args - print default calendar x = [y, m] elif len(args) == 1: ...
241630f6a15f1a8c2ac195740aba8a7307b763ba
34,330
def reorder_cube_coord( cube, indices, new_coord_points=None, *, promote=True, **coord_kwargs ): """Use indices and the corresponding axis to reorder a cube's data along that axis. Args: cube (iris.cube.Cube): Cube to be modified. indices (1-D iterable): Indices used to select new ordering ...
5f4cb78a9111fb9048fc7b6ac87e58be5da31f2d
34,331
import os def file_parts(file_path): """ Lists a files parts such as base_path, file name and extension Example base, name, ext = file_parts('path/to/file/dog.jpg') print(base, name, ext) --> ('path/to/file/', 'dog', '.jpg') """ base_path, tail = os.path.split(file_path) name...
3f366dcd54bcc6e218655e1df038541a20de66d2
34,332
import time def verify(ctx, config): """ :param PxContext ctx: :param pxConfig config: :return bool: is request verified """ logger = config.logger logger.debug('Evaluating Risk API request, call reason: {}'.format(ctx.s2s_call_reason)) try: start = time.time() respons...
1f8b817f73afd205b4609b838c589b418822ad5f
34,333
import os def get_or_train_cav(concepts, bottleneck, acts, cav_dir=None, cav_hparams=None, overwrite=False): """Gets, creating and training if necessary, the specified CAV. Assumes the activations already exi...
dfa853b43d5a95d6ba084659736b233f469cd6d7
34,334
def _dice(array): """Given an array containing true/false positive/negative columns for the 'shadow' class, calculates the dice coefficient.""" v = {'TP': 0, 'TN': 0, 'FP': 0, 'FN': 0} for val in v: v[val] = float(np.sum(array['Shadow ' + val])) dice = v['TP'] / ((v['FP'] + v['TP']) + (v[...
644f1e5d982b9d5239f2b339ae4bdd14c10ebc73
34,335
import math def euclidian_dist(p1, p2): """ p1 and p2 must both be of len 2 where p1 = (x1,y1); p2 = (x2,y2)""" return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2)
3bceb46cf311e418cac83370c673772f885587be
34,336
def colorify_by_name(image, cmap_name, flip_map=False, rescale_type='min_max', limits=None, num_colors=256): """ Return 2D image as 3D RGB stack colored with a given colormap. Parameters ---------- image: 2d array image to convert to RGB cmap_name: str Matplotlib colormap or...
68a034150e327c3fbef2603f422d18e935dec590
34,337
import numpy def lazy_matrix_mul(m_a, m_b): """ multiply 2 matrix that is given Args: m_a: input first matrix m_b: input second matrix Returns: return m_a * m_b """ return numpy.matmul(m_a, m_b)
3e58214d944d1962260b747af53dc8c82cc79b40
34,338
def denormalize_tags(df: pd.DataFrame) -> pd.DataFrame: """ For a DataFrame with a column 'tags' that contains comma-space-separated tags, denormalize the 'tags' column. """ if df.empty: return add_missing_columns(df, required_columns=['tag']) df = df.copy() df['tags'] = df['tags'].str.spli...
ce61cd49041a6238fc91bb1256ee0357944dc71e
34,339
import gzip def read_consanguineous_samples(path, cutoff=0.05): """ Read inbreeding coefficients from a TSV file at the specified path. Second column is sample id, 6th column is F coefficient. From PLINK: FID, IID, O(HOM), E(HOM), N(NM), F Additional columns may be present but will be ignored. ...
be3515e6704966ae927bfaff2594be9191063889
34,340
from re import T def component(graph: Graph[T], node: T) -> Graph[T]: """Returns the connected component that contains the given vertex, as a new Graph object. A vertex with no incident edges is itself a component. A graph that is itself connected has exactly one component, consisting of the whole graph. ...
6d1d23b28e35f291e79369f39e66d7444f0395ba
34,341
import six from datetime import datetime import typing def _deserialize(data, klass): """Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object. """ if data is None: return None if klass ...
7f008dc9edcdb433fe6561f5ad30695e8103c347
34,342
def smooth(data, fwhm, mask = 0): """ smooth Parameters --------------------- data an object of class field fwhm mask a numpy.nd array, with the same dimensions as the data Returns --------------------- An object of class field with Examples --------------...
feba63fe44605c4c59ca9b83794daad046ac3244
34,343
def get_xy_coords(xda): """Return the dimension name for x and y coordinates e.g. XC or XG Parameters ---------- xda : xarray DataArray with all grid information Returns ------- x,y : str with e.g. 'XC' or 'YC' """ x = 'XC' if 'XC' in xda.coords else 'X...
6aca5de1eda17df617027c742a06f97cf77af1d5
34,344
import attr def make_klass(spec): """ Create a data class given a spec. Parameters ---------- spec : TODO """ if spec is None: return None fields = spec.fields if fields: newfields = dict() for item in fields: if len(item) == 2: ...
61e25fc67e517a08d460b63341aa34c78716ea6d
34,345
def get_init_cell(batch_size, rnn_size): """ Create an RNN Cell and initialize it. :param batch_size: Size of batches :param rnn_size: Size of RNNs :return: Tuple (cell, initialize state) """ # TODO: Implement Function lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size) cell = tf.contrib.r...
db9599d05324ca5e62d98446ab7074f1e2059093
34,346
def remote_docker(client_ip, docker_host, *args): """ Run ``docker`` on ``client_ip``. :param bytes docker_host: The DOCKER_HOST environment variable to set before running ``docker``. :param args: Other command line arguments to supply to ``docker``. :returns: A ``Deferred`` when the comman...
cbbff3fdd1460c61dbbc48b4833bede2a60312aa
34,347
import argparse def make_parser(): """Makes the argument parser""" p = argparse.ArgumentParser("conda-suggest") subcmd = p.add_subparsers(dest="subcmd", help="subcommand to execute") # Generate commands gen = subcmd.add_parser("generate", help="create map files for a channel") gen.add_argument...
dae75c1a3eb8ead453e77d25fdf7c6c45dd05973
34,348
def aggregate_f(loc_fscore, length_acc, vessel_fscore, fishing_fscore, loc_fscore_shore): """ Compute aggregate metric for xView3 scoring Args: loc_fscore (float): F1 score for overall maritime object detection length_acc (float): Aggregate percent error for vessel length estimation ...
c3120882e50710d6874def60ad85e7a8be47c5d7
34,349
def index(request): """ Index view: shows a form with a list of ticket that one can buy """ ticket_types = TicketType.objects.all() form = TicketsForm(ticket_types,[], request.POST) if form.is_valid(): data = form.cleaned_data p = TicketPurchase() print data if da...
997ed750187586077d5ca24d17326d5f5510382e
34,350
from typing import Union def _on_vertex( easting: Union[int, float], northing: Union[int, float], resolution: int ) -> bool: """Test if point lies on vertex.""" return ( True if (int(easting) % resolution == 0) and (int(northing) % resolution == 0) else False )
06902474da9bfc49e209ada65d160c0fa7f28cbf
34,351
def add_jitter(df, jitter): """ Adds jitter to a data set based on a random normal distribution. Requirements: numpy, pandas """ return abs(df + np.random.normal(df, jitter, size=len(df)))
dc03d1506db3e21908a02a370122b8735167606b
34,352
import torch import itertools def collate_fn(batch): """Creates mini-batch tensors from the list of tuples (query, positive, negatives). Args: data: list of tuple (query, positive, negatives). - query: torch tensor of shape (3, h, w). - positive: torch tensor of shape (3, h, w)...
d6e4985b7b0e248f05e78684a2a09136da865799
34,353
def complete_graph(number_of_vertices, name="Complet graph", directed=False): """ Construction of a complete graph. The number of edges is exactly n*(n-1)/2 (where n is the number of vertices) :param number_of_vertices: :param name: :param directed: False for undirected graph :return: the ...
e603583abcc6e1de10f057965bf587cde1eebcc0
34,354
def obv(df, price, volume, obv): """ The On Balance Volume (OBV) is a cumulative total of the up and down volume. When the close is higher than the previous close, the volume is added to the running total, and when the close is lower than the previous close, the volume is subtracted from the running...
19f4c456ed501523d2b349e2766d482bd1fef13b
34,355
def is_data(line): """ Function utilized by itertool's groupby method in determining the delimiter between our blocks of data. """ return True if line.strip() else False
da3db970c5c5a3169446513cb4148ffedf598095
34,356
def update_license(license_id, **kwargs): """ Replace the License with given ID with a new License """ updated_license = licenses_api.get_specific(id=license_id).content for key, value in iteritems(kwargs): if value: setattr(updated_license, key, value) response = utils.che...
c500224309e71d0e14a641980deaa75714a9c117
34,357
def _browse_device(device_id: MediaId, device: Device) -> BrowseMediaSource: """Return details for the specified device.""" device_info = NestDeviceInfo(device) return BrowseMediaSource( domain=DOMAIN, identifier=device_id.identifier, media_class=MEDIA_CLASS_DIRECTORY, media_...
76f36c2cf5eedad06f527d78aa45fac1d6ea6b11
34,358
def get_organization_suggestions(config, donl_type): """ Get organization suggestions for a given type :param dict[str, Any] config: The configuration to use for selecting DONL organizations :param str donl_type: The DONL type to get suggestions for :rtype: list of...
6d306c49bc7671707479b5327e69a74320ebf3a6
34,359
def make_func_entry(func, name=None, description=None, params=None): """ Create a function docstring entry for a swig interface file. func - a doxyxml object from which documentation will be extracted. name - the name of the C object (defaults to func.name()) description - if this optional variable is ...
d5fb2067d0c69bc5cffc47376f3f91573c5cc1d4
34,360
import copy def instance_update(context, instance_uuid, values, session=None): """Updates an existing VM instance in the Database""" values = copy.deepcopy(values) power_specs = values.pop('power_specs', None) #Merge in the existing MetaData if they asked for Partial Updates _instance_merge_metada...
80296ff02a320bdf3192802bbde50d8adc6778c5
34,361
import subprocess def _cmd_7zip_list(src) -> bytes: """获取列表""" p = subprocess.run(["7z", "l", "-ba", src, "-p"], capture_output=True, timeout=1) return p.stdout or p.stderr
3f4be38dba9cf862576799866270dd7292952509
34,362
from bs4 import BeautifulSoup def xkcdt(): """ Return the title of the most recent xkcd, taken from the wesite's source code. """ page=BeautifulSoup(urllib2.urlopen('https://xkcd.com'),'lxml') return page.title.string
55f90a86d8e0410743a968bf1c3351f23709b728
34,363
import warnings def log_cpm_hvg(adata: ad.AnnData, n_genes: int = 1000) -> ad.AnnData: """Normalize logCPM HVG Normalize data to log counts per million and select n_genes highly variable genes """ adata = log_cpm(adata) if adata.n_vars < n_genes: warnings.warn( f"Less th...
ee9cda4caedde03d81fbc361a5c70d90c7bfc1f7
34,364
def c_string_arguments(encoding='UTF-8', *strings): """ Convenience function intended to be passed to in_format which allows easy arguments which are lists of null-terminated strings. """ payload = b"" # Add each string, followed by a null character. for string in strings: payload ...
5c93afae01d199f31a27f658e133024c8fb9f92f
34,365
async def create_mirror(request): """ Create a debian aptly mirror. --- description: Create a debian aptly mirror. tags: - Mirrors consumes: - application/x-www-form-urlencoded parameters: - name: name in: query required: true type: stri...
b6e60120580f25a967f19ec5ec7fff3fd0fa9478
34,366
def anneal(c_max, step, iteration_threshold): """Anneal function for anneal_vae (https://arxiv.org/abs/1804.03599). Args: c_max: Maximum capacity. step: Current step. iteration_threshold: How many iterations to reach c_max. Returns: Capacity annealed linearly until c_max. """ ...
ca6cbb5fe109e5d6b36870b398604ee79042827f
34,367
import json def update_timer_interval(acq_state, chart_data_json_str, chart_info_json_str, active_channels, samples_to_display): """ A callback function to update the timer interval. The timer is temporarily disabled while processing data by setting the interval to 1 day and the...
1bc695ab2e5d63d4734d27417efc3d17a5e3a471
34,368
def constant_change_luminance(img): """ luminance noise added to image :param img: image: numpy input image :return: blurred image """ # constant [-25, 25] constant = np.random.randint(-25, 25, size=(img.shape[0], img.shape[1], 1)) new_img = np.clip(img.astype(np.float32) - constant, 0.0...
e5e11a49db0c2ac051f7e8fb881f724ed94a1ad6
34,369
def rectify(x): """Rectify activation function :math:`\\varphi(x) = \\max(0, x)` Parameters ---------- x : float32 The activation (the summed, weighted input of a neuron). Returns ------- float32 The output of the rectify function applied to the activation. """ # Th...
f781c4a382d211fbcadfe599c470523d3a59c2f1
34,370
def login_form(): """Show login form.""" return render_template("login_form.html", loggingin=True)
9f70323f1936f9b68200e3e1c75dfd52c262bc44
34,371
def create_backup_options(logsync, dbs, logger): """ Creates the backup options string to be used in restore.sh script for source backup Args: logsync (string) : Are we enabling replication? dbs (string): Which databases are we backing up? Returns: backup_options (string): Compl...
bb2177e3c22637e25a65a08b8cfc1ebc65c8b50f
34,372
from typing import Union from typing import Sequence def truncate_batches(*xl: Union[dy.Expression, Batch, Mask, recurrent.UniLSTMState]) \ -> Sequence[Union[dy.Expression, Batch, Mask, recurrent.UniLSTMState]]: """ Truncate a list of batched items so that all items have the batch size of the input with t...
a39a4e8fec318b8e27ce6df1029051c07e058180
34,373
def get_loss_f(**kwargs_parse): """Return the loss function given the argparse arguments.""" return Loss(lamL1attr=kwargs_parse["lamL1attr"])
0389a9ca1799d7f98965caed7c0474543ed3c24a
34,374
import argparse def _add_cromwell_status_args(parser: argparse.ArgumentParser): """Add cli args for checking status of Cromwell workflow""" parser.add_argument('workflow_id') parser.add_argument('--json-output', help='Output metadata to this path') _add_generic_cromwell_visualiser_args(parser) r...
eececff5b596d513d67c83a4b0b9468e30805a71
34,375
def input_reading_mod(input_dir, input): """This helper convert input""" with open('%s/%s' %(input_dir, input), 'r') as input_fid: pred = input_fid.readlines() det = [x.strip('\n') for x in pred] return det
34fd8e5fe53d809ee1cc870c031bca8691756a63
34,376
async def connect(config, loop, protocol=None, session=None): """Connect and logins to an Apple TV.""" if config.identifier is None: raise exceptions.DeviceIdMissingError("no device identifier") service = config.main_service(protocol=protocol) supported_implementations = { const.PROTOC...
1f6357737ce93a69e0b75093a5da8c72aebbb660
34,377
def _is_none(s: str) -> bool: """Check if a value is a text None.""" if s == 'None': return True return False
b7a6118b2c04c965d808911405d23a168f0fbff3
34,378
def get_C_and_Ic(Cin_est, Icin_est, f01, f02on2): """Get the capacitance and critical current for a transmon of a certain frequency and anharmonicity. Args: Cin_est (float): Initial guess for capacitance (in fF) Icin_est (float): Initial guess for critical current (in nA) f01 (float...
ad7597b1e525a5d5818d6f79058cbe1213d38e2a
34,379
def read_positionfixes_postgis(sql, con, geom_col="geom", **kwargs): """Reads positionfixes from a PostGIS database. Parameters ---------- sql : str SQL query e.g. "SELECT * FROM positionfixes" con : str, sqlalchemy.engine.Connection or sqlalchemy.engine.Engine Connection string or...
f55f6934f675c76a99e544243b0f1cf779820e44
34,380
import logging def get_model(letters, max_length): """Create a LSTM model.""" logging.info("Create model") input_dim = len(letters) logging.info("input_dim=%i", input_dim) model = Sequential() model.add(LSTM(8, return_sequences=True, input_shape=(max_lengt...
0506c1f892ca2518b95c9edfc4deedfd8ebd4174
34,381
import time def attempt(task): # pragma: no cover """Offer the user a single task to perform.""" ui = UI() clock = time t = Task(task) wantToAttempt = ui.offerTask(task) if not wantToAttempt: # TODO: Do something with `reason`. reason = ui.requestReasonForDeferral(task) ...
51abd6bcdebc4bd1506bcfd82a19a0d90993b4f3
34,382
def _group_auto_update_helper(auto_update): """Helper that prepares the given group auto update for JSON serialization. :param GroupAutoUpdate auto_update: the auto update to serialize :return: dictionary suitable for JSON serialization :rtype: dict """ fields = { 'to': auto_upda...
fd95526cbea8d4888b7e581ab5eec5260f557517
34,383
def make_diag_scale(loc, scale_diag, scale_identity_multiplier, validate_args, assert_positive, name=None): """Creates a LinOp from `scale_diag`, `scale_identity_multiplier` kwargs.""" def _convert_to_tensor(x, name): return None if x is None else ops.convert_to_tensor(x, name=name) def _...
9cb8f10acb9cd6aa679a7e8274b88cb92e42f026
34,384
import pyemd def emd(hist1, hist2, cost_matrix='sift'): """ earth mover's distance by robjects(lpSovle::lp.transport) require: lpsolve55-5.5.0.9.win32-py2.7.exe CommandLine: python -m vtool.distance --test-emd Example: >>> # DISABLE_DOCTEST >>> from vtool.distance import ...
21a364ef673190ce2a25175154bd275ebc764506
34,385
def equal_angle_stereographic_projection_conv_YZ_plane(x,y,z): """Function to take 3D grid coords for a cartesian coord system and convert to 2D equal area projection.""" Y = y/(1+x) Z = z/(1+x) return Y,Z
121b24f20ef0ff7f0655a4b39c7ede70c632ef2a
34,386
def download_past_trees(test: bool, number: int): """ Download a number of past trees :param number: number of trees to download from the latest """ trees = [] key = "badger-tree.json" bucket = env_config.bucket response = s3.list_object_versions(Prefix=key, Bucket=bucket) versions =...
810ebc9ca714e4b9377bb7dd5d0cba0e9dd4089f
34,387
import re def read_init_values(srclines, init_names=None): """ srclines - an ODE-file content in the list of strings, if init_names is None all parameters will be read init_names - the list of parameters names return: the dict of parameters, where keys=pars_names, values are parsed from srclines ...
e793399c4d258134e3767c067b1754bcd820c430
34,388
def getCategorySentiments(termSentiData,trainLexicon,finalDF): """ Module to extract category-wise sentiment scores and generate final dataframe with predicted and true sentiment Args: termSentiData: dictionary of aspect terms and its sentiment trainLexicon: Lexicon of defining terms und...
d8efc2ea0d1ffb18d3949f104c21ce6eae923a2e
34,389
def get_test_pipeline(): """Return an arbitrary pipeline definition.""" return { 'sg1': [ 'step1', 'step2', {'step3key1': 'values3k1', 'step3key2': 'values3k2'}, 'step4' ], 'sg2': False, 'sg3': 77, 'sg4': None }
036cfdca7324be6940e1ed095292b0ac494ab771
34,390
def get_package_type(name): """ Returns the package type. Available package types are defined in PackageType. Only ASR9K supports Service Packs concept Example: asr9k-px-4.3.2.sp-1.0.0 or asr9k-px-4.3.2.k9-sp-1.0.0 """ if name.find(SMU_INDICATOR) != -1: return PackageType.SMU elif ...
89543d14c83f666c102dd11f3e093552b03c84d9
34,391
def merge(df1, df2, on=None, how="left"): """ DESCRIPTION ----------- Merge two pandas dataframes on a common field name or specified fields in each frame. PARAMETERS ---------- df1 : pd.DataFrame A pandas dataframe instance df2 : pd.DataFrame A pandas dataframe ins...
f297fcc005bdb6425ebb5306eae285c747ab46be
34,392
def resident_required(a_view): """居住者権限を持つユーザのみ実行を許可する 居住者権限を持つユーザとは 1 つ以上の community.Unit と関連づけられたユーザ. 不許可なら 403 Forbidden を返す. Args: a_view (func): ビュー関数 """ def _wrapped_view(request, *args, **kwargs): if request.user.unit_set.count(): return a_view(request, *args, **kwargs) else: return HttpRes...
db211cb5861bfd1c47d23fc30b20a7ebf3080a4b
34,393
def get_movie(id): """ Given a movie ID, return a movie with that ID, with the comments for that movie embedded in the movie document. The comments are joined from the comments collection using expressive $lookup. """ try: """ Ticket: Get Comments Please implement a $lo...
77f5cd27d78c308574dd7a5cb266ecf34f210a84
34,394
import logging def _stdout_logging(level): """Setup logging to stdout and return logger's `info` method. """ formatter = logging.Formatter( '%(levelname)s %(asctime)s %(module)s %(funcName)s(): %(message)s', '%Y-%m-%d %H:%M:%S') stdout = logging.StreamHandler() stdout.setLevel(leve...
a2fff81c0425b35f855c0372607d708f1c2aa3b4
34,395
def standardize_phone(raw: str) -> str: """Make sure it's 10 digits, remove everything else >>> standardize_phone("(555) 555-1212") '5555551212' """ raw = [x for x in raw if x.isnumeric()] raw = "".join(raw) if len(raw) != 10: raw = None return raw
a0d3afc2ffdaffee9d084ed7f50d49a1e3a023e0
34,396
async def find(req): """ Get a list of all existing group documents. """ cursor = req.app["db"].groups.find() return json_response([virtool.utils.base_processor(d) async for d in cursor])
d78fb6d84c18cbcdf07ee6d3699d58bd539e5fb2
34,397
from typing import Union from typing import List from typing import Dict from typing import Any def template_readable_response(responses: Union[dict, List[dict], str]) -> Union[str, List[Dict[str, Any]]]: """ Creates a readable response for responses that have fields in the form of: { 'def...
56b416aae9e254453855c27910d2e4d20365b6fc
34,398
def rehtml(content): """ does unicode bullshit :param content: :return: """ doc = UnicodeDammit(content, is_html=True) parser = ht.HTMLParser(encoding=doc.original_encoding) root = ht.fromstring(content, parser=parser) return root
157a1659c0b5af469acfddc175eb37376f1914af
34,399