content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def add_anomaly_data(egg_data: pd.DataFrame) -> pd.DataFrame: """ Given a dataframe of egg data, add a column for each anomaly metric, and populate it with the results of running the breakpoint analysis on each row Args: egg_data (pd.DataFrame): the dataframe containing the egg temperature data ...
74a65f25275e816eb4cf59c3a6aa11daa30ea41e
3,625,342
import struct def set_wm_strut_partial(window, left, right, top, bottom, left_start_y, left_end_y, right_start_y, right_end_y, top_start_x, top_end_x, bottom_start_x, bottom_end_x): """ Sets the partial struts for a window. :param window: A windo...
b6da1a199d1ca3194efee425c6f704d03093c28e
3,625,343
def get_connection(database_name: str): """Hakee yhteyden tietokantaan ja palauttaa sen. """ return connection
9970b6e9804806c3fb7e97b40f66ef8e20a280c6
3,625,344
def generate_graph_seq2seq_io_data( df, x_offsets, y_offsets, add_time_in_day=True, add_day_in_week=False, scaler=None ): """ Generate samples from :param df: :param x_offsets: :param y_offsets: :param add_time_in_day: :param add_day_in_week: :param scaler: :return: # x: ...
0140bdbe039748b1b1690e30b179154c7adaf6f4
3,625,345
def execute(cmd, stderr_to_stdout=False, stdin=None, cwd=None): """Execute a command in the shell and return a tuple (rc, stdout, stderr)""" if stderr_to_stdout: stderr = STDOUT else: stderr = PIPE p = Popen(cmd, shell=False, bufsize=0, close_fds=True, stdin=stdin, stdout=PIPE, stderr=s...
db50c409e0fd24003c304d1f1d27e8341913fd84
3,625,346
import random def get_random_number_with_zero(min_num: int, max_num: int) -> str: """ Get a random number in range min_num - max_num of len max_num (padded with 0). @param min_num: the lowest number of the range in which the number should be generated @param max_num: the highest number of the range i...
bdc9f192286262566d2b2a87e8124abdf745ecbd
3,625,347
from typing import List import torch def cluster_props(all_props: List[CollisionProp]) -> dict: """ Many provided properties are overlapping -- some subsumes some others, cluster them for later usage. :return: a dict of central points -> sorted props in decreasing order of their epsilons """ d = defau...
44fefaeb620caf7eb6f66ec0e35052df8396fea6
3,625,348
from comtypes.automation import VARIANT def COMMETHOD(idlflags, restype, methodname, *argspec): """Specifies a COM method slot with idlflags. XXX should explain the sematics of the arguments. """ paramflags = [] argtypes = [] # collect all helpstring instances # We should suppress docstr...
0686af6b9adf193320a3bff57b5a1bb8c7b29c15
3,625,349
def _validate_rpc_ip(rpc_server_ip): """Validates given ip for use as rpc host bind address. """ if not is_valid_ipv4(rpc_server_ip): raise NetworkControllerError(desc='Invalid rpc ip address.') return rpc_server_ip
24defd4633d13b1bed2d53ec9663e6abcc05b904
3,625,350
def normalize_data(df): """Normalizes a dataframe.""" scaler=MinMaxScaler() df[FEATURE_NAMES] = scaler.fit_transform(df[FEATURE_NAMES]) return df
1a718dc75d451269e0b5c83e5d10a0a1631b9728
3,625,351
def hex_to_root(hex_string: str) -> Root: """ Convert hex string to trie root. Parameters ---------- hex_string : The hexadecimal string to be converted to trie root. Returns ------- root : `Root` Trie root obtained from the given hexadecimal string. """ return ...
d5685289a3474cc6af6c8436822c4b6cefa0b835
3,625,352
def redis_connection(): """ Returns a redis connection from one of our pools. """ pool = ConnectionPoolManager.connection_pool(**CONNECTION_KWARGS) return Redis(connection_pool=pool)
08a1484b1406f5d5935a6caa057d0f537b645f02
3,625,353
def count_simple(a, alphabet_len): """Counts items in a. """ result = zeros(alphabet_len, Int) for i in ravel(a): result[i] += 1 return result
e6c0629175bd90d8942e05f8177e3ffbf1944699
3,625,354
def _select_manager(backend_name): """Select the proper LockManager based on the current backend used by Celery. :raise NotImplementedError: If Celery is using an unsupported backend. :param str backend_name: Class name of the current Celery backend. Usually value of current_app.extensions['celery...
d12de5e954a4d0b0d64c39f515a5736fb341ad8d
3,625,357
import warnings def ivim_model_selector(gtab, fit_method='LM', **kwargs): """ Selector function to switch between the 2-stage Levenberg-Marquardt based NLLS fitting method (also containing the linear fit): `LM` and the Variable Projections based fitting method: `VarPro`. Parameters ----------...
58aaf65baed294b344a3eae0e42f8f049ca34d6a
3,625,358
def temperature(): """ Raspberry Pi temperature """ return render_template("temperature.html")
6ccdf487f1760e812c83d75140e0b8653813f71d
3,625,359
import math def convert_size_bytes_to_human_readable_format(size_bytes): """ Converts a size in bytes to a human readable format. :param size_bytes: The size in bytes :return: Bytes converted to readable format """ if size_bytes == 0: return "0B" size_name = ("B", "KiB", "MiB", "G...
b14d345e5990e431997adeba09b5cee701f83fd0
3,625,360
def activate(client, name, file_=None): """Activate a model view. Args: client (obj): creopyson Client. name (str): View name. `file_` (str, optional): Model name. Defaults is current active model. Returns: None """ data = {"name...
cd928a364261e9f73cecbafc010f8eff2c5a39ab
3,625,361
def delete_table(userId, id): """ Deletes a table from the db. Only can be called via the saved_search.html """ try: savedSearch = SavedSearch.objects(id=id).first() tableName = savedSearch.name doDelete = True message = tableName+" deleted successfully!" if saved...
bb13d1c40157e2457adb31c94a58bbe421771e48
3,625,362
def _get_heatmap(job_name, build_number, builds, group_field, count_skips, project=None): """Run the aggregation to get the Jenkins heatmap report""" # Get the run IDs for the last 5 Jenkins builds build_min = build_number - (builds - 1) build_max = build_number + 1 build_range = [str(bnum) for bnum...
7652ca6cb5e573a88c2eb8ca2949d71ebf8004e0
3,625,363
def control_4_5_ensure_route_tables_are_least_access(regions): """Summary Returns: TYPE: Description """ result = True failReason = "" offenders = [] offenders_links = [] control = "4.5" description = "Ensure routing tables for VPC peering are least access" scored = Fals...
aa1f4e57703877e33a85f7f412bd00be9761310e
3,625,364
def kiv_pred(df: Kerneldict, lam: float, xi: float, stage: int) -> np.ndarray: """Kernel instrumental variable prediction.""" n = len(df["y1"]) m = len(df["y2"]) brac = make_psd(df["K_ZZ"]) + lam * np.eye(n) W = np.linalg.solve(brac, df["K_XX"]).T @ df["K_Zz"] brac2 = make_psd(W @ W.T) + m * xi * make_psd(...
8ada371e3596631af4b2cfb0b2f7af35e7e75461
3,625,365
def _query_multi_armed_bandit_probabilities(): """Get query results. Queries above BANDIT_PROBABILITY_QUERY and yields results from bigquery. This query is sorted by strategies implemented.""" client = big_query.Client() return client.query(query=BANDIT_PROBABILITY_QUERY).rows
181a38cd4602830c68ccd008d0ae857ea36ee86d
3,625,366
from datetime import datetime import logging import json def check_jobs(): """Check if various jobs have been running. The following URL parameters can be provided: - names: - Comma separated list of names of tasks to check. - seconds (default 3600) - How many seconds are allowed since last completio...
ffb6da52342eb28cfc811918fb62dd7dede5f4e6
3,625,367
def med(data, mw=24, sf=16, sigma=5.0): """ Median baseline correction Algorith described in: Friedrichs, M.S. JBNMR 1995 5 147-153. Parameters: * data Array of spectral data. * mw Median Window size in pts. * sf Smooth window size in pts. * sigma Standard-deviation of Gaus...
0c00f8740b61b5706f5be275e3a6cba9594cb1fa
3,625,368
def raoult_liquido(fraccion_vapor, presion_vapor, presion): """Calcula la fraccion molar de liquido mediante la ec de Raoult""" return fraccion_vapor * presion / presion_vapor
bd15f53ee74ef3dc1925ee3da7133a9c3f455333
3,625,369
def deletePlayers(): """Remove all the player records from the database.""" dbcursor = connect() dbcursor.execute("TRUNCATE players") return 1
57fb88118faec5b7a4836f176c210786a57bd5bd
3,625,370
def recursepath(path, reverse=False): # type: (Text, bool) -> List[Text] """Get intermediate paths from the root to the given path. Arguments: path (str): A PyFilesystem path reverse (bool): Reverses the order of the paths (default `False`). Returns: list: A list of...
a00286a2933eac2a5e8115fe9bb9bfd6de4d0c64
3,625,371
def pack_items(arrays, key_encoding="utf-8"): """ Packs the specified items by computing the relevant file offsets and return the list of ItemDescriptors and the overall size of the file. """ num_items = len(arrays) # We store the keys in sorted order in the key block. sorted_keys = sort...
da01e3e8662fa925c94c642ecfb771e7d880ac10
3,625,372
def list_datasets(): """Returns the list of available FiftyOne datasets. Returns: a list of :class:`Dataset` names """ # pylint: disable=no-member return sorted(foo.DatasetDocument.objects.distinct("name"))
727d397f2e2e6d62b7faa7e76b75f0b78ba71c62
3,625,373
def wayPointDistribution(rx, ry, ryaw, s): """ :param rx: :param ry: :param ryaw: :param s: :return: generate the efficients of the reference line """ x_list = [] y_list = [] theta_list = [] s_list = [] for i in range(len(rx)): if 20 * i > (len(rx) - 1): break x_list.append(rx[20 * i]) y_list.app...
0813888ae810a617804af8129baa38c8f388aed2
3,625,374
import bottleneck as bn def rolling_median_(a, n, axis = 0, data = None, instate = None): """ Equivalent to rolling_median(a) but returns also the state. For full documentation, look at rolling_median.__doc__ """ state = instate or dict(vec = None) return _data_state(['data','vec'],_rolli...
c3d3a3ad892bbe2fe39d7ad7823d10d8bed38fca
3,625,375
def implemented_motifs(): """ Returns ------- List strings of all implemented motif definitions """ return ['Sheet', 'Gamma', 'Herringbone', 'Sandwich']
63564c7e1b3e7e5f8f6b93354a3e268a79e9c5de
3,625,376
def left(direction): """rotates the direction counter-clockwise""" return (direction + 3) % 4
f8136385e5fec11bf26a97f77e336b04ce783571
3,625,377
def union(list1, list2): """Union of two lists, returns the elements that appear in one list OR the other. Args: list1 (list): A list of elements. list2 (list): A list of elements. Returns: result_list (list): A list with the union elements. Examples: >>> union([1,2,3...
983e96ceb4f4eeb2b4b2d96362a0977be0cb2222
3,625,378
def render_analytics_code(): """ Renders the new google analytics snippet. """ return { 'ANALYTICS_TRACKING_ID': getattr(settings, 'ANALYTICS_TRACKING_ID', 'UA-XXXXXXX-XX'), 'ANALYTICS_DOMAIN': getattr(settings, 'ANALYTICS_DOMAIN', 'auto') }
e88e928ce43b91eef5fc3b85a8af54d6fd5b0224
3,625,379
import urlparse def valid_proxy(proxy): """Return 1 if the proxy string looks like a valid url, for an proxy URL else return 0.""" scheme, netloc, url, params, query, fragment = urlparse.urlparse(proxy) if scheme != 'http' or params or query or fragment: return 0 return 1
f3e9bddd49eb5fa31260876343a15c2b7b5bf7af
3,625,380
def oauth2_from_dict(oauth2_dictionary: dict): """ The function converts a dictionary of OAuth2 to a OAuth2 object. :param oauth2_dict: A dictionary that contains the keys of a OAuth2. :type oauth2_dict: dict :rtype: ibmpairs.authentication.OAuth2 :raises Exception: if not a di...
66d36c6dc2f6eaf6b87907854bdc8e9c59864749
3,625,381
def _initiate_pipeline_stop( mlmd_handle: metadata.Metadata, pipeline_uid: task_lib.PipelineUid) -> metadata_store_pb2.Execution: """Initiates a pipeline stop operation. Upon success, MLMD is updated to signal that the pipeline given by `pipeline_uid` must be stopped. Args: mlmd_handle: A handle t...
87c857e10d95cd79cd22460f8ee3c613d8d1dc1f
3,625,383
def slot_schedule_difference(old_schedule, new_schedule): """Compute the difference between two schedules from a slot perspective Parameters ---------- old_schedule : list or tuple of :py:class:`resources.ScheduledItem` objects new_schedule : list or tuple of :py:class:`resources.Sc...
fbc21d67e2738131246c62f1ccc7b539fef44c9c
3,625,384
def drive_cancellation_seq( drive_op_code, ramsey_qubit_names, operation_dict, sweep_points, n_pulses=1, pihalf_spacing=None, prep_params=None, cal_points=None, upload=True, sequence_name='drive_cancellation_seq'): """ Sweep pulse cancellation parameters and measure Ramsey on qubits the ...
5140bb2a97f34d45bc29d164cee725907f756682
3,625,385
def generate_inputs(generate_calc_job_node, fixture_localhost, generate_structure, generate_kpoints_mesh): """Create the required inputs for the ``ProjwfcCalculation``.""" entry_point_name = 'quantumespresso.pw' inputs = {'structure': generate_structure(), 'kpoints': generate_kpoints_mesh(4)} parent_ca...
25d15d6123a5ab1c5f26a050cfe1925cb185b127
3,625,386
import re def list_all_links_in_page(source: str): """Return all the urls in 'src' and 'href' tags in the source. Args: source: a strings containing the source code of a webpage. Returns: A list of all the 'src' and 'href' links in the source code of the webpage. """ retu...
f17f2ac2724fcfdd041e2ad001557a0565b51e00
3,625,387
def resp_delete_successfully(msg): """Response 202""" response = jsonify({ 'message': f'{msg} delete successfully.' }) response.status_code = 202 return response
449585ee86d16c41f4a0ee5f2cee9276ca39e8d4
3,625,388
import math def embedding_column_v2(categorical_column, dimension, combiner='mean', initializer=None, max_sequence_length=0, learning_rate_fn=None, embedding_lookup_device=No...
aa776edad95892fd7e1f74810497e078dd561649
3,625,389
def synthesize_data(): """ synthesize the (block, program) pairs :return: train_shape, train_prog, val_shape, val_prog """ # == training data == data = [] label = [] n_samples = [5000, 30000, 5000, 5000, 5000, 10000, 5000, 5000, 5000, 5000, 30000, ...
41a254326e116dcc9f0942ba984e549c0ed52540
3,625,390
from bs4 import BeautifulSoup def parse_predict_data(html: str) -> list[tuple]: """Returns the following tuple: (week, (away_data, home_data)) """ predict_meta = FTE_PREDICT_STATS parsed = [] soup = BeautifulSoup(html, HTML_PARSER) # build field processor based on predict metadata field...
b1edfa0ced51fce0dad8b2182a375643eee3a0d0
3,625,391
def get_direction(source, destination): """Find the direction drone needs to move to get from src to dest.""" lat_diff = abs(source[0] - destination[0]) long_diff = abs(source[1] - destination[1]) if lat_diff > long_diff: if source[0] > destination[0]: return "S" else: ...
224a8df79cbafbcf1eed8df522ab7f58cc93598d
3,625,392
def newAction( parent, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, enabled=True, checked=False, ): """Create a new action and assign callbacks, shortcuts, etc.""" a = QtWidgets.QAction(text, parent) if icon is ...
a58e20293bca2888360151cb9ef905c3c4a17f5e
3,625,394
def _echelon_form(M, iszerofunc=_iszero, simplify=False, with_pivots=False, dotprodsimp=None): """Returns a matrix row-equivalent to ``M`` that is in echelon form. Note that echelon form of a matrix is *not* unique, however, properties like the row space and the null space are preserved. Parame...
c6e0f1afe21432c18ef4da705074f9c348cc4da5
3,625,395
def div23(): """ Returns the divider 22222222222222222222222 :return: divider23 """ return divider23
61dbccd02231227e60c5ac70787cb473c5c6ca45
3,625,397
from datetime import datetime import pytz def datetime_to_timestamp(dt): """Converts a `datetime.date` or `datetime.datetime` to milliseconds since epoch. Args: dt: a `datetime.date` or `datetime.datetime` Returns: the number of milliseconds since epoch """ if type(dt) is dat...
328b1aaa45477cc9f6502b8a8210f174b4ececc3
3,625,398
def get_specific_dummies(df, col_map=None, prefix=None, suffix=None, return_df=True): """ Given a mapping of column_name: list of values, one hot the values in the column and concat to dataframe. Optional arguments to add prefixes and/or suffixes to created column names. Example col_map: {'foo':['...
98f2adcd49a59c4c9774e166019aedf9e59d9939
3,625,399
def create_controls(pagesize): """ Create an LDAP control with a page size of "pagesize". """ if LDAP24API: return SimplePagedResultsControl(True, size=pagesize, cookie='') else: return SimplePagedResultsControl(ldap.LDAP_CONTROL_PAGE_OID, True, ...
4875878b6e96fb3d06cf580f4a82f1104bf520e3
3,625,401
def threshold_measurement(state, instruction, shots): """ NOTE: This function calculates only by using torontonian. """ if not np.allclose(state.xpxp_mean_vector, np.zeros_like(state.xpxp_mean_vector)): raise NotImplementedError( "Threshold measurement for displaced states are not s...
5f07f01ebb2883d6a36f4e27003d1c6341fea779
3,625,402
def white(N, sigma=1, prng=None): """ Create white noise. Parameters --------- N : numeric Length of 1d noise array to return sigma : numeric Standard deviation prng : np.random.RandomState, None A RandomState instance, or None """ prng = process_prng(pr...
40178bb71786ed9da558f7dcd34090e033e9a202
3,625,403
from pathlib import Path from typing import Tuple from typing import List import gzip def get_sequence( series: pd.Series, path_to_pdb: Path ) -> Tuple[str, str, int, int, List[int]]: """Gets a sequence of from PDB file, CATH fragment indexes and secondary structure labels. Parameters ---------- ...
17b3132b0d1050154595bb746cfc1e3ddf505ddb
3,625,404
def generate_without_options(): """ Returns 1 to 6 Pokemon based on default generator values """ # Generator chooses how many Pokemon to generate number_of_pokemon = randint(1,6) try: api_response = _send_api_request(num_pokemon=number_of_pokemon) except: return statement(re...
e8104227b0494b6cd4e9475b421542e6dbd86de7
3,625,406
import numpy def fit_harmonic_decay(data, deltat=1.0, numcoef=DEFCOEF, axis=-1): """Fit harmonic functions with exponential decay. Can be used to fit frequency-domain fluorescence image data with photobleaching. Parameters ---------- data : array_like Experimental data (observed valu...
07a3c2080ed58f6febc1271a335dc9fef5750887
3,625,407
import math def lab_to_lch(lab): """Din99o Lab to Lch.""" l, a, b = lab h = math.degrees(math.atan2(b, a)) c = math.sqrt(a ** 2 + b ** 2) # Achromatic colors will often get extremely close, but not quite hit zero. # Essentially, we want to discard noise through rounding and such. if c <=...
6c63eb19a7581f2bf41053cef99fc0dc23b79d6c
3,625,408
def moments(data, n_neighbors=30, n_pcs=30, mode='connectivities', method='umap', metric='euclidean', use_rep=None, recurse_neighbors=False, renormalize=False, copy=False): """Computes moments for velocity estimation. Arguments --------- data: :class:`~anndata.AnnData` Annotated dat...
c6e2db61e2b12274039342454fc87849723d8ed8
3,625,409
def QuadRemeshAsync1(thisMesh, parameters, guideCurves, progress, cancelToken, multiple=False): """ Quad remesh this mesh asynchronously. Args: guideCurves (IEnumerable<Curve>): A curve array used to influence mesh face layout The curves should touch the input mesh Set Guide...
b59c11c8c42e2131828c22ff17eb26cbbf7c6b0c
3,625,410
def are_close(col1, col2): """This function used to compare values of collections with numeric data """ if len(col1) != len(col2): raise ValueError("Different size of input collections") result = [] for x, y in zip(col1, col2): result.append(abs(abs(x) - abs(y)) < 0.4) r = T...
72896f522a5fc7cb9f4f96e873c14797009877fe
3,625,411
def compute_depression(input_dem, scale_factor=1, curvature_percentile=75, return_polygon=True, alpha=0.5): """ Compute depressions and return a new image with largest depressions filled in. Parameters ---------- input_dem : np.array, rd.rdarray 2d array of elevation DNs, a DEM ...
3341b7c88ad82a0437a2a264ac91f00bf24de471
3,625,412
from typing import Dict from typing import Any def _deregister_ec2_instance( public_address: str, require_no_running_jobs: bool, region_name: str ) -> bool: """ Deregisters an EC2 instance. If require_no_running_jobs is true, then only deregisters if there are no currently running jobs on the instance...
c43f15b3ba3bedfb478889caaf91eeb1fee7df41
3,625,413
def mse(pred, labs): """ Calculates MSE :param pred: sequence of Strings / predicted score values as strings :param labs: sequence of Strings / true score values as strings :return: (Int, Int) / MSE of valid samples AND number of invalid samples """ idx = np.where(np.array([isfloat(x) for x ...
69b28cfadde29b9d80ec07d41a82521e04e048bb
3,625,415
def described_field_type(singular_type_field): """ Human readable equivalent of a singular avro type - e.g. long -> number. """ if isinstance(singular_type_field, dict): if "logicalType" in singular_type_field: return singular_type_field["logicalType"] else: if si...
11514dec5fe2ee6b501a5c03d7321ed1f6a861af
3,625,416
def package_releases(name, show_hidden=True): """return a list of package releases""" return pypi.package_releases(name, show_hidden)
e820369935e56b3b0074257cedeaf633fd08512c
3,625,418
def _randomize_network(network, keep): """ This function returns a network with the same nodes and edge number as the input network. However, each edge is placed randomly. :param network: NetworkX object :param keep: List of conserved edges :return: Randomized network """ null = nx.Grap...
eb0881625bdd73f0a94018feb0facb76c868ffb9
3,625,419
import six def get_docstring(value, module_name=None): """ Return the docstring for the given value; or C{None} if it does not have a docstring. @rtype: C{unicode} """ docstring = getattr(value, '__doc__', None) if docstring is None: return None elif isinstance(docstring, six.t...
e68e997e843d4110ec608ad6eadac46fdef74eda
3,625,420
import requests def _classswitch_file(url, header, params): """ 文件存储类型转换请求 :param url:string类型,文件存储类型转换的url :param header: dict类型,http 请求header,键值对类型分别为string,比如{'User-Agent': 'Google Chrome'} :param params: dict类型,http 请求的查询参数,键值对类型分别为string类型 :return: ret: return message, None if response s...
c61af20073932c67a5d4607325eee780da224ccb
3,625,422
def cofa(session=None): """ Return location class of current COFA. Parameters ---------- session: db session to use """ h = Handling(session) located = h.cofa() h.close() return located
363fb61bee4cc0e5c9b95a2c2623050f693e2b0e
3,625,423
def identity(*args, **kwargs): """ An identity function used as a default task to test the timing of. """ return args, kwargs
472808f6b5260569538f26513f24ffcb1bd88c4d
3,625,424
def _with_largest_possible_masks(oneof): """Add masks to enable all possible ops / filters in the search space.""" if oneof.tag == basic_specs.OP_TAG: n = len(oneof.choices) mask = tf.constant([1 / n] * n, dtype=tf.float32) elif oneof.tag == basic_specs.FILTERS_TAG: largest_index = None for i, cho...
c7a9bfb4bb875abe3f6232873f64ad70334c71f8
3,625,425
def list_merger_list0(*lists): """Picks leading list, discards everything else""" return lists[0]
c571adb593de991f633a28b086e61fa7888cbc7e
3,625,426
def serialize(): """ Get dict with internal data """ with _exception_log_lock: return {'exceptions': _exceptions.copy()}
aacebcf8d18e7f1654ed2e16ed846dfe35668532
3,625,427
def cmp(a,b): """3-way comparison like the cmp operator in perl""" if a is None: a = '' if b is None: b = '' return (a > b) - (a < b)
97c5a33e9161196119abbc323841be0b1cfdda14
3,625,428
def _pixel_to_map(coordinates, geotransform): """Apply a geographical transformation to return map coordinates from pixel coordinates. Parameters ---------- coordinates : :class:`numpy:numpy.ndarray` 2d array of pixel coordinates geotransform : :class:`numpy:numpy.ndarray` geogr...
4aee896d9185625b838c12215835e513996f15b7
3,625,429
def median_filter(ts: pd.Series, stats: pd.DataFrame = None, second_pass=False): """Apply rolling median filter to time series""" _ts = ts.dropna() # Make sure there are no empty values filtered = _ts.copy() # Assing rolling median from 2nd to 2nd last index filtered.iloc[1:-1] ...
d9b21f26eb47584aea0376ab0f4a2ca3d055432d
3,625,430
def calculate_pairwise_correlations(df_variable: pd.DataFrame) -> dict: """For each pair of modalities, calculate correlations, and put them together into a column""" modalities = list(df_variable.columns.values) df_dict = {} modality_iterator = itt.combinations(modalit...
9aef93cf3ccf040f7c4a0ee804a171f38ac7646c
3,625,431
from datetime import datetime def event_context_vars(env_deployment): """Return context variables for zaza-events configuration params. Note that it is cached because env_deployment is immutable, and the date should only be evaluated the first time. The "bundle" var is derived from the first model i...
b618e00cec98e93c3ec44df400a1c5e022063c27
3,625,432
def update_model(model, player, winner, board_hist, move_hist, learnig_rate): """ Updates 2 layer policy network weights using gradient descent (policy gradients) according to the played game data. Parameters ---------- model: dict {"W1": [numpy Hx9 array], "W2": [numpy 9xH array]} Policy n...
c7dd57005fc8892be2d3682b562d8097277758a6
3,625,434
def init(base_url, username=None, password=None, verify=True): """Initialize ubersmith API module with HTTP request handler.""" handler = RequestHandler(base_url, username, password, verify) set_default_request_handler(handler) return handler
07b0ab1f076b0ae79dc6f4eaba87078d9f8c700e
3,625,435
def view_mol(option, maps=None, out_put=None, target_id=None, extra=None): """Function to render the 3D coordinates of a molecule Takes a PDB code as input Returns an SD block""" my_mols = Molecule.objects.filter(prot_id__code=option) new_mol = "" for mol in my_mols: new_mol += (str(mol....
e42b583e63f3ac2ad6cb7d241754491604b66455
3,625,436
def left_fit_width(s, width, fill=' '): """Make a string fixed width by padding or truncating. Note: fill can't be full width character. """ s = trim_width(s, width) s += fill * (width - str_width(s)) return s
11d285b6065ac1f95d9a9f9f31bd55849c53f8d6
3,625,437
def create_item_selection_window(): """ This function contains all the logic of the item selection window and will run the window by it's own. :return: None """ item_selection_window = sg.Window("Item selection", generate_item_selection_layout(), finalize=True, ...
d33eb2858786dc38d90b22147ec1145236c206c3
3,625,438
def check(consumer_households_in_siumulation, prosumer_households_in_siumulation): """[summary] Checks if a new user needs to be added to the simulation or if a user is removed Args: consumer_households_in_siumulation ([list]): [List of current consumers in the simulation] prosumer_hous...
00d84b25ce1533406b78aa455c8605269978983b
3,625,439
def create_model(inner_settings:InnerModelSettings,outer_settings:OuterModelSettings) -> OuterModel: """ function creates an OuterModel with provided settings. Args: inner_settings: an instannce of InnerModelSettings outer_settings: an instannce of OuterModelSettings """ model = Out...
28e0f47b2130ecb4a5e08886c08e9589af04a932
3,625,440
def create_logdir(method, weight, label, rd): """ Directory to save training logs, weights, biases, etc.""" return "bigan/train_logs/mnist/{}/{}/{}/{}".format(weight, method, label, rd)
4b4edcc9c0c36720e76013a6fb0faf1b49472bc0
3,625,441
def ontocreate(): """View function for the standard vocabulary creator module. Returns: str: HTML page for the standard creator module. """ form = OntologyDescript() form2 = InvertLangButton() return render_template("ontocreate.html", form=form, form2=form2)
83197d6062ed8d78882980542949f43ba8df3982
3,625,442
def log_spherical_gaussian(theta, variance): """Unnormalized log density of a spherical Gaussian""" return -np.sum(theta**2) / (2 * variance)
d113c4014b72a41c2f0cb252a2a6b6e2ae5f3e0b
3,625,443
def apply_target(rule, substitutions): """Return target string with non-terminals replaced with substitutions.""" if rule.arity != len(substitutions): raise ValueError output = [] for token in rule.target: if token == NT_1: output.append(substitutions[0]) elif token == NT_2: output.appen...
595333291d2fcce159c927f09666de7a1f7be3bf
3,625,444
import io import sqlite3 def adapt_array(arr): """ """ # https://stackoverflow.com/a/18622264 # http://stackoverflow.com/a/31312102/190597 (SoulNibbler) out = io.BytesIO() np.save(out, arr) out.seek(0) return sqlite3.Binary(out.read())
74ca1db4ed25dd60f6ec91ade3c150be313fd1c6
3,625,445
from typing import List def usage_stats_invalid_messages_exist(messages: List[str]) -> bool: """ Since the usage stats functionality does not raise exceptions but merely logs them, we need to check the logs for errors. """ return any( [ UsageStatsExceptionPrefix.INVALID_MESSAGE.va...
3de0e6bc0fa82c57b07209e8ccda5ade3465f668
3,625,446
def spike_train_from_string(s, edges, sep=' ', is_sorted=False): """ Converts a string of times into a :class:`.SpikeTrain`. :param s: the string with (ordered) spike times. :param edges: interval defining the edges of the spike train. Given as a pair of floats (T0, T1) or a single float...
1ecfaa7b8ac7320eef95e8b4db16775669adef9a
3,625,447
def batch_effective_sample_size(x, mu, var, logger=None): """ Calculate the effective sample size of sequence generated by MCMC. :param x: :param mu: mean of the variable :param var: variance of the variable :param logger: log :return: effective sample size of the sequence We calculate ...
808b4bb4f5294c58d6c3eee42af772d9818c91f9
3,625,449
def copy_ecf_ord_players_post_2006_rules(widget, logwidget=None): """Import a new ECF downloadable OGD rating list csv file. widget - the manager object for the ecf data import tab. Downloads have been produced in this format since mid-2020. These are available for all lists since 1994 according to ...
af72186f0cad73e0d37dcd996991d901912de1c7
3,625,450
from io import StringIO import io def _str_io(*args, **kwargs): """Helper for PY2/Py3 StringIO""" if StringIO: return StringIO.StringIO(*args, **kwargs) return io.StringIO(*args, **kwargs)
b9013fae9ca9231dfb74064ee293727734c38697
3,625,451
import functools def eval_mode(f): """a decorator designed for nn.Module methods which wraps the function call in the eval context. Note: you can use this decorator for any function that takes a model as first parameter. but it's reccommended to use on nn.Module methods. """ @functoo...
740936b7118dda0e4a28c73914344de50d73e9cb
3,625,452
from datetime import datetime def read_logs(start_time=None): """ Read all log messages after a certain time from the latest text file log Parameters ---------- start_time : datetime The earliest timestamp from which to read logs Returns ------- string, datetime The relev...
8a3a3feeb7c98fe5938e81e2fd5afa06bbd7b02a
3,625,453