content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging def process(utim, data): """ Run process :param Utim utim: Utim instance :param list data: Data to process [source, destination, status, body] :return list: [from, to, status, body] """ source = data[SubprocessorIndex.source.value] destination = data[SubprocessorIndex....
5774ecf399274fa19513d866cf8a29d6d698a70d
3,633,217
def get_event_list_current_file(df, fname): """ Get list of events for a given filename :param df: pd.DataFrame, the dataframe to search on :param fname: the filename to extract the value from the dataframe :return: list of events (dictionaries) for the given filename """ event_file = df[df[...
4fc56e23e57f021a5c84d5650d2c9586ed86b19e
3,633,218
def get_dealer_reviews_from_cf(url, **kwargs): """ Get Reviews""" results = [] json_result = get_request(url) if json_result: reviews = json_result["entries"] for review in reviews: dealer_review = DealerReview(id=review["id"], name=re...
08f16863e1f05d5fe45d7e6bec0cceded41994af
3,633,219
def fused_normalize(x: th.Tensor, mean: th.Tensor, std: th.Tensor, eps: float = 1e-8): """Normalize or standardize.""" return (x - mean) / (std + eps)
971e061da3d55642fc32729132a647cdf63d6d42
3,633,220
def get_attachment_file_upload_to(instance, filename): """ Returns a valid upload path for the file of an attachment. """ return instance.get_file_upload_to(filename)
e38c51a2ca947bebe1ed274c4265081c6b9e7c41
3,633,221
def temp_ann(S_SHSTA_0, S_SHSTA_1, S_SHSTA_2, S_SHSTA_3, I_SHSTA_0, I_SHSTA_1, I_SHSTA_2, I_SHSTA_3, C_KSWCK_0, C_KSWCK_1, C_KSWCK_2, C_KSWCK_3): """ Notes ----- Where t = 0, provide the current time step. Where t = 1, provide the 1-month prior time step value. Repeat this pattern for a...
cddc9ac237fcc446daff7f2f4ffd99783a9faab5
3,633,222
def slice(Matrix, a, b): """Slice a matrix properly- like Octave. Addresses the confounding inconsistency that `M[a,b]` acts differently if `a` and `b` are the same length or different lengths. Parameters ---------- Matrix : float array Arbitrary array a, b : int lists or arrays ...
a66dbdca7bbaf1ecf556e4cdd340d10dca28be02
3,633,223
import _functools def completing(rf, cf=identity): """Returns a wrapper around `rf` that calls `cf` when invoked with one argument. Args: rf: A :any:`reducing function`. cf: An optional function that accepts a single argument. Used as the completion arity for the returned :any:`re...
9efc81357d65871871a335d1e66fe687127568aa
3,633,224
def build_feet( filter1, # type: pymunk.ShapeFilter normal_rect, # type: pygame.Rect pymunk_objects, # type: List[Any] body_body, # type: pymunk.Body seat_body, # type: pymunk.Body ): # type: (...) -> Tuple[pymunk.Body, pygame.Sprite] """ Builds our unicycle cat...
f903b89feedab4bf80cf34b2b6c0fd6e296330d3
3,633,225
def zone_distances(zones): """ :param zones GeoDataFrame [*index, zone, geometry] Must be in a CRS of unit: metre """ for ax in zones.crs.axis_info: assert ax.unit_name == 'metre' print("Calculating distances between zones...") distances_meters = pairwise_distances( list...
74538d679e7efa3e4a2dfa031548e7e2062053cb
3,633,226
import re import base64 def decode_base64(data, altchars=b'+/'): """Decode base64, padding being optional. :param data: Base64 data as an ASCII byte string :returns: The decoded byte string. """ data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data.encode()) missing_paddi...
c99f4c832e8e990611ad8413d4b508a697504218
3,633,227
from operator import ge def _run_after(a, b): """Force operation a to run after b. Do not add control dependencies to ops that already run after. Returns 0 if no dependencies were added, 1 otherwise.""" already_after = (b in a.control_inputs) or (b in [i.op for i in a.inputs]) if already_after: return...
36489af41d4671a952dd62c4dd5d68618606a361
3,633,228
def handle_negations(tweet_tokens, lexicon_scores): """ Handling of negations occuring in tweets -> shifts meaning of words -> if a negation was found the polarity of the following words will change Parameters ---------- tweet_tokens : List list of tweet tokens that were already prepocessed (...
cca56e5fa1b611aa6adb2e74ab580fed49b923ee
3,633,229
def build_keras(hyperparams_fn, freeze_batchnorm, inplace_batchnorm_update, num_predictions_per_location_list, box_predictor_config, is_training, num_classes, add_background_class=True): """Builds a Keras-based box predictor based on the configuration. Builds Keras-based box predict...
9b5247042bb1a47715c0f64f19011c5634c4aff3
3,633,230
def log_level(non_prod_value: str, prod_value: str) -> str: """ Helper function for setting an appropriate log level in prod. """ return prod_value
86f098cfe9137519da1d160c22dfc1f43303c546
3,633,231
def add(x, y): """ Add two numbers and return their sum""" return x+y
5afb9194e696fe87f9f29f8893fd2f0e90673a1b
3,633,233
from typing import Any from typing import Optional from typing import Union def default_resolve_type_fn( value: Any, info: GraphQLResolveInfo, abstract_type: GraphQLAbstractType ) -> MaybeAwaitable[Optional[Union[GraphQLObjectType, str]]]: """Default type resolver function. If...
d1266fc358bbce50c226d7e40f95f6930261a121
3,633,234
def svn_repos_parse_fns2_invoke_close_node(*args): """svn_repos_parse_fns2_invoke_close_node(svn_repos_parse_fns2_t _obj, void * node_baton) -> svn_error_t""" return _repos.svn_repos_parse_fns2_invoke_close_node(*args)
996ebf6c153a659361d429ae6cbb977dc4202f3a
3,633,235
def sample_dball(dimension: int, amount: int, radius: float = 1) -> np.ndarray: """ **Sample from a d-ball by drop of coordinates.** Similar to the sphere, values are randomly assigned to each dimension dimension from a certain interval evenly distributed. Since the radius can be determined...
a1bbf552ea05dad5b1d11fa397ae8c2ce98c77a5
3,633,236
def distinguishable_paths(path1, path2): """ Checks if two model paths are distinguishable in a deterministic way, without looking forward or backtracking. The arguments are lists containing paths from the base group of the model to a couple of leaf elements. Returns `True` if there is a deterministic s...
140f8f18f030df233490ef242504649f175f62c7
3,633,237
def _correct_rotation(img: np.ndarray) -> np.ndarray: """if image is rotated correct for this and return it""" edges = cv2.Canny(img, 50, 150, apertureSize=3) lines = cv2.HoughLinesP( edges, 1, np.pi / 180, 100, minLineLength=100, maxLineGap=10 ) avg_slope = 0 cnt = 0 try: fo...
d2a3760ceb4a73260f8013a9aeafcfd21cfd6a07
3,633,238
def get_xyz_coords(illuminant, observer): """Get the XYZ coordinates of the given illuminant and observer [1]_. Parameters ---------- illuminant : {"A", "D50", "D55", "D65", "D75", "E"}, optional The name of the illuminant (the function is NOT case sensitive). observer : {"2", "10"}, optiona...
bca3f1e4a195fc2dcfc0dd9d440a84336573d34f
3,633,239
async def document_analyze(*, db:AsyncIOMotorClient = Depends(get_database), payload: NoteSchema): """[summary] View inserts item in the document string. [description] Endpoint to retrieve an specific item. """ analyze = await gensim.result(db, payload) return fix_item_id(analyze)
a7dc75306a40c2cc89016f7cf632e558e50fef7e
3,633,241
def create_example_concept_description() -> model.ConceptDescription: """ Creates an example :class:`~aas.model.concept.ConceptDescription` :return: example concept description """ concept_description = model.ConceptDescription( identification=model.Identifier(id_='https://acplt.org/Test_Co...
72c60aca03bd85fc66a5600675888a10542c1c96
3,633,243
def to_int(x): """ Try to convert a string to int :param x: str :return: int or np.nan """ try: return int(x) except: return np.nan
6d488258d49fc0cb396d48e1dd74c8bd9ed9fbea
3,633,244
def residuals(pars, data): """Returns data - model for given values of parameters Parameters ---------- pars : array-like [alpha, beta, gamma] parameters. data : Data object (string) Data to be compared with model. """ alpha, beta, gamma = pars mod = model(data.x, alp...
ee69bb681c003041de62ea9bb7774b51f9de5600
3,633,246
def plot_psth_photostim_effect(units, condition_name_kw=['both_alm'], axs=None): """ For the specified `units`, plot PSTH comparison between stim vs. no-stim with left/right trial instruction The stim location (or other appropriate search keywords) can be specified in `condition_name_kw` (default: bilateral...
d416207f19cf640faac1da6ab2e97c6a3fad251e
3,633,247
import configparser def load_versions(versions): """ parses 'jc221,jc221' etc. returns the supported versions and orders them from newest to oldest """ props = configparser.ConfigParser() props.read(LIB_DIR / "sdkversions.properties") known = list(props["SUPPORTED_VERSIONS"]) filt...
28bd0e7f080fb75707f716117c0c6b9ed6d05d77
3,633,248
import click def market_search_formatter(search_results): """ Formats the search results into a tabular paginated format Args: search_results (list): a list of results in dict format returned from the REST API Returs: str: formatted results in tabular format """ headers = ["id", ...
24942024599ddd5117a604cbd4e4890a8ccb5bf6
3,633,249
from typing import Optional from pathlib import Path def get_run_dir(run_number: Optional[int] = None) -> Path: """ Returns the directory corresponding to a given run number as a Path. If no run number is provided, return the current run directory. """ if run_number is None: run_number = o...
513c913effeadbf1267e63e1948e7ff9cb2fe753
3,633,250
def read_to_ulens_in_intvls(read, intvls): """Extract units within `intvls` from `read.units`.""" return [unit.length for unit in read.units if unit.length in intvls]
11159bea8bbf0cb68f0e9a7355c82e93b430065d
3,633,251
def org_identities_edit(self) -> bool: """ ### NOT IMPLEMENTED ### Edit an existing Organizational Identity. :param self: :return 501 Server Error: Not Implemented for url: mock://not_implemented_501.local: """ url = self._MOCK_501_URL resp = self._mock_session.get( url=...
bb08be8788812b396776c41f195ccce91c36a071
3,633,252
import secrets def makePrimes(bits): """ Generates the prime numbers p and q. Param bits: int -- the bit length of each prime Returns a tuple of prime numbers. """ p = None q = None for _ in range(500): p = secrets.randbits(bits) q = secrets.randbits(bits) ...
f14c31c1ef6bbf151a743b2468db7d545ea7feb3
3,633,253
from beakerx import TableDisplay import ipywidgets def _in_splice_compatible_env(): """ Determines if a user is using the Splice Machine managed notebooks or not :return: Boolean if the user is using the Splice Environment """ try: except ImportError: return False return get_ipyth...
8088e1526daa33c86a88acd08a14c77b3de5fc8d
3,633,254
import torch def make_split(dataset, holdout_fraction, seed=0, sort=False): """ Split a Torch TensorDataset into (1-holdout_fraction) / holdout_fraction. Args: dataset (TensorDataset): Tensor dataset that has 2 tensors -> data, targets holdout_fraction (float): Fraction of the dataset that is...
148f0569320329c1737d2d585d9502db2215e9a4
3,633,255
from typing import Callable def singleton(instance: str = 'name') -> Callable: """ Wrap injector decorator. :param instance: name of instance to inject :type instance: str :return: injector decorator :rtype: Callable """ def save_to_storage(factory_method): """ Decora...
d8e9b63d81f95c18663edf00d0fb462a44805c0e
3,633,256
def fillNaToNone(data): """Iterates through NA values and changes them to None Parameters: dataset (pd.Dataset): Both datasets Returns: data (pd.Dataset): Dataset with any NA values in the columns listed changed to None """ columns = ["PoolQC", "MiscFeature", "Alley", "Fence", "FireplaceQu...
2a6fc8008447abefd9f993b01606c1afc5aa5a8a
3,633,257
import re def is_ld_block_defn_line(mdfl): """ Parse GFM link definition lines of the form... [10]: https://www.google.com [11]: https://www.google.com "Title Info" [1a]: https://www.google.com "Title Info {}" [2b]: https://www.google.com "Title Info {biblio info}" Ret...
0ebd01c0c05634ee33a320fa4c280ad575ee9b25
3,633,258
def return_data_frame_deaths_vs_cases(dict_corona_virus: dict, data_frame_countries: pd.DataFrame) -> pd.DataFrame: """ This method will return a data_coronavirus frame with the fields we need to create our map with circles: In this map, the circles will represent the ratio between deaths and number of case...
c7b1cf4456f2495de1302eb75c0617cef1c965ae
3,633,259
def vn_islowercase(char): """Check is lowercase for a vn character :param char: a unicode character :return: """ if char in _DIGIT or char in _ADDITIONAL_CHARACTERS: return True return char in VN_LOWERCASE
2393de33155a940f260d91f7304f7f3c35ce3e4e
3,633,260
def shared_template(testconfig): """Shared template for hyperfoil test""" shared_template = testconfig.get('hyperfoil', {}).get('shared_template', {}) return shared_template.to_dict()
160daa08699ae973d5cbbfe28b75f08ff3eb2f52
3,633,261
def doubleSlit_interaction(psi, j0, j1, i0, i1, i2, i3): """ Function responsible of the interaction of the psi wave function with the double slit in the case of rigid walls. The indices j0, j1, i0, i1, i2, i3 define the extent of the double slit. slit. Input parameters: ...
99fe70f564a72ff84d2de09bc93b3c9dada3c4a0
3,633,262
import random def gnp_from_data(sizes, densities, directed = True):#, p_disconnect_node = None): """ Given a set of graph sizes (number of nodes) and densities, generate a new gnp (Bernoulli/Erdos-Renyi) random graph with size selected from the given graph sizes. Density is estimated based on a linear model o...
e63cea7d705eacb77b6fdc97654d049967a4de4a
3,633,263
def greedy_tsp(G, weight="weight", source=None): """Return a low cost cycle starting at `source` and its cost. This approximates a solution to the traveling salesman problem. It finds a cycle of all the nodes that a salesman can visit in order to visit many nodes while minimizing total distance. It...
e9dbb0c2bb4b1b41545fd5e47d03e022bdfd5ca9
3,633,264
def get_sector(sector_id): """ GET: Gets all Entities on the required sector. https://meinformoapi.herokuapp.com/entities/sectors/Ejecutivo """ sector_id = str(sector_id) output = tools.filter_dict(current_entities,"sector", [sector_id]) return Response(dumps(output), mimetype='application/j...
4df0d454e1f592173e8c43d26254a00e054fd721
3,633,265
def map_get_by_key_range(bin_name, key_range_start, key_range_end, return_type, inverted=False): """Creates a map_get_by_key_range operation to be used with operate or operate_ordered The operation returns items with keys between key_range_start(inclusive) and key_range_end(exclusi...
4a2ffac60203e88520a46fb28d4fc31715c16369
3,633,266
def output(input_text : str = ""): """ It will take input as a string and return the output of the given input mathematics problem """ cal_object = Calculator(input_text) return cal_object.result
3393216343c4c2aa7a4b5e8fd73494b65f2c652f
3,633,267
import torch from typing import Sequence def to_tensor(X, use_cuda): """Turn to torch Variable. Handles the cases: * Variable * PackedSequence * numpy array * torch Tensor * list or tuple of one of the former * dict of one of the former """ to_tensor_ = partial(to...
51eaec2cdd4b64ca2a1922f36221305992d78d2b
3,633,268
def get_regularization_losses(scope=None): """Gets the list of regularization losses. Args: scope: An optional scope name for filtering the losses to return. Returns: A list of regularization losses as Tensors. """ return ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES, scope)
442d47f32e1d4be11072d0731c58bac795cce1ff
3,633,269
def get_output_tracking_error_message(ulog: ULog) -> str: """ return the name of the message containing the output_tracking_error :param ulog: :return: str """ for elem in ulog.data_list: if elem.name == "ekf2_innovations": return "ekf2_innovations" if elem.name == "e...
55445033308ca476b31e06a4374ad098e74f0c92
3,633,270
def getBpms(): """ return a list of bpms object. this calls :func:`~aphla.lattice.Lattice.getGroupMembers` of current lattice and take a "union". """ return machine._lat.getGroupMembers('BPM', op='union')
44ad3256074be5f5d521892ed48379cc6539f9d3
3,633,271
def get_single_label(label_id): """Get an ID as a single element. Args: label_id: Single ID or sequence of IDs. Returns: The first elements if ``label_id`` is a sequence, or the ``label_id`` itself if not. """ if libmag.is_seq(label_id) and len(label_id) > 0: ...
b97b6dbaf5fbb56204acef637f358ec35a331db7
3,633,273
import unittest def not_implemented(cls): """Decorator for TestCase classes to indicate that the tests have not been written (yet).""" msg = "%s: tests have not been implemented" % cls.__name__ _NOT_IMPLEMENTED.append(msg) return unittest.skip(msg)(cls)
0454ffeb08e4367dbb70c90f40748a32c5cec05d
3,633,275
from pymatgen.io.cif import CifParser def get_structure_tuple(fileobject, fileformat, extra_data=None): """ Given a file-like object (using StringIO or open()), and a string identifying the file format, return a structure tuple as accepted by seekpath. :param fileobject: a file-like object contai...
ada7d694b0d9ec60f6b1e40dd21487650c637207
3,633,277
def find_merge_commit_in_prs(needle, prs): """Find the merge commit `needle` in the list of `prs` If found, returns the pr the merge commit comes from. If not found, return None """ for pr in prs[::-1]: if pr['merge_commit'] is not None: if pr['merge_commit']['hash'] == needle[1...
42320473aff84985e35cdf9024a64a18fe6f14f1
3,633,278
def date_breaks(width): """ Regularly spaced dates Parameters ---------- width: an interval specification. must be one of [minute, hour, day, week, month, year] Examples -------- >>> date_breaks(width = '1 year') >>> date_breaks(width = '6 weeks') >>> date_breaks('month...
a1808ccb7c09fcc3f2d0367f64cd3533eb63a33d
3,633,279
def create_valid_url(url: str) -> str: """ Generate a video direct play url. """ return url
a04a22ec64b346be83b020745aeb33f74ca90b74
3,633,280
import numpy def circular_weight(angle): """This function utilizes the precomputed circular bezier function with a fit to a 10th order curve created by the following code block: .. code-block:: python x = numpy.arange(.5, 180, 0.5) y = [] for i in x: y.append(bezier.f...
4341173c3e3584fcddbe04c60f7dd43fe859ac89
3,633,281
def parse_single_example(serialized, # pylint: disable=invalid-name names=None, sparse_keys=None, sparse_types=None, dense_keys=None, dense_types=None, dense_defaults=No...
aa2a7774a5b03e0b89b6a55c13a13ed45c1e700d
3,633,282
def delta_date_feature(dates): """ Given a 2d array containing dates (in any format recognized by pd.to_datetime), it returns the delta in days between each date and the most recent date in its column """ date_sanitized = pd.DataFrame(dates).apply(pd.to_datetime) return (date_sanitized ...
bfdde9fe12ffabb336d2f92b9bd3875782a9f8ff
3,633,283
import torch import timeit def benchmark_training(model, opts): """Benchmarks training phase. :param obj model: A model to benchmark :param dict opts: A dictionary of parameters. :rtype: tuple: :return: A tuple of (model_name, list of batch times) """ def _reduce_tensor(tensor): r...
45f9328949e3385c1001db3dc2097d7a814455a4
3,633,284
def inhib_kin_query(inhib_pubchem_cid): """ Query to pull targeted kinases using inhib CID :param inhib_pubchem_cid: string inhib CID :return: Flask_Table Kinase object """ session = create_sqlsession() q = session.query(Inhibitor).filter_by(inhib_pubchem_cid= inhib_pubchem_cid) inh = q....
cf06cd79e057e4bd7f6c8abc8db115a94cc51a0f
3,633,286
from typing import Set def abstract_methods_of(cls) -> Set[str]: """ Gets the abstract methods of a class. :param cls: The class to get the abstract methods from. :return: """ return getattr(cls, ABSTRACT_CLASS_ATTRIBUTE, set())
0cf9fa46433230e535bb01daaa27109ccb246aef
3,633,287
def parameterized_qubit_qnode(): """A parametrized qubit ciruit.""" def qfunc(a, b, c, angles): qml.RX(a, wires=0) qml.RX(b, wires=1) qml.PauliZ(1) qml.CNOT(wires=[0, 1]).inv() qml.CRY(b, wires=[3, 1]) qml.RX(angles[0], wires=0) qml.RX(4 * angles[1], wire...
e82a93b3f3c9c7d9a7c63c5f22c80e2248c1bdf4
3,633,289
def get_indicators_from_fred(start=start, end=end): """ Fetch quarterly data on 6 leading indicators from time period start:end """ # yield curve, unemployment, change in inventory, new private housing permits yc_unemp_inv_permit = ( web.DataReader(["T10Y2Y", "UNRATE", "CBIC1", ...
8ed26654d64ca8c5a08c74ecc48e326396ecb311
3,633,291
def permission_denied_exception_handler(exc, context): """If the object exist but the user does not have permission for it, change the status code and message.""" # Call REST framework's default exception handler first to get the standard error response. response = exception_handler(exc, context) if co...
c3abfb58419a9cd2e07d29b3340ba3042db93506
3,633,292
from typing import Optional import ray def get_current_placement_group() -> Optional[PlacementGroup]: """Get the current placement group which a task or actor is using. It returns None if there's no current placement group for the worker. For example, if you call this method in your driver, it returns No...
5a7fd8cad03adaad2479bdb33cf2182c050dedf4
3,633,293
def _GenerateManifest(args, service_account_key_data, image_pull_secret_data, upgrade, membership_ref, release_track=None): """Generate the manifest for connect agent from API. Args: args: arguments of the command. service_account_key_data: The contents of a Google IAM service account...
af3553a3cbdc7c8bd75cafe5c48cfa06a72ec347
3,633,294
import re def check_conjunctions(sentence: str) -> list or None: """ Returns the list of messages about a punctuation error with conjunctions if there is one. """ sentence = sentence.lower() conjunctions = {'а', 'але', 'однак', 'проте', 'зате', 'хоч', 'хоча'} errors = [] for word in co...
9bbf6e72e431cf652cdac659e8e0a4da7b7a9b3c
3,633,296
import numpy def decompose(poly: PolyLike) -> ndpoly: """ Decompose a polynomial to component form. In array missing values are padded with 0 to make decomposition compatible with ``chaospy.sum(output, 0)``. Args: poly: Polynomial to decompose. Returns: Decompose...
d2817904fb6a2f1977d92a99c75d640b5b869fca
3,633,297
def letter_to_vec(letter): """returns one-hot representation of given letter """ index = ALL_LETTERS.find(letter) return _one_hot(index, NUM_LETTERS)
490aa2f3c5a9ddf7bf950c309f30c7753ea6628d
3,633,298
def Hellinger2D(dist1, dist2, x_low=-np.inf, x_high=np.inf, y_low=None, y_high=None): """ Computes the Hellinger distance between two bivariate probability distributions, dist1 and dist2. inputs: dist1: a function that returns the probability of x, y dist2: a function...
0541e44529d9c04916ee8ab88f2eaf4295b77256
3,633,299
def outline_to_mask(line, x, y): """Create mask from outline contour Parameters ---------- line: array-like (N, 2) x, y: 1-D grid coordinates (input for meshgrid) Returns ------- mask : 2-D boolean array (True inside) Examples -------- >>> from shapely.geometry import Poin...
1c1ab70ed949b10a052aae1b17239a5d7a08da64
3,633,300
def check_ContentType(): """ HowTo make Pre-Processing for all requests. But: it also can be managed in View Class, just like django-rest-framework """ if request.method != 'GET': if (not request.content_type) or ('application/json' not in request.content_type): msg = jsonify( ...
7fc35fe40621a1cf0486d681b294ff636f293c06
3,633,301
import hashlib def _hash_feature(feature): """Calculate SHA256 hash of feature geometry as WKT""" geom = shape(feature["geometry"]) return hashlib.sha256(geom.to_wkt().encode("utf-8")).hexdigest()
bd1dc2ad46f0960a042066152b5622febe530411
3,633,302
import socket def ssdp_scan(address=None, service=None, timeout=None): """ Returns a list of responses to an SSDP request """ if address is None: address = DEFAULT_ADDR if service is None: service = DEFAULT_SERVICE if timeout is None: timeout = DEFAULT_TIMOUT mes...
43a0f557ed3f8b5b8a9c8085ce71a0e5a45a2f31
3,633,303
def random_walk_timeseries(length: int = 10, freq: str = 'D', mean: float = 0, std: float = 1, start_ts: pd.Timestamp = pd.Timestamp('2000-01-01')) -> 'TimeSeries': """ Creates a random walk TimeSeries by sampling a gaussian distribution with mean 'mean' and standard deviation 's...
754a52be186f6f05fd70c8019c61cf6c27059680
3,633,304
def provider_for(platform: str, source: str) -> ContentProvider: """ A factory method that returns the appropriate data provider. Throws an exception to let you know if the arguments are unsupported. :param platform: One of the PLATFORM_* constants above. :param source: One of the PLATFORM_SOURCE>* ...
8f77453c6ec02d9bae571f12cd2de2a3420976b5
3,633,305
def create_app(config_name: str = "development") -> Flask: """ Factory for the creation of a Flask app. :param config_name: the key for the config setting to use :type config_name: str :return: app: a Flask app instance """ app = Flask(__name__) app.config.from_object(config[config_name]...
ca38c3bb82e19db20aff7a26724f00e848d54b5b
3,633,306
def oneorzero(argument): """Conversion function for the various options that let you choose between 1 and 0.""" return directives.choice(argument, ('0', '1'))
4de687a99c56c5a7e2074d0ae58312690f115472
3,633,307
def encode(s, c): """ s is the scret code c is the clear text """ secret_code_list = list(s) clear_text_list = list(c) encoded_text_list= [] count = 0 for letter in clear_text_list: if letter == ' ': encoded_text_list.append(' ') continue enc...
3af6297fb79b77c542b19789ccf9bc0668f6afd5
3,633,308
import sqlite3 def test_ap_wpa2_eap_sql(dev, apdev, params): """WPA2-Enterprise connection using SQLite for user DB""" try: except ImportError: return "skip" dbfile = os.path.join(params['logdir'], "eap-user.db") try: os.remove(dbfile) except: pass con = sqlite3.con...
cf5139cfc264e18fdb8e60eb4bce75797506db48
3,633,309
import numpy def polyfit(data, time_axis, masked_array, outlier_threshold): """Fit polynomial to data.""" if not masked_array: if outlier_threshold: data, outlier_idx = timeseries.outlier_removal(data, outlier_threshold) coeffs = numpy.ma.polyfit(time_axis, data, 3)[::-1] ...
c58b04e31bea8a028ee464d4b70515c4e5b1e7e2
3,633,310
def update_board(position, board, player): """ Update the board with the user input position if position not taken returns board, True=position taken or False=position not taken and board updated args: position (int 1-9, user input) board (np.array 2d) player ("X" or "O") """ ...
eb53d24c4976499e6611c97757d0c33b4cb3254f
3,633,311
def find_deployed_version(package_name, environment, version=None, revision=None, apptypes=None, apptier=False): """Find a given deployed version for a given package in a given environment for all related app types; search for full tier or host only deployment specifically ...
57bcd217e0a63a610f78a5ce49365578d7540d3e
3,633,312
import itertools import math def stochastic_block_model(sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True): """Returns a stochastic block model graph. This model partitions the nodes in blocks of arbitrary sizes, and places edges between pairs of ...
4beb0e20381aa65927a8b60278f8de6cb06f64ca
3,633,313
def get_text_and_links(wikitext): """ Obtain text and links from a wikipedia text. """ parsed = wtp.parse(wikitext) basic_info = parsed.sections[0] saved_links = {} num_links = len(basic_info.wikilinks) for i in range(num_links): index = num_links - i - 1 link = basic_in...
a0b05f72c12529b655dda216e32e129b5fcaad8f
3,633,314
import signal def SobelOperator(image, n): """ 构建了 Sobel 平滑算子和差分算子后,通过这两个算子来完成图像矩阵与 Sobel 算子的 same 卷积, 函数 SobelOperator 实现该功能: 图像矩阵先与垂直方向上的平滑算子卷积得到的卷积结果, 再与水平方向上的差分算子卷积, 这样就得到了图像矩阵与sobel_x 核的卷积。 与该过程类似,图像矩阵先与水平方向上的平滑算子卷积得到的卷积结果, 再与垂直方向上的差分算子卷积, 这样就得到了图像矩阵与 sobe...
e39b807ecff2e78f289a918e6f85ef7fced84427
3,633,315
import typing import pickle def read_model(model_file: typing.IO) -> SVR: """Read the model from the given file.""" return pickle.loads(model_file.read())
32a49bd37da2b6fb33a64d0ff334b8e323030169
3,633,316
def create_nonfixations(stimuli, fixations, index, adjust_n = True, adjust_history=True): """Create nonfixations from fixations for given index stimuli of different sizes will be rescaled to match the target stimulus """ x_factors, y_factors = calculate_nonfixation_factors(stimuli, index) non...
5c4462dd4bb5a3565158a9b2b085b88651d8b5a5
3,633,317
def get_commit_log(url, revnum): """Return the log message for a specific integer revision number.""" out = launchsvn("log --incremental -r%d %s" % (revnum, url)) return recode_stdout_to_file("".join(out[1:]))
fb079051926292fdabf69da99008c6dd5dab47c9
3,633,318
import torch def cov(x, rowvar=False, bias=False, ddof=None, aweights=None): """ Estimates covariance matrix like numpy.cov https://github.com/pytorch/pytorch/issues/19037 """ # ensure at least 2D if x.dim() == 1: x = x.view(-1, 1) # treat each column as a data point, each row as ...
376e89804374979fc21b1412d9db5ed588555d40
3,633,319
def tle_fmt_int(num, digits=5): """ Return an integer right-aligned string with DIGITS of precision, all blank if num=0 Ignores sign. """ if num: num = abs(num) else: return " "*digits string_int = "{:>{DIGITS}d}".format(num,DIGITS=digits) return string_int
8db7938e7a88e68c4a22013b10debbc4f5a9ca72
3,633,320
def get_status(): """Return classifier status.""" return 'ok'
84aedac3659ac2321867b02d3f6e7acb523923a3
3,633,322
def get_config_info() -> dict: """Gets the config from core sqlfluff and sqlfluff plugins and merges them.""" plugin_manager = get_plugin_manager() configs_info = plugin_manager.hook.get_configs_info() return { k: v for config_info_dict in configs_info for k, v in config_info_dict.items() }
c51f5853a54080189c37b1dea49da126d402854d
3,633,323
def landing_page(request, page): """Return resource landing page context.""" edit_resource = check_resource_mode(request) return get_page_context(page, request.user, resource_edit=edit_resource, request=request)
1a78491694a004ed784c50e8205c7341cbe58452
3,633,324
import torch def _smooth_l1_loss(pred: Tensor, target: Tensor, beta: float = 1.) -> Tensor: """(F.smooth_l1_loss()) :param pred: shape(N, In) :param target: shape(N, In) :param beta: smooth线 :return: ()""" diff = torch.abs(target - pred) return torch.mean(torch.where(diff < beta, 0.5 * d...
33cbfbf66360f9dd9d473b82c0f2103af19df676
3,633,325
import scipy def solve_assignment(weights, exclude_zero=False): """Finds matching that maximizes sum of edge weights. Args: weights: 2D array of edge weights. exclude_zero: Exclude pairs with zero weight from result. Returns: Integer array of pairs with shape [num_matches, 2]. """ rs, cs = sci...
d73d2c8b5dc7d5c5cbd08f38a4cc21d0b1ebf62a
3,633,326
def stepwise_kpca(X, gamma, n_components): """ Implementation of a RBF kernel PCA. Arguments: X: A MxN dataset as NumPy array where the samples are stored as rows (M), and the attributes defined as columns (N). gamma: A free parameter (coefficient) for the RBF kernel. n_c...
3e0abd47e5527191e681f68ccb9ed71587a5adb2
3,633,329
import functools def make_val_and_grad_fn(value_fn): """Function decorator to compute both function value and gradient. For example: ``` @tff.math.make_val_and_grad_fn def quadratic(x): return tf.reduce_sum(scales * (x - minimum) ** 2, axis=-1) ``` Turns `quadratic` into a function that accepts a...
f08e889d62ce5d7e94e70bf96ae0ec8bca31f931
3,633,330