content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def dict_fetch_all_by_month(cursor): """ We need the data in this format data = [ Month: "jan", "type1": value , "type2": value, Month: "feb", "type1": value , "type2": value, ...... ] do the below code helps to build the dictionary on that method """ collectors = [] ...
e1056dd16310915d6acb3ae5570df85920681da3
3,602,797
import re def pypi_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): """Role for linking to PyPI packages.""" env = inliner.document.settings.env text = utils.unescape(text) has_explicit, title, target = split_explicit_title(text) m = re.match(r'(.*)\s+\((.*?)\)', target) if m...
fa75191fcd4e661c08e3269aeabbb091ec991e33
3,602,798
from typing import Dict def dict_from_text_file(fpath: str) -> Dict[str, float]: """Parse a two-column CSV file into a dictionary of string keys and float values. Will fail an assertion if the second column contains values which are not valid floats. Args: fpath (str): Path to file to parse. ...
5baf29832e0a44c8131a97168cde796757c05bfa
3,602,800
from re import T from re import A def twitter_outbox(): """ RESTful CRUD controller for the Twitter Outbox - all sent Tweets are visible here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args ...
7c26501e4665d255377c7011b093669abc62a984
3,602,801
def filter_by_organization(object_type, user=current_user): """ Filter object by user's organization :param object_type: Object type to filter :param user: User('s Organization) to use for the filter :return: List of object filter by the user's organisation """ db = Info.get_db() return ...
ae94ea6042ad9ee16dbbde36369490f9c6ad0ac1
3,602,802
def auth_wrapper(f): """Decorator ensures User is authorized to perform editing commands.""" def _wrapper(obj, id): """ Check that the password is the proper password for User of the given id, then continue to perform function. Else, return authentication error. Return not found...
e4320ad32a97ffe2658f13833596f55683e18560
3,602,803
import inspect def analyse_action(func): """Analyse a function.""" description = inspect.getdoc(func) or 'undocumented action' arguments = [] args, varargs, kwargs, defaults = inspect.getargspec(func) if varargs or kwargs: raise TypeError('variable length arguments for action not allowed.'...
2639bb58d27927eed38a9b7c5ba96f3f9c260836
3,602,804
from typing import Dict def _check_instance(entry: Dict): """ Function to check instances in the expand_grid function. This checks if entry is a dictionary, checks the instance of value in key:value pairs in entry, and makes changes to other types as deemed necessary. Additionally, type-spec...
a6ecd16d5488af5368042316b927299dbed97239
3,602,805
from typing import Union from typing import Optional def get_baseline( powers: list[mne.time_frequency.AverageTFR], picks: Union[str, list[str], slice], baseline: tuple[ Optional[Union[int, float]], Optional[Union[int, float]] ] = (None, None), ) -> list[np.ndarray]: """Get baseline array ...
3df65de8e7f6ef0e4ec7dcd088492b8b936da5e1
3,602,806
def define_bayesian_model(): """Define the architecture of the Bayesian network.""" kl_divergence_function = (lambda q, p, _: tfp.distributions.kl_divergence(q, p) / tf.cast(NUM_TRAIN_EXAMPLES, dtype=tf.float32)) model = tf.keras.models.Sequential([ tfp.layers.Convolution2DReparameterization( ...
d97a4fcf22218327068980b4b89643017afba870
3,602,807
import time def auto_canny(image, ): """ by zj 计算一个合适的canny阈值 thr1 第二个阈值一般是 thr1 的 2 到三倍 性能 0.05s 左右(C_ZZ_JG 和 套管双耳实测是0.05s左右, 图片大小一般是 250 × 250) 图片过大的会增加计算时间计算时间和图像的size(w × h)正相关 :param image: 构件图片 :return: canny_thr """ t1 = time.time() i = 1 canny_contour_num = [] ...
79d823163cab9e8805093f7a044226dfe3ae4636
3,602,808
import tqdm def progress(*args, **kwargs): """ Progress bar Uses ``tqdm.autonotebook`` to automatically use a native Jupyter widget when executing within a Jupyer Notebook. Parameters ---------- *args Passed to the tqdm **kwargs Passed to the tqdm Returns --...
16c8f758212dec704060e0e0845a0a20ebba91f0
3,602,809
def get_PSF_model(psf_models, n_psf, current_idx): """Get a single PSF model from the model(s) previously instantiated Parameters ---------- psf_model : list list of PSF model(s) n_psf : int number of PSF model(s) current_idx : int Returns ------- lenstronomy.PS...
3848ff065fecea79be7e13ed2ace692f855d3a4d
3,602,810
from typing import List import zmq def send_array(socket, A: np.ndarray, t: List[int], n_samples: int, std: List[float], flags=0, copy=True, track=False): """send a numpy array with metadata A can be: xu: (n, n_x + n_u): 2D array containing the nominal points about which ...
28647122f0fa21f0d065db83a65f5718065497fd
3,602,811
import traceback def lenovo_umount_virtual_media(ip, login_account, login_password, image, mounttype): """Unmount virtual media, supporting both 18D and 19A version of Lenovo XCC. :params ip: BMC IP address :type ip: string :params login_account: BMC user name :type login_account: string :para...
1731800986d35d1843f7d60f573728738ad0dd10
3,602,812
from . import context import functools def non_transactional(allow_existing=True): """A decorator that ensures a function is run outside a transaction. If there is an existing transaction (and allow_existing=True), the existing transaction is paused while the function is executed. Args: allo...
bebbe60c7b478aa74880f3a113a36558e444e450
3,602,813
def numeric_amount(param, data): """Validate that param in data is a representation of a positive decimal number""" try: numeric_amount = float(data[param]) except ValueError: return (None, error("Invalid {} specified: {}. Must be a decimal number, e.g. 123.45.".format(param, data[param]), 4...
b191cdf239495be174d3cf96c7b9a870cdf8e01f
3,602,814
from typing import Optional def generate_hdwallet(mnemonic: str = MNEMONIC, cryptocurrency=EthereumMainnet, passphrase: Optional[str] = None) -> BIP44HDWallet: """[summary] Args: cryptocurrency (hdwallet.cryptocurrencies, optional): crypto of the wallet. Defaults to EthereumMainnet. mnemonic (...
56a02125b425c67d39fee9be37691ca846c32747
3,602,815
import zipfile def _HasMultipleResDirs(zip_path): """Checks for magic comment set by prepare_resources.py Returns: True iff the zipfile has the magic comment that means it contains multiple res/ dirs inside instead of just contents of a single res/ dir (without a wrapping res/). """ with zipfile.ZipFile(...
0a8edb987eb927700510d96f796741ae2bcd251e
3,602,816
def get_population_count(data_path:str, roi): """ Check if we have population count for roi and add to timeseries df if we do. Args: data_path (str): Full path to data directory. roi (str): Region. Returns: population (int): Population count for ROI (if e...
7cc83773bf25e83258716312604faa453e00a2d2
3,602,817
def convert_to_schema(schema: List[Dict[str, str]) -> List[bigquery.SchemaField]: """Read the schema as a JSON and reformats as an array. Args: schema: list of dicts to convert to list of SchemaField Returns: List of bigquery.SchemaField objects holding the schema. """ input_fields...
7709fa109db7951743e82a3757a931592497d283
3,602,818
import posixpath def get_fuzzer_benchmark_covered_regions_filestore_path( fuzzer: str, benchmark: str, exp_filestore_path: str) -> str: """Returns the path to the covered regions json file in the |filestore| for |fuzzer| and |benchmark|.""" return posixpath.join(exp_filestore_path, 'coverage', 'da...
f999a81c53d961a2ed38a7941d7dd6912dae9621
3,602,819
def rescale(info, max_size): """ Rescale a heatmap given its info and a maximum size. Biggest side (width or height) will be rescaled to maximum size, and the smallest will be rescaled proportionally :param info: dict, heatmaps info :param max_size: int :return: dict, heatmaps info rescaled...
279ad2bce061439ef3ee588f1f393e0e8b81157a
3,602,820
import base64 def base64_encode(data): """Returns base 64 encoded value of data.""" try: data = base64.b64encode(data.encode()) except TypeError as e: LOG.error("Couldn't encode data to base64: %s", e) return data
7c22438c57a9901b50472079c610c1dadbe0acbb
3,602,821
import json def customer_add_order(request): """ params: access_token restaurant_id address order_details (json format), example: [{"meal_id": 1, "quantity": 2},{"meal_id": 2, "quantity": 3}] stripe_token return: ...
8302dbb91dd7a30b6fb1f26b2225a211483cf240
3,602,822
def resnext50_32x4d(pretrained=False, **kwargs): """Constructs a ResNeXt50-32x4d model. """ model_args = dict(block=Bottleneck, layers=[3, 4, 6, 3], cardinality=32, base_width=4, **kwargs) return _create_resnet('resnext50_32x4d', pretrained, **model_args)
92c7e7185d08fd423d08e3dbaeea6c4090c02622
3,602,823
def get_language_array(lang, textlist=None): """gets language array with encoding and texts for all possible models as an EmbeddingSet Args: lang (whatlies, tfhub or huggingface model): language model to encode texts textlist (list, optional): list of texts to encode. Defaults to None. Ret...
363a63caaf9fde9048fef5cf9b5d8869ca133df3
3,602,824
def make_feature(record): """ Get a complete GeoJSON feature object for a record. """ return dict( type="Feature", id=record.get("Key"), geometry=wkt.loads(record.get("WktGeometry")), properties=extract_properties(record), )
ba61f8f0c014fa0a96e201d29a2f3db49f6ffd96
3,602,825
def check_compliance(business: Business) -> list: """Check for non-compliant business data.""" result = [] legal_type = business.legal_type result.extend(check_office(business)) result.extend(check_parties(legal_type, business)) return result
e37bc36a2dc21100aefc2eb6ecf9b14e5e0f47a1
3,602,826
def histvalue(image, channel="red"): """ Create Histogram values of an image Inputs: image (np.array) : Image input channel(string) : red (or) blue (or) green (or) all channel on which histvalue to be calculated Output: hist (np.array) : (255, 1) array wi...
89d425c86963830de74c2cb6e634451c854c5ef5
3,602,827
def del_dref(*args): """ del_dref(frm, to) Delete a data cross-reference. @param to: linear address of referenced data (C++: ea_t) """ return _ida_xref.del_dref(*args)
7b5ec52243fce3b85a38b308e16d7ae772caf397
3,602,828
def breakdown(data): """Break down each row into context-utterance pairs. Each pair is labeled to indicate truth (1.0) vs distraction (0.0). Output is a native array with format : [context, utterance, label]""" output = [] for row in data: context = row[0] ground_truth_utterance = ro...
613cc8ca3d65d8eb22631114a88a934f67f37867
3,602,829
from datetime import datetime import pytz def mailgun_timestamp_to_datetime(timestamp): """ Parses a timestamp value from a Mailgun API response as a datetime Args: timestamp (float): A timestamp value from a Mailgun API response Returns: datetime.datetime: The parsed timestamp "...
bc48c0eb74c2cebe887098ef62389198cd020ad6
3,602,830
def string_escape(text: str) -> str: """Escape values special to javascript in strings. With this we should be able to use something like: elem.evaluateJavaScript("this.value='{}'".format(string_escape(...))) And all values should work. """ # This is a list of tuples because order matters, an...
f85d02527f3a9fdb9373f2359c2fce86b86a5a89
3,602,831
import doctest def testmod_flt(mod,verbose=False): """Doctest a module using float comparisons. """ finder = doctest.DocTestFinder() dtlist = finder.find(mod) checker = FltOutputChecker() runner = doctest.DocTestRunner(checker) for dt in dtlist: runner.run(dt) results = runner....
0ddaee0f4785cf045c4f3ad3ffd4ddf78c1e5bd4
3,602,832
import torch def cross_points_set_solve_3d(L, points, a, b, step=1, solver=1): # points_set: (N, 3), # (c, y, x) """ L[cj, yj-a, xj] L[cj, yj, xj-a] L[cj, yj, xj] L[cj, yj, xj + b] L[cj, yj+b, xj] """ cj, yj, xj = points[:, 0], ...
64c675a678debca8f85e8092d588c8216170bbe2
3,602,833
import scipy def ci(data, confidence=0.95): """ Calculates the confidence intervals for a given 1D dataset. Calculated by multiplying standard error of the mean and percent point function (inverse CDF) for a given confidence and sample size. Then +/- mean. Args: data (array-like): 1D arra...
0918ce249892ff4b4a47989c443a54915bea60d7
3,602,835
def check_permutation(str1, str2): """ 1.2 Check Permutation: Given two strings, write a method to decide if one is a permutation of the other. Complexity: O(n) time, O(n) space """ h = {} for c in str1: if c not in h: h[c] = 0 h[c] += 1 for c in str2: if ...
4da48752e963c05115b3255b03749e8579a9f8ff
3,602,836
def calculate_metrics_single_ticker_via_celery(tuple, tca_request, dummy_market): """Calls auxillary methods to get market/trade data for a single ticker. If necessary splits up the request into smaller date chunks to collect market and trade data in parallel (using Celery) Parameters ---------- tc...
31b86cd5e6cd9c0135ae3e41b352a5c7f6aaa251
3,602,837
from typing import Union import torch from typing import Optional from typing import Any import tqdm def extract_features( model: nn.Module, dataset: Union[data.Dataset, torch.Tensor], transform: Optional[Any] = None, device: Optional[torch.device] = None, verbose: bool = True, **kwargs ) -> t...
3c52769c22399543f4d36bead0b50f65133155ed
3,602,838
def sli_usage(dir): """ Calculate the Storyline-items (sli) statistics given the sitting-data calculated from the Robomind Academy. The sli statistics consist of storyline/person/count/cumtime vectors. Count is the number of time the person executed a program for the storyline and cumtime is the accumul...
b8e8a237055b6a6c52ae50af0f3f74cdde9aa8a0
3,602,840
def climb_stairs(n: int) -> int: """ Args: n: number of steps of staircase Returns: Distinct ways to climb a n step staircase Raises: AssertionError: n not positive integer """ fmt = "n needs to be positive integer, your input {}" assert isinstance(n, int) and n > 0, ...
71ac88a1f475e8fe2da8e525f7924e289dbf28e4
3,602,841
def accel_ES(q: np.ndarray): """ Compute the gravitational accelerations in the earth-sun system. q in row vector of 6 elements: sun (x, y, z), earth (x, y, z) """ # Number of celestial bodies num_bodies: int = 2 # Number of dimensions in arrays; 3 spatial dimensions times the number of bod...
4084e0502cd8fa64066f3c6926ffd961661f0e65
3,602,844
import time import json def get_json(url, params): """ Attempt to fetch JSON for the given URL and query parameters. Since ArcGIS occasionally returns empty HTTP 200 responses, we also retry on those empty responses. """ empty_retries = 5 sleep_time = 0.05 while True: # Throttle our requests to red...
75108c26e3949d0571a39df6ef4d2577c7f2eec6
3,602,845
def _process(proc_data): """ Final processing to conform to the schema. Parameters: proc_data: (Dictionary) raw structured data to process Returns: Dictionary. Structured to conform to the schema. """ int_list = ['hop', 'asn'] float_list = ['rtt'] if 'hops' in proc...
172ff750af67d777b15e5a0370c7e7c41cba6c5a
3,602,846
from typing import overload from typing import Union import types from typing import Optional from typing import Callable def _blanket_implementation( group: Blanket, ): """Generator of blanket types. Unless blanket requires something fancy, this function should be used in order to obtain new blanket...
c4c982677dbe944a9a7c09163a7aa9e37e3c0dd6
3,602,847
def calculateProbableRootOfGeneTree(speciesTree, geneTree, processID=lambda x : x): """ Goes through each root possible branch making it the root. Returns tree that requires the minimum number of duplications. """ #get all rooted trees #run dup calc on each tree #return tree with fewest num...
551dced0a943ca309c91b3572c700bccea0c8af0
3,602,849
def _linear_solution(wcs_dict): """Constructs a Linear1D model based on the WCS information obtained from the header. """ intercept = wcs_dict['crval'] - (wcs_dict['crpix'] - 1) * wcs_dict['cdelt'] model = models.Linear1D(slope=wcs_dict['cdelt'], intercept=intercept) return model
29d104eb4fc8d72d78d21810329411cf592aa939
3,602,850
from pathlib import Path from typing import Optional def load_dataset(corpus_path: Path) -> Optional[pd.DataFrame]: """Load dataset from given xlsx or csv files, as dataframe Parameters ---------- corpus_path : pathlib.Path dataset file's path Returns ------- loaded dataframe ...
c0d483d63caf56bbb6c8f10c6e9fe250a0181a99
3,602,851
def determine_targets(gts, anchors, bg_threshold=0.3, fg_threshold=0.4): """ inputs: gts: [n, 4] [x1, y1, x2, y2] anchors: [k, 4] [x1, y1, x2, y2] bg_threshold: float, 0.3~0.4 fg_threshold: float, 0.4~0.5 outputs: anchor_gts_index: [k, ] # ...
e40e6277cf5b9974ab5bb63a481babb9cc1da71b
3,602,852
import torch def clusterize(α, x, scale=None, labels=None): """ Performs a simple 'voxelgrid' clustering on the input measure, putting points into cubic bins of size 'scale' = σ_c. The weights are summed, and the centroid position is that of the bin's center of mass. Most importantly, the "fine" l...
75b8baaee6f443fed1ecaeb01718a05c11caeaa2
3,602,854
from typing import List import smtplib def send_email(msg: str, to_: List[str] or str or set, headers: str = None): """ 发送运维信息,该函数仅用于发送简单文本信息 :param msg: 正文内容 :param to_: 发送对象 1. str to_ == 'self',发送给“自己” 2. List[str] 传入邮箱列表,群发邮件(...
5d45326c2c8a9aa5b3efc995ba631b48507d4ca0
3,602,855
from datetime import datetime def cases_in_last(domain, days): """ Returns the number of open cases that have been modified in the last <days> days """ now = datetime.utcnow() then = json_format_datetime(now - timedelta(days=int(days))) now = json_format_datetime(now) q = {"query": { ...
89d49e9e9a70ed285d17a020df68e5046aa8d73f
3,602,856
import warnings def GridRaysampler( min_x: float, max_x: float, min_y: float, max_y: float, image_width: int, image_height: int, n_pts_per_ray: int, min_depth: float, max_depth: float, ) -> "MultinomialRaysampler": """ GridRaysampler has been DEPRECATED. Use MultinomialRays...
a19d09d0bc93e860b38785bae13efd913cd235f4
3,602,857
async def _connect_redis(self): """ Connect to a Redis URL stored in config. Parameters: self - Aiko instance which contains configuration variables """ pool = await aioredis.create_redis_pool(self.config["redis_url"]) return pool
5a72e70885ef6cbfda91a05b738c4cb9009e7cad
3,602,858
def _convert_creators(value): """Convert creators.""" if isinstance(value, dict): # compatibility with previous versions return [Person.from_jsonld(value)] if isinstance(value, list): return [Person.from_jsonld(v) for v in value]
96fe6fd55fa7933728097ed492391a7c23d163d0
3,602,859
def apply_autocorrelation(signal): """ Calculate autocorrelation of a signal. Parameters ---------- signal : ndarray Signal to be autocorrelated. Returns ------- autocorr : ndarray Autocorrelation lags : ndarray Corresponding lags for each autocorrelation va...
2699c2a1099c6bde022b11c6def5ecfba8fe4e9e
3,602,860
import codecs def raw_buffered_line_counter(path, encoding="utf-8", buffer_size=1024 * 1024): """ Fast way to count the number of lines in a file. :param Path path: Path to file. :param str encoding: Encoding used in file. :param int buffer_size: Size of buffer for loading. :return: int ""...
700135dc1a5b5bf4a807469e34f56213d7b1265a
3,602,861
def drawcoorpoints(vis,points,col_out=black,col_in=red,radius=2): """ Funtion to draw points. :param vis: image array. :param points: list of points. :param col_out: outer color of point. :param col_in: inner color of point. :param radius: radius of drawn points. :return: """ po...
7be3d7e0c9dd429115bc3fdc1adad080a9ef202e
3,602,862
def neighborhood_quality(x): """ Strip field 'WOHNLAGE' to be an interval representing only the neighborhood quality If it's a rural area, fill the value with NaN Re-order values from poor to good Original values of 'WOHNLAGE': 0: no score calculated (should be converted to NaN already...
3dcae226a5035357939eb5fc25df8d3db2ebea43
3,602,863
def check_aggregate( df, variable, components=None, exclude_on_fail=False, multiplier=1, **kwargs ): """Check whether the timeseries values match the aggregation of sub-categories Parameters ---------- df : IamDataFrame args : passed to :meth:`IamDataFrame.check_aggregate` kwargs : used...
969dbd8e221c89e172fcdde0d6a91469bfead1d8
3,602,864
def consider_trip_number(trip_strategy, total_trips, trip_num): """Determines if the vehicle should charge given trip strategy and current trip :param int trip_strategy: a toggle that determines if should charge on any trip or only after last trip (1-anytrip number, 2-last trip) :param int total_trips:...
b2fe3a43b95fead4ebf65981cfba39857d1bee3c
3,602,866
import pathlib def as_pathlib(path): """ Converts the supplied path to an pathlib.Path object :param path: The path to convert :return: The path converted to pathlib.Path """ return pathlib.Path(path)
88129771be8c3277320c813502efbcfee6abdc84
3,602,867
def load_test_data(transformed_corpus, ques_len, ans_len): """ load train data """ pointwise_corpus = [] for sample in transformed_corpus: q, a = sample q_pad, q_len = padding(q, ques_len) a_pad, a_len = padding(a, ans_len) pointwise_corpus.append((q_pad, a_pa...
d8dbb1079602abd3865b7cb48da0f10b0fedfeec
3,602,869
import re def remove_non_alpha_numeric(input_string): """ return string by removing non alpha numric characters from it """ return re.sub(r'\W+', '', input_string)
fc7b203e4937a7a5a80f0d3dc9a2d7bca5de6b45
3,602,870
import torch def cov(x, rowvar=False, bias=False, ddof=None, aweights=None): """Estimates covariance matrix like numpy.cov""" # ensure at least 2D if x.dim() == 1: x = x.view(-1, 1) # treat each column as a data point, each row as a variable if rowvar and x.shape[0] != 1: x = x.t(...
97650dd602fc51bd0b61cf4a401a53870d4d41c6
3,602,871
def setup(lifecycle_hooks): """Setup fixture which adds FakeOIDC lifecycle hook""" class FakeOIDC: """Fake oidc class which updates services to oidc config with example.com:81 url""" # pylint: disable=unused-argument @staticmethod def before_proxy(service: Service, proxy_params: ...
a2266001e99ee34a2978a791cde24a7dbae94a4d
3,602,872
def run_gmm_test(sc, sqlCtx, table_name, fields, model, where_clause=''): """ Test a pretrained model on a table of test data Args: sc (pyspark.SparkContext): Spark Context to use for execution sqlCtx (pyspark.sql.SQLContext): Spark SQL Context to use for sql queries table_name (str...
245d73bedada563030e460297a2305e5c7a6c433
3,602,873
def runQuery(HTSQLquery,fetch=None): """Query MRIC database, return query result""" if not fetch: fetch=_login() return fetch(HTSQLquery)
6cdb0f3eee2d853cc72044053078b747ce9dc941
3,602,874
from pathlib import Path def index_gff3(path: Path): # gff3/{species} """Create bgzipped and indexed genome.gff3.""" genome = htslib.create_genome_bgzip(path) print(genome) print(htslib.tabix(genome)) return genome
7c4d97cc6123dd8f9d08618e8495659d386d949e
3,602,875
def _gaussian(x, x0, dx, A, N=False): """Simple Gaussian function with oversampling.""" if not N: return A * np.exp(-np.power((x - x0) / dx, 2)) xx = np.linspace(x[0], x[-1], x.size * int(N)) yy = A * np.exp(-np.power((xx - x0) / dx, 2)) return np.array([np.average(yy[i*N:(i+1)*N]) for i in ...
878246d642269640bc35c7ac8cd1206aca94f450
3,602,876
def fit_sigmoid_diffusion( l_value, x_data, y_data, start_parameters, number_of_iterations=10000 ): """Fit sigmoid curve based on two points on the diffusion curve Arguments ---------- l_value : float The sigmoids curve maximum value (max consumption)...
409b9b1926d29300b4ca76d12cd52fbc50e7ad1c
3,602,877
import string, urllib def url2pathname(url): """OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.""" # e.g. # ///C|/foo/bar/spam.foo # and # ///C:/foo/bar/spam.foo # become # C:\foo\bar\spam.foo # Windows i...
7a1359fc0422127a1ca27b39a68c933d3642603f
3,602,878
async def coordinator(hass, zigpy_device_mock, zha_device_joined): """Test zha light platform.""" zigpy_device = zigpy_device_mock( { 1: { "in_clusters": [], "out_clusters": [], "device_type": zha.DeviceType.COLOR_DIMMABLE_LIGHT, }...
e53cf36b59d069ef9d870c37b19d7ecd3c286deb
3,602,879
import random def median(values): """Return the middle value, when the values are sorted. If there are an odd number of elements, try to average the middle two. If they can't be averaged (e.g. they are strings), choose one at random. >>> median([10, 100, 11]) 11 >>> median([1, 2, 3, 4]) 2....
cedbf00a96f99914c9b3ceafda0275f968d4327e
3,602,880
def storage_backend(storage_dir) -> LocalStorage: """Provide a local storage backend for all local tests""" return LocalStorage(path=storage_dir)
2fb83dcadc1aac09b4776a112e0a3022e1d573a0
3,602,881
def nmc_LGM50_diffusivity_Chen2020(sto, T): """ NMC diffusivity as a function of stoichiometry, in this case the diffusivity is taken to be a constant. The value is taken from [1]. References ---------- .. [1] Chang-Hui Chen, Ferran Brosa Planella, Kieran O’Regan, Dominika Gastol, W. Dh...
5b7cbd03376ad34cf0522283ac945c7eaeaaac87
3,602,882
def gen_borders(border=40,H=800,W=800): """ Generate linear random borders (50% straight, 50% with random points on the border frame) """ border = (float)(border) if np.random.uniform()<0.5: border_points = (gen_p(border,W-border),H-gen_p(border,H-border),W-gen_p(border,W-border),gen_p(borde...
3c5e7eefb5fa0854afe06bd95f91ba66a20f6a82
3,602,883
def set_par(self, dummy=None, setpar=None, npar=None, verbose=False, roundto=5, **args): """Set the current parameter values. In essence, this is a wrapper around `get_par` which also compiles the transition function with the desired parameters. Parameters ---------- dummy : str or array, optional...
f88f3a88fcbe6fdf7d2b63bb8f0e2e4e47be6b0d
3,602,884
def mask_box_ellip(image, ellip): """Creates boolean mask of the ellipse and finds minimal-area rectangle. Parameters ------------ image : 2D array region of interest as grayscale image ellip : tuple Ellipse defined by its centroid, axes lengths and angle. Returns -...
ddd4966c6c5f067b69bb14e6add82737d555f156
3,602,885
def is_raster_intersecting(src0: DatasetReader, src1: DatasetReader) -> bool: """Test two rasters for overlap Parameters: src0: rasterio read source src1: rasterio read source Returns: True if the raster sources intersect """ bbox0 = window_bounds(((0, 0), src0.shape), src...
2ccad9ff8876bc7d03f47cd6f53cf134581e2095
3,602,886
from typing import List from typing import Tuple def find_all_comment_segments(src: str) -> List[Tuple[int, int]]: """ Find all comment segments in a database starting from a position return a list of pairs [ (comment start pos, comment end pos) ] where start pos is inclusive and end pos is exclusive ...
eec33aae79caa029186d3b320f90682b5a9bebd6
3,602,891
def get_key(file_path): """ 获取一个文件的key,七牛的算法是获取文件的hash值,使用的是 qiniu.etag() :param file_path: :return: key (str) """ key = etag(file_path) return key
17391d45bb47b8c7f948243e08bba08fc6c265e7
3,602,892
import copy def get_choices(cli, prog_name, args, incomplete): """ :param cli: command definition :param prog_name: the program that is running :param args: full list of args :param incomplete: the incomplete text to autocomplete :return: all the possible completions for the incomplete """...
ce40e8dba98416f59c8d3de12ca40c995ea4c151
3,602,895
def R_value_U(X, y, k=None, theta=None): """Compute the R-value. Return high values for overlapping classes, low values for well separated classes""" if k == None: k = int(0.1 * len(X)) R_U_ = 0. for d_lbl in unique_elements(y): msk_ = np.asarray([lbl == d_lbl for lbl in y]) th...
7b897298a023bc0442d7d173e22fbbe24d8b1d2e
3,602,896
def toGeneMatrix(segments, gene_mapping, style='weighted', missingchrom=['Y'], gene_names_col='gene_name'): """ makes a geneXsample matrix from segment level copy number (works with multiple sample file) Args: ---- style: str one of "weighted","mean","closest" segments: dataframe of segments containing...
91518ad547a3e72e3d03a6160216890901b43445
3,602,897
def mean_squared_error(y_true, y_pred): """ loss function computing MSE of non-blank(!=0) in y_true Args: y_true(tftensor): true label y_pred(tftensor): predicted label return: MSE reconstruction error for loss computing """ loss = K.switch(K.equal(y_true, tf.constant(0.)),tf.zeros(K.shape(y_true)),K.sq...
7f03ff02f433c9ff935b526c5ce55f0b209e4691
3,602,898
def all_tasks_to_do(client=default): """ Returns: list: Tasks assigned to current user which are not complete. """ return raw.fetch_all("user/tasks", client=client)
92a5faf6e323d2ff85c6a8cb468c517050c91976
3,602,899
import itertools def filter(iterator, field, value): """ Takes an iterator and returns only the docs that have a field == value. The field can be a nested field like a.b.c and it will descend into the embedded documents. """ return itertools.ifilter(lambda x: _deep_get(x, field) == value, it...
c9f7a1a60c2add295e547144b63146c8d957d2b4
3,602,900
def progress(iter, **kwargs): """ 프로그래스 bar for i in progress(10): print i for i in progress(iter): print i """ if isinstance(iter, int): iter = xrange(iter) if hasattr(iter, '__len__') or 'target' in kwargs: cls = Progress else: cls = ProgressBas...
296f9f2574b939d57e583742f7833817eebefdd7
3,602,901
import sklearn def auc_roc(yhat, ytrue): """ Class wise AUC ROC. :param yhat: :param ytrue: :return: """ auc_roc = np.array([ sklearn.metrics.roc_auc_score(y_true=ytrue[:, i], y_score=yhat[:, i]) for i in range(ytrue.shape[0]) ]) return auc_roc
44a30350aa9aa0eff5cc6d947932dedd901da3e1
3,602,902
def keV_to_kelvin(temperature): """Convert from temperature expressed in keV to a temperature expressed in Kelvin""" return temperature * (con.e / con.k * 1000.0)
b7888babed588be952308a3c2821d57eba43f778
3,602,903
def extract_text(tweet): """Gets the full text from a tweet if it's short or long (extended).""" def get_available_text(t): if t['truncated'] and 'extended_tweet' in t: # if a tweet is retreived in 'compatible' mode, it may be # truncated _without_ the associated extended_tweet ...
41660b71e3b020bc25309821b46471e88d79aa49
3,602,904
def search_linearf(a, x): """ Returns the index of x in a if present, None elsewhere. """ for i in range(len(a)): if a[i] == x: return i return None
949cb93218381a1a45002be03c6b8ca4d00092bf
3,602,905
def update_posterior(n: np.ndarray, alpha: np.ndarray) -> np.ndarray: """ Updates posterior distribution. Parameters ---------- n : np.ndarray Amount to update posterior distribution parameter by. alpha : np.ndarray Posterior distribution parameter. Returns ------- ...
fa9f69c0dddb8c819982485d411cf76b88b7f53e
3,602,906
def from_xml(xml): """Deserialize XML to a dictionary.""" if xml is None: return None deserializer = XmlDeserializer() return deserializer(xml)
61ee1ce93e427ca405542d5b46853466b9db3a00
3,602,907
import networkx import itertools def primes2stg(Primes, Update, InitialStates=lambda x: True): """ Creates the state transition graph (STG) of a network defined by *Primes* and *Update*. The *InitialStates* are either a list of states (in *dict* or *str* representation), a function that flags states t...
caba25a6b11fa6e5a80c217de7d8592d9697fb32
3,602,908
def autoprops_override_decorate(func, # type: Callable attribute=None, # type: str is_getter=True # type: bool ): # type: (...) -> Callable """ Used to decorate a function as an overridden getter or...
80ac64ead677d0b84d1a86f6cff38839d564d3bb
3,602,909
import logging def fetch_from_landing_page(landing_url): """Returns a tuple of (pdf_link, summary_text).""" add_pdf = False skip = False page = utils.beautifulsoup_from_url(landing_url) report_tables = page.select('table[summary~="reports"]') # in the rare case that doesn't work, have faith if len(rep...
9e02f0525921596909af00fdf5b08e08c7b22eb4
3,602,910
import requests def get_user_contribs(username): """ Fetch user contributions via MediaWiki API's Usercontribs module """ params = { "action": "query", "format": "json", "list": "usercontribs", "ucprop": "user|ids|title|sizediff", "ucuser": username, "uclimit": ...
d59810b6ac87e0dba28c9b21be9a21de6f878e80
3,602,911