content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def index(request): """Blog home page view""" blog_settings = BlogSettings.load() post_list = Post.get_displayable().all() page = request.GET.get("page") ret_dict = { 'blog_settings': blog_settings, 'posts': __get_post_page(post_list, page=page, blo...
9dac202c7748b8f3aa1740f82fe254352e49c360
47,100
def find_joins(df, ids, downstream_col="downstream", upstream_col="upstream", expand=0): """Find the joins for a given segment id in a joins table. Parameters ---------- df : DataFrame data frame containing the joins ids : list-like ids to lookup in upstream or downstream columns ...
39f16985ddd8e79338e520e56ba6ee793558d03f
47,101
def velocity(sigma, xs, ys, X, Y): """ Generalizing the one source case: xs, ys --> (1,) X, Y --> (nx, ny) sigma --> (1,) To the several sources one: xs, ys --> (ns, 1, 1) X, Y --> (ns, nx, ny) sigma --> (ns, 1, 1) """ sigma = np.atleast_1d(sigma)...
ab766a16e3bc27f269847d9e130430acd874e925
47,102
import functools def rate_limit(limit, period): """This decorator implements rate limiting.""" def decorator(f): @functools.wraps(f) def wrapped(*args, **kwargs): if current_app.config['USE_RATE_LIMITS']: # generate a unique key to represent the decorated function a...
78a83f85d24083ec7e1155326371a3cb26b56222
47,103
from typing import Optional def get_sketch_details(sketch_id: Optional[int] = 0) -> Text: """Return back details about an existing sketch. Args: sketch_id (int): the sketch ID to check. Returns: string containing information about the sketch. """ sketch = None state_obj = state.state() if not...
6730aa649b9b74275e3aa92b213b930fdeb2ef9d
47,104
import pkgutil import sys import os def finder_for_path(path): """ Return a resource finder for a path, which should represent a container. :param path: The path. :return: A :class:`ResourceFinder` instance for the path. """ result = None # calls any path hooks, gets importer into cache ...
d182f41de21f2616d33088a7de30723c77bb4e79
47,105
import copy import torch def dataProcessing(data_x, data_y, batch_size, training_ratio, validation_ratio, FM_indices, bool_norm=False): """ Data preprocessing. Parameters: ---------- data_x: 2D Array (nDOF x SampleNum). The deformation data (x SampleNum) of al...
e7dac71df8e11be2839f77f2397660ff12578076
47,106
def ten_interp(x, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9): """``Approximation degree = 10`` """ return ( a0 + a1 * x + a2 * (x ** 2) + a3 * (x ** 3) + a4 * (x ** 4) + a5 * (x ** 5) + a6 * (x ** 6) + a7 * (x ** 7)...
93ce278f784080602990f386164d71fd8290560f
47,107
def mock_interface_settings_match(mock_interface_settings): """ Fixture that yields mock USB interface settings that is the correct USB class, subclass, and protocol. """ mock_interface_settings.getClass.return_value = libusb.USB_DEVICE_CLASS mock_interface_settings.getSubClass.return_value = libusb...
ca97bf1af08abbc39407d99ec959caf425f2469e
47,108
def multinomial_naive_bayes_inference(X, W, b): """Multinomial naive Bayes classifier inference. Parameters ---------- X : ndarray, shape (m, n) input features (one row per feature vector). W : ndarray, shape (n, k) weight vectors, each row representing a different class. b : ...
4107e7cc5dbf22fdc874fc50d5e0736df74841c4
47,109
def sort_dist_matrix(mat, row_col_names): """ sort the distance matrix by seg_id_nat :return: """ df = pd.DataFrame(mat, columns=row_col_names, index=row_col_names) df = df.sort_index(axis=0) df = df.sort_index(axis=1) sensor_id_to_ind = {} for i, sensor_id in enumerate(df.columns): ...
09144b94db1d2f22ca1543e0e52cbab831e52e1c
47,110
def is_complete(step, lst): """ Check required field of question for complete state Required: question is always require user response to be complete Conditional: Optional question needed depends on reveal_response value of conditional_target. """ if not lst: return False, [] questio...
0ae26de169e9ee0eacfdb30cdf349345d42b8ca9
47,111
def mels_spectrogram(spec, sr, n_mels, fmin=64, fmax=None, top_db=80.0): """ Extracting mel-filter bands from power spectrum (i.e. the output from function `odin.preprocessing.signal.power_spectrogram`) Parameters ---------- spec : array [nb_samples, n_fft] power spectrum array s...
d64f562b50a22704f3f0f94f2c6b3d06539b7ba9
47,112
import torch def create_data_loader(data, batch_size=32, shuffle=True, drop_last=False): """ Create a data loader given numpy array x and y Args: data: a tuple (x, y, z, ...) where they have common first shape dim. Returns: Pytorch data loader """ if drop_last: batch_size = min(...
573c6d440812e8d9d504d621ace6db572c9acbb5
47,113
def set_order(order): """decorator to set callback's method order usage: @set_order(100) def method(self): pass """ def inner(meth): def fn(*args, **kwargs): return meth(*args, **kwargs) fn._order = order return fn return inner
60a051e87e9ad0b87511892d5d0545555049c1ab
47,114
from typing import Tuple def calculate_ci( values: np.ndarray, ci_level: float, **kwargs, ) -> Tuple[np.ndarray, np.ndarray]: """Calculate confidence/credibility levels using percentiles. Parameters ---------- values: The values used to calculate percentiles. ci_level: ...
cccff0595dcbfb1456a02d16f488997075492610
47,115
from typing import Optional from typing import Union from typing import List def plot__02__a( results: pd.DataFrame, ks: Optional[Union[List[int], int]] = None, min_class_support: int = 50, colormap_name: str = "fixed", sharey: str = "all", cf_level: str = "superclass", n_samples: int = 50, to...
1d3e4c501585486ee1943d457f4590a4c2455ba4
47,116
def display_calibration(probs, actual, *, figure=None, bins=100, label=None, show_ici=True, alpha=0.05, n_resamples=None, ...
7f2545c76f2c37079d15e3874cd5f63421ad6fa1
47,117
import math def max_crossing_subarray(given_array, start_index, mid_index, end_index): """Function To Calculate The Mid Crossing Sub Array Sum""" max_left_sum = - math.inf # Used For Sentinel Value max_right_sum = - math.inf # Used For Sentinel Value cross_start = None # Just used for variable pr...
1106b063b652e0d0d475f5b0979a138f4c48113b
47,118
def ignore_warnings(obj=None, category=Warning): """Context manager and decorator to ignore warnings. Note. Using this (in both variants) will clear all warnings from all python modules loaded. In case you need to test cross-module-warning-logging this is not your tool of choice. Parameters ----...
093fdbbc0728c3f98840c6fa54be2930cf2b9e6c
47,119
import json def create_sort_spec(model, sort_by, descending): """Creates sort_spec.""" sort_spec = [] if sort_by and descending: for field, direction in zip(sort_by, descending): direction = "desc" if direction else "asc" # we have a complex field, we may need to join ...
e2c486cf6b2188646c573ebf02447f6cfcbefdec
47,120
def css_classes(): """return settings or default""" return getattr(project_settings, 'DJALOHA_CSS_CLASSES', ())
21fd26e50044cd6de06000b9eb38e9b6eca6a487
47,121
import array def load_position(dir_path: str, label_file: str) -> array: """Loads position of an object from a file. Parameters ---------- dir_path : str Folder of the file. label_file : str File name. Returns ------- array Position of an object defined by a b...
cc655dc0172aff3cb8571c733e37c30e696c888c
47,122
import re def camel_2_snake_case(word): """ >>> camel_2_snake_case("HTTPResponseCodeXYZ") 'http_response_code_xyz' From https://stackoverflow.com/a/1176023/548792 """ return re.sub(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", r"_\1", word).lower()
dc20c832a212f89d51bb05302c9e1677e8f2cb83
47,123
def copy_to_device(target_device, source_device="/cpu:0"): """A transformation that copies dataset elements to the given `target_device`. Args: target_device: The name of a device to which elements will be copied. source_device: The original device on which `input_dataset` will be placed. Returns: A...
4b77ea7a13c6cbef5aa31daa3db88b79124cb786
47,124
def get_run_info(): """ get run base info """ return _global_dict["run_info"]
3c329e55c970310cbf19967eeee2f77a3eb2ae9e
47,125
def generate_configs(experiment_config): """Generate parameter configurations based on an input configuration. Input is a nested configuration where on each level there can be 'fixed', 'grid', and 'random' parameters. In essence, we take the cartesian product of all the `grid` parameters and take random s...
42b380ce9dad365efed0cba0d0bd38abde4ebd37
47,126
from datetime import datetime def now_str(time=False): """Return string to be used as time-stamp.""" now = datetime.now() return now.strftime(f"%Y-%m-%d{('_%H:%M:%S' if time else '')}")
02b73bda5f27e7c25120d50d50244bd103661c90
47,127
def set_ai_character(controller, character, gamestate, port, opponent_port): """Set the given controller to the STANDARD state playing as the given character. This is to be called repeatedly each frame while in the character selection menu. Returns true once it is complete.""" if ga...
1eaeb2baea4f6977541ae7db3ab696158e8be456
47,128
def camino_minimo(inicio, fin, rutas, ciudades, grafo): """Devuelve una lista con el camino mas corto y de menor coste entre inicio y fin (ambas ciudades de nuestro grafo) Pre: inicio, fin son las IDs de las ciudades; rutas es un diccionario con objetos Ruta (rutas[id_ciudad1][id_ciudad2]), y ciudades es un dic...
7076c291a9dec9c2de7c7765ceccfa5a3d7a4f5f
47,129
def get_custom_refinfo(*args): """ get_custom_refinfo(crid) -> custom_refinfo_handler_t const * Get definition of a registered custom refinfo type. @param crid (C++: int) """ return _ida_nalt.get_custom_refinfo(*args)
031cce0572fed275c29df37f7e928236896b37f9
47,130
import re def re_tester(regex, flags=0): """Creates a predicate testing passed string with regex.""" if not isinstance(regex, _re_type): regex = re.compile(regex, flags) return lambda s: bool(regex.search(s))
39a55bc0e9a30b8295a2550f086e4352af6631ab
47,131
def objective_function(n_splits, PopFrenetPath, curv_smoother, tors_smoother, hyperparam, smoothing, alignment, lam, parallel): """ Objective function that do the cross validation. ... """ print(hyperparam) # kf = KFold(n_splits=n_splits, shuffle=True, random_state=1) kf = KFold(n_splits=n_s...
018a0dd7c2994b9576ba39c310a7f3e36b29033b
47,132
def from_file(path: str) -> set: """ Read conditions from a file. Each line contains a separate condition. :param path: Path to file. :return: Read conditions. """ conditions = set() with open(path) as f: for line in f: conditions.add(line) return conditions
3780d540d6f300fe0a97d354ed33fa0aab803d56
47,133
def from_gca_point(gca_obj, name_header, folder_name, folder_description='', altitude_mode="ctg", style_to_use=None, pt_hidden=False, folder_collapsed=True): """ Save features from GCA object into a kml folder Parameters ---------- gca_obj : GCA name_header : str The ...
37f1748a8c17e3c380ed5599fabf2ce1f4045abc
47,134
def join_positions(pos1,pos2): """ Merge two positions and return as a list of strings pos1: iterable object containing the first positions data pos2: iterable object containing the second positions data Example: >>> join_positions('ABCD','1234') ['A1', 'B2', 'C...
cf5525a9d246501976bcb9ed74b12a13034c7525
47,135
def get_corrcal_gainsol(data,ant1,ant2,gain_int,noise,sky_cov_vecs,src_vecs,block_edges,gain_fac,maxiter=1000): """ This fuction solve for antenna gain per frequency. Method : Conjugate-gradient Method Software : python scipy.optimize --- fmin_cg Parameters ---------- data : array; sh...
84d47654c0ff0b832260cbf8f42a39ed3acc0703
47,136
def writePQR(filename, atoms): """Write *atoms* in PQR format to a file with name *filename*. Only current coordinate set is written. Returns *filename* upon success. If *filename* ends with :file:`.gz`, a compressed file will be written.""" if not isinstance(atoms, Atomic): raise TypeError(...
d1044594d5231b9fbc36e0091c0eb1aa31f9daf6
47,137
import os import re import syslog def retrieve_vlan_id(): """ Retrieves VLAN ids of in-band interfaces. This function fetchs vlan ids from OLT /broadcom/bal_config.ini file. :return : vlan id of in-band interface if successfull and None in case of failure. :rtype : integer(valid vlan_id) in case...
d84ff5215d8c670ff0d2c4e56855a8bd7d1fbe91
47,138
def read_intersections(fname1, fname2, band1=None, band2=None): """Read in the intersection of 2 files as an array""" bounds = get_intersection_bounds(fname1, fname2) print(f"bounds: {bounds}") im1 = copy_vrt(fname1, out_fname="", bbox=bounds) im2 = copy_vrt(fname2, out_fname="", bbox=bounds) re...
cb6bee733a078bf47acddf6922ec1334b758af58
47,139
def transformer(vocab_size, num_layers, units, d_model, num_heads, dropout, name="transformer"): """ transformer的粗粒度的结构实现,在忽略细节的情况下,看作是 encoder和decoder的实现,这里需要注意的是,因为是使用self_attention, 所以在输入的时候,这里需要进行mask,防止暴露句子中带预测的信息,影响 模型的效果 :param vocab_size:token大小 :param num_layers:编码解码...
3b68ed04cde51f1672414d124b2b74d0aeb0b06d
47,140
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu): """Reusable code for making a simple neural net layer. It does a matrix multiply, bias add, and then uses ReLU to nonlinearize. It also sets up name scoping so that the resultant graph is easy to read, and adds a number of s...
f42afcf25113dd92a0692a411edbc346960d0209
47,141
import os def get_device_names(): """ """ devices = [comport.device for comport in serial.tools.list_ports.comports()] devices = [comport.device for comport in serial.tools.list_ports.comports()] device_names = [] if os.name == 'posix': # macOS # Strip the device prefix ...
65161d328cf8242ee31c2b712894c80b40fcfe46
47,142
def divide(data: tuple, domain='freq'): """Divide pyfar audio objects, array likes, and scalars. Pyfar audio objects are: :py:func:`Signal`, :py:func:`TimeData`, and :py:func:`FrequencyData`. Parameters ---------- data : tuple of the form (data_1, data_2, ..., data_N) Data to be divide...
1c5c89cba61230b3fcddfc3512be39c04c84f8fd
47,143
import array def norm_D_sum(D_sum): """Normalize a D_sum by the elements for each feature by smallest absolute size (that element becomes 1 in norm). For unweighted feature sensitivities, or else it unweights weighted ones.""" D_n = {} for feat, pD in D_sum.items(): pD_min_abs = min(ab...
26eda448ec7db143bc89b5319bbbc18597a88349
47,144
import torch def collate_fn(data): """Creates mini-batch tensors from the list of tuples (image, caption). We should build custom collate_fn rather than using default collate_fn, because merging caption (including padding) is not supported in default. Args: data: list of tuple (image, captio...
c60edfb028d9405d76cabded30e5fb74fd1e821e
47,145
def getLeastReplaggedCommons(): """ Returns the name of the least replagged Commons replica among s1, s2 and s3 """ return "commonswiki-p.rrdb.toolserver.org" # broken: #return urllib.urlopen("http://toolserver.org/~eusebius/leastreplag").readline()
5726416f7a1cbb09f51de81d967009005a06af1b
47,146
import json def parse_line(header, line): """Parse one line of data from the message file. Each line is expected to contain chunk key - comma - tile key (CSV style). Args: header (dict): Data to join with contents of line to construct a full message. line (string): Contents of the line. ...
452dd80f84a35f6e3532330155bade7f424c102a
47,147
from datetime import datetime from sys import version async def handle(request): """ index req """ dt = datetime.datetime.now() dtstr = str(dt) myulid = ulid.new() strmyulid = myulid.str intmyulid = myulid.int bmyulid = bazed_ulid(intmyulid) text = tpl % ( version, dtstr,...
405459c6270335194a6157ad7f7d4606861a29a6
47,148
def filequote(text): """Transform text to file name.""" trans = str.maketrans(' /()', '____') return text.translate(trans)
dd6237fe6c66f60c00c8a569636adf17d45d66cc
47,149
def characteristic(text, ontology=None): """ Making a ENA Biosamples characteristic """ if ontology: return [{"text": text, "ontologyTerms": [ontology]}] else: return [{"text": text}]
e7f175a1ef8137b4c0e19a28a5d74055d9363c66
47,150
import logging def get_full_vol_name(vmdk_name, datastore, vm_datastore): """ Forms full volume name from vmdk file name an datastore as volume@datastore For volumes on vm_datastore, just returns volume name """ vol_name = vmdk_utils.strip_vmdk_extension(vmdk_name) logging.debug("get_full_vol_...
72587f94fbf8f15bbe538a7a6b53bd87a164f709
47,151
from . import eds from . import epf def import_od(source, node_id=None): """Parse an EDS, DCF, or EPF file. :param source: Path to object dictionary file or a file like object or an EPF XML tree. :return: An Object Dictionary instance. :rtype: canopen.ObjectDictionary """ if ...
5c6ef6056df075c4f0918473e6a3851032bdf27a
47,152
def _strip_trailing_ffs(binary_table): """ Strip all FFs down to the last 32 bytes (terminating entry) """ while binary_table.endswith("\xFF"*64): binary_table = binary_table[0:len(binary_table)-32] return binary_table
43c14297da709f78316e460180c6c4515650f34d
47,153
def params_schedule_fn_constant_09_01(outside_information): """ In this preliminary version, the outside information is ignored """ mdp_default_gen_params = { "inner_shape": (7, 5), "prop_empty": 0.9, "prop_feats": 0.1, "start_all_orders": [ {"ingredients": ["...
4fa999ee03a8d1fb3178ad6267c5d48a23026855
47,154
import pathlib import glob import os def getFileListing(files, recurse): """Creates recursive or non-recursive file listing. Args: file: path to evaluate recurse: True/False value which dictates whether the listing is recursive Returns: fileList: array containing the results of t...
8c722b372b7ef0fd904cdda7cc153295b8aa4707
47,155
def is_same_day(t1, t2, refresh_time=None): """check two times in same day""" return get_day_time(t1, refresh_time) == get_day_time(t2, refresh_time)
b8fa216f79f14b419add6b6e96c6923ba791c88e
47,156
from datetime import datetime def benchmark(synthesizers, datasets=DEFAULT_DATASETS, iterations=3, add_leaderboard=True, leaderboard_path=LEADERBOARD_PATH, replace_existing=True): """Compute the benchmark scores for the synthesizers and return a leaderboard. The ``synthesizers`` object can eith...
9168c94921c93765d68d15a32a826622c59bd6ff
47,157
import io import os def context_from_format(format_def: str, **kwargs) -> ( InvokeContext, io.BytesIO): """ Creates a context from request :param format_def: function format :type format_def: str :param kwargs: request-specific map of parameters :return: invoke context and data :rt...
db272011a0f0a62096c6304efb1249b0e167db37
47,158
def detec_data_space(): """判断是否有free分区磁盘""" diskLists = commands.getoutput(""" fdisk -l | grep -iw "^Disk" | grep "/dev/" | grep -vi "\/mapper\/" | awk -F ":" '{print $1}' | awk '{print $2}' | sort """) diskLists = diskLists.split('\n') return diskLists
fdcd3016d38c7036cef7a83d2b15c901af8ea9b7
47,159
def arctand(x): """Trigonometric inverse tangent using :func:`np.arctan <numpy.arctan>`, element-wise with an output in degree. Parameters ---------- x : array_like Input array. Returns ------- y : array_like The corresponding tangent values. This is a scalar if x is a scal...
3e10dd7bc3a65b3615e330041891a8aff2f81d5c
47,160
import struct def byte_to_float(b1, b2, b3, b4): """ A function to get a 32 bit float from 4 bytes read in order [b1, b2, b3, b4] :param b1: first byte :param b2: second byte :param b3: third byte :param b4: fourth byte :return: the byte array from b1, b2, b3, b4 unpacked as a float using ...
962480d1b9d2c50e3196b5480e9c62bf696a8f0d
47,161
def interpolate_and_average(xs, ys, interp_points=None): """ Average bunch of repetitions (xs, ys) into one curve. This is done by linearly interpolating y values to same basis (same xs). Maximum x of returned curve is smallest x of repetitions. If interp_points is None, use maximum number of p...
35e7a0deec29710df4bc868d1c50845e6fc533f9
47,162
from .PlanheatMappingPlugin import PlanheatMappingPlugin def classFactory(iface): # pylint: disable=invalid-name """Load PlanheatMappingPlugin class from file PlanheatMappingPlugin. :param iface: A QGIS interface instance. :type iface: QgsInterface """ # return PlanheatMappingPlugin(iface)
c048ea0cc82c4571dbe9459a237fe8733b666da7
47,163
def plot_marker_3d(x, y, z, max_size=0.75, min_size=0.05, marker_type='scatter', num_lines=8, ax=None, **kwargs): """Pseudo-3D scatter plot using marker size to indicate height. This plots markers at given ``(x, y)`` positions, with marker size determined by *z* values. This is an alternative to :func:`mat...
895aa1a78ba0229d33bf65deac35102bf5f75d81
47,164
def is_record(obj): """Check whether ``obj`` is a "record" -- that is, a (text, metadata) 2-tuple.""" if ( isinstance(obj, (tuple, list)) and len(obj) == 2 and isinstance(obj[0], compat.unicode_) and isinstance(obj[1], dict) ): return True else: return Fal...
e95b7e885afb3594b688c90d1d46fc4ce1e326c8
47,165
import re def get_used_by_from_comments(lines: "list[str]") -> "tuple[int, list[str]]": """Read the module-used-by block comment from a module file. Args: lines (list[str]): The content of the module file as a list of strings. Returns: tuple[int, list[str]]: The integer indicates the las...
6ac30266524373d0de7cf7bb9ad9fd8dcd1933a2
47,166
def text_to_layer(block, unit, return_sequences=False): """Build tensorflow layer, easily.""" layer = None if block == "CNN": layer = tf.keras.layers.Conv1D(unit, kernel_size=1, strides=1, padding='same', activation='relu') elif block == "LCNN": layer = tf.keras.layers.LocallyConnected1D...
6ad7fb22ce222c6011e05beb9b6120ba43bd2abf
47,167
from pathlib import Path def construct_target_path(participant_name, model_name, roi): """Construct path to save results to.""" project_root = Path(__file__).parents[1] return project_root / "results" / participant_name / f"model_{model_name}"\ / f"roi_{roi}"
072681647a3362563829c25d4890aa13425cff2c
47,168
import codecs def txidFromBroadcast (hexStr): """Extracts the hex txid from a broadcast in hex.""" # The prevout txid is the first part of the broadcast data # in serialised form. But we need to reverse the bytes. hexRev = hexStr[:64] bytesRev = codecs.decode (hexRev, "hex") return bytesRev[::-1].hex ...
96690f4fdef5f0cff857188045696e427914b887
47,169
def _tm_range_from_secs(start, dur, rate=25.0): """ Return a TimeRange for the given timestamp and duration (in seconds). """ return otio.opentime.TimeRange( _rat_tm_from_secs(start), _rat_tm_from_secs(dur))
9c68f34f5456252d4062c5bccfb82b3fc6f17537
47,170
def is_known_scalar(value): """ Return True if value is a type we expect in a dataframe """ def _is_datetime_or_timedelta(value): # Using pandas.Series helps catch python, numpy and pandas # versions of these types return pd.Series(value).dtype.kind in ('M', 'm') return not ...
231035c6c8282a4b2c632112e74fee6194660a78
47,171
def get_model_results(ldamodel, corpus, dictionary): """ Create doc-topic probabilities table and visualization for the LDA model """ vis = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary, sort_topics=False) transformed = ldamodel.get_document_topics(corpus) df = pd.DataFrame.from_records([{...
db622cdefa51337985c0b3dba9987d0be3b6f704
47,172
from django.conf import settings def i18n(request): """ Set client language preference, lasts for one month """ next = request.META.get('HTTP_REFERER', settings.SITE_ROOT) lang = request.GET.get('lang', settings.LANGUAGE_CODE) if lang not in [e[0] for e in settings.LANGUAGES]: # lang...
e9f2e1cc69a81e1766abfaae7efc4463e1103273
47,173
from typing import Optional def repr_errors(res, estimator=None, method: Optional[str] = None) -> str: """Pretty print original docstring and the obtained errors Parameters ---------- res : dict result of numpydoc.validate.validate estimator : {estimator, None} estimator object or...
fd24899717b209ee1419a7c46f006587a0b8323e
47,174
from hstore_flattenfields.db import fields def get_modelfield(typo): """ >>> get_modelfield('Input') <class 'hstore_flattenfields.db.fields.HstoreCharField'> >>> get_modelfield('Integer') <class 'hstore_flattenfields.db.fields.HstoreIntegerField'> >>> get_modelfield('Random') <class 'hstor...
a41e79d6f297f5da4d21e1e0645713afeff9415f
47,175
def thread_get_messages(service, thread): """Get the list of messages in a given thread. Args: service: gmail api service object. thread: thread from which to get the messages. Returns: list of messages objects (minimal format: only id and label). """ _Context.set('Thread {}: retrieving l...
da356d3e4b5dcfe9330002eb54b32b57b62e1990
47,176
from typing import Tuple def cc_cyclic(amp: Tuple[int, int] = (10, 15), freq: Tuple[int, int] = (10, 15)) -> DeltaGenerator: """ Creates a cyclic shape control chart sequence Parameters ---------- amp: Tuple. Defaults to (10,15) Chooses randomly a number between the tuple values as am...
d53062923ab9a7231dfc5fbec64df08104588618
47,177
import os def activate(): """ Return the path to the `activate` shell script within a virtual environment. """ path_to_venv = os.environ.get("PATH_TO_VENV", "venv") if os.name != "nt": # Posix return os.path.join(path_to_venv, "bin", "activate") else: # Windows ...
baf7846ae2ce9433fcf444457e5d251deed06ec3
47,178
def predict(X, y, parameters): """ This function is used to predict the results of a L-layer neural network. Arguments: X -- data set of examples you would like to label parameters -- parameters of the trained model Returns: p -- predictions for the given dataset X """ ...
e4d374577c2fe0499bc5233a843290e59512dad9
47,179
def build_log_src_prior(prior_type, xs, ys): """ Construct a log-probability distribution from a prior type specifier. Units are probability per area. """ shape = (len(xs), len(ys)) dx = np.mean(np.diff(xs)) dy = np.mean(np.diff(ys)) if prior_type == 'uniform': log_p_unnormaliz...
394b700779f1936d92189a2c9d39c0805043c079
47,180
def query_lat_long_with_fallback(address): """ Make a query for latlong from address with fallback mechanism. The method will first attempt to query latlong from Google geocoding service for it's higher precision. If the server cannot connect to the Google service or a timeout happens, the server tries to ...
5caa21c13fb3061c36aab7171eb88acbeee4d64e
47,181
def GEV_mean(mu, sigma, xi): """Calculate the mean of a GEV distribution. The arguments mu, sigma, and xi are the location, scale, and shape parameter of the GEV distribution, respectively. """ if xi >= 1: return np.inf elif xi == 0: return mu + sigma * np.euler_gamma else: ...
82b7e9137bb3365a1c661059b4de3356fb05f97b
47,182
import tqdm def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, aa_features, do_hydro, do_charge, do_pks, do_solubility, ...
3980b1aafb550ee0d4999e9f968fbbbff29c981e
47,183
import re def delete_dup_greater_than(text): """Processes html text deleting duplicated '>' generated after previous processing steps. Args: text (string): html text that is going to be processed. Returns: string: text once it's processed. """ p1 = re.compile(r'(<br>)(>)(</)', re.UNICODE) processed_text...
dd4383047c17addd9d32dd8d3e6d5f9d35911dd2
47,184
def svc_model_adjustment_optimization_score(X_train,X_test,y_train,y_test): """ 支持向量机 Support Vector Machine """ svc_params = {'C': [0.5, 0.7, 0.9, 1], 'kernel': ['rbf', 'poly', 'sigmoid', 'linear']} return model_adjustment_optimization(SVC(),'Support Vector Machine',svc_params,X_train,X_test,y_trai...
188a76d35452f765a158479768f9ba23ea221577
47,185
def msg_handle_KOR(string)->list: """Sort for data, double check with isit_covid""" isit_covid = False day = 0 #(0: default, 1: 오늘, 2:어제, 3:그저께) my_list = split_string(string) print(string) #0 기본 언어 : 코로나, 확진자, 몇, 명 if check_item(my_list, '코로나'): if check_item(my_list, '명') or check_...
f2e5bf3f579203d115e1e571d82a980e7912b1f1
47,186
import difflib import re from typing import Any import json def activity_diff(context: Context, data_dict: DataDict) -> dict[str, Any]: """Returns a diff of the activity, compared to the previous version of the object :param id: the id of the activity :type id: string :param object_type: 'package...
286bcd88b8adbd2ab2ec2d44e3e524f97aa8cd71
47,187
def property_graph(graph='g1'): """ Define the properties of the graph to generate :graph : type of desired graph. Options : ['g1','g2', 'g3', 'g4', 'g5'] """ if graph == 'g1': method = 'partition' sizes = [75, 75] probs = [[0.10, 0.005], [0.005, 0.10]] number_class =...
57aa301801213f4b88e9b2c77b3bf44c372b09ee
47,188
import re def readxtalkcoeff(xtalkfile): """read crosstalk coefficent file""" xdict = {} try: xfile = open(xtalkfile,'r') for line in xfile: if (len(line.strip()) > 0 and line[0] != '#'): line = line.rstrip('\r\n') line = line.rstrip() ...
759e9264b605256580bf4c3dd59859d50524f195
47,189
import copy import warnings from re import U def radec2altaz(radec, location, obstime=None, epoch_RA=2000.0, time_type=None): """ ---------------------------------------------------------------------------- Convert RA-Dec to Alt-Az with accurate ephemeris Inputs: radec [numpy array] Altitude ...
b4e1dff708e78adf90937d0c886cd7347f7b71ae
47,190
from jiant.utils import gcp from jiant.utils import emails import argparse import io import os import random import torch import tokenizers def initial_setup(args: config.Params, cl_args: argparse.Namespace) -> (config.Params, int): """Perform setup steps: 1. create project, exp, and run dirs if they don't a...
f7498290ba55f325a06f87bd158f7d3e8afb0c49
47,191
def filter_properties(person, PERSON_PROPERTIES): """ Extract specific properties of the given person into a new dictionary. Parameters: person (dict): the dictionary containing properties of a person. PERSON_PROPERTIES (tupl): a tuple containing the characteristics of a person Returns...
2a3ec4ab32c5d99d475ebffaefe0d8c40ce137af
47,192
import argparse def OriginFromArg(arg): """Constructs the origin for the token from a command line argument. Returns None if this is not possible (neither a valid hostname nor a valid origin URL was provided.) """ # Does it look like a hostname? hostname = HostnameFromArg(arg) if hostname: return "...
f2418f2b0800dce8c682a66e40840413b173086b
47,193
import importlib def import_module(module, app): """Handle the import of a module by mocking them with autodoc config. Query the value of ``autodoc_mock_imports`` inside the ``conf.py`` module. Arguments: module (str): The name of the module to import. app (Sphinx): The current sphinx ap...
d83633c09cf6c9f56e5a415b1d350587e7d79564
47,194
def landsat8_spectral_indices(img): """ Function that computes several spectral indices for Landsat 8 sensor. The indices specifically focus in detecting vegetation phenology, and water and salt content in the soil. The indices are added to the input image as bands. The function can be used either w...
2392382e6c6f1bbb222c2a7e42c77d1a654ea9b5
47,195
def rphiz_to_xyz(values): """Converts axis values from cylindrical coordinates into cartesian coordinates Parameters ---------- values: array Values of the axis to convert (Nx3) Returns ------- ndarray of the axis (Nx3) """ r = values[:, 0] phi = values[:, 1] if len...
1b9c7ff031bec97b588844da9a7498f2dd79a85c
47,196
import logging import pandas def get_opt_solution(model=None): """Returns the solution found for the optimization parameters as data frame The resulting data frame will have the columns: * `name`: the name of the parameter * `lower`: the parameters lower bound * `upper`: the parameters upper bou...
3466d6f208cfbe4d9de4854f949f163fcb44b930
47,197
import os def load_conv(save_path, name): """Load convolution layer parameters""" fname = os.path.join(save_path, '%s.msg' % name) with open(fname) as f: weight = mp.unpack(f) bias = mp.unpack(f) weight = np.asarray(weight).astype(np.float32) bias = np.asarray(bias).as...
95ca4dbec1cd4c6622842c48c66855b3f9e353b9
47,198
def invert(image): """Invert the given image. :param image: image :returns: inverted image """ assert np.amin(image) >= -1e-6 assert np.amax(image) <= 1+1e-6 return 1.0 - np.clip(image, 0, 1.0)
4b9237fb1e2c76eaab08a4b7632165ede5951a7f
47,199