content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Union from typing import Sequence def average_false_positive_score( y_true: Union[Sequence[int], np.ndarray, pd.Series], y_pred: Union[Sequence[int], np.ndarray, pd.Series], ) -> float: """Calculates the average false positive score. Used for when we have more than 2 classes and want ou...
4b789381e25efffc0aa811287bab8299edf6b962
15,243
import html def display_text_paragraph(text: str): """Displays paragraph of text (e.g. explanation, plot interpretation) Args: text (str): Informational text Returns: html.Small: Wrapper for text paragraph """ return html.P(children=[text], style={'font-size': '...
8c4ae8f7b606b81726149891fb5db624647ba484
15,244
def is_numeric(_type) -> bool: """ Check if sqlalchemy _type is derived from Numeric """ return issubclass(_type.__class__, Numeric)
1d604873e4043206b50ddc09c691331c4c50c49c
15,245
def make_generic_time_plotter( retrieve_data, label, dt, time_unit=None, title=None, unit=None, ): """Factory function for creating plotters that can plot data over time. The function returns a function which can be called whenever the plot should be drawn. ...
3fa391a94973e5b98394e684d8e4018fa16811df
15,246
def registration(request): """Registration product page """ if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): # Create a new user object but avoid saving it yet new_user = user_form.save(commit=False) # Se...
d176a5027058124dfd30a247f924776a87f7aba3
15,247
def error_measure(predictions, labels): """ calculate sum squared error of predictions """ return np.sum(np.power(predictions - labels, 2)) / (predictions.shape[0])
135b3b90047895ecff90aed6f4a37d73ef0ddd17
15,248
def add3(self, x, y): """Celery task: add numbers.""" return x + y
0d1017953dcdd1a0791afe291ce005247547f198
15,249
def zscore(dat, mean, sigma): """Calculates zscore of a data point in (or outside of) a dataset zscore: how many sigmas away is a value from the mean of a dataset? Parameters ---------- dat: float Data point mean: float Mean of dataset sigma: flaot Sigma of dataset ...
b11216e50632e2024af0a389184d5e1dba7ed4fd
15,250
from typing import OrderedDict from typing import Tuple from re import S def _create_ast_bilinear_form(terminal_expr, atomic_expr_field, tests, d_tests, trials, d_trials, fields, d_fields, constants, ...
0929f83f1cfcc6424b00d5b931017ec5af6ffaee
15,251
import math def asen(x): """ El arcoseno de un número. El resultado está expresado en radianes. .. math:: \\arcsin(x) Args: x (float): Argumento. Returns: El ángulo expresado en radianes. """ return math.asin(x)
c52f7fc504c1eb02eb240378b14b19b0752c7299
15,253
def get_mock_response(status_code: int, reason: str, text: str): """ Return mock response. :param status_code: An int representing status_code. :param reason: A string to represent reason. :param text: A string to represent text. :return: MockResponse object. """ MockResponse = namedtup...
e1743755c64796e5644a00e26414fc16c110c1b6
15,254
import traceback def get_user_stack_depth(tb: TracebackType, f: StackFilter) -> int: """Determines the depth of the stack within user-code. Takes a 'StackFilter' function that filters frames by whether they are in user code or not and returns the number of frames in the traceback that are within user...
e02f1ca3ee6aeb765a09806ecded5919a28b5df0
15,255
def unused(attr): """ This function check if an attribute is not set (has no value in it). """ if attr is None: return True else: return False
febc225f3924fdb9de6cfbf7eba871cce5b6e374
15,256
def compute_npipelines_xgbrf_5_6(): """Compute the total number of XGB/RF pipelines evaluated""" df = _load_pipelines_df() npipelines_rf = np.sum(df['pipeline'].str.contains('random_forest')) npipelines_xgb = np.sum(df['pipeline'].str.contains('xgb')) total = npipelines_rf + npipelines_xgb resul...
7e7b9ea536564b4796dcf9eea6866a8c64ce0c4e
15,257
def get_evaluate_SLA(SLA_terms, topology, evaluate_individual): """Generate a function to evaluate if the flow reliability and latency requirements are met Args: SLA_terms {SLA} -- an SLA object containing latency and bandwidth requirements topology {Topology} -- the reference topology object f...
81fdaa07e3fc21066ab734bef0cc71457d40fb5b
15,258
def latest_consent(user, research_study_id): """Lookup latest valid consent for user :param user: subject of query :param research_study_id: limit query to respective value If latest consent for user is 'suspended' or 'deleted', this function will return None. See ``consent_withdrawal_dates()`` f...
2295b592a0c1fdaf3b1ed21e065f39e73a4bb622
15,259
def microarray(): """ Fake microarray dataframe """ data = np.arange(9).reshape(3, 3) cols = pd.Series(range(3), name='sample_id') ind = pd.Series([1058685, 1058684, 1058683], name='probe_id') return pd.DataFrame(data, columns=cols, index=ind)
7bca3cf21f2942819c62c597af8761ec04fa91ba
15,260
from typing import Tuple def find_next_tag(template: str, pointer: int, left_delimiter: str) -> Tuple[str, int]: """Find the next tag, and the literal between current pointer and that tag""" split_index = template.find(left_delimiter, pointer) if split_index == -1: return (template[pointer:], le...
82d091ef6738ffbe93e8ea8a0096161fc359e9cb
15,261
def hasNLines(N,filestr): """returns true if the filestr has at least N lines and N periods (~sentences)""" lines = 0 periods = 0 for line in filestr: lines = lines+1 periods = periods + len(line.split('.'))-1 if lines >= N and periods >= N: return True; return Fa...
d75c4d241d7c4364c410f2dbae06f1c4d439b14e
15,262
def CAMNS_LP(xs, N, lptol=1e-8, exttol=1e-8, verbose=True): """ Solve CAMNS problem via reduction to Linear Programming Arguments: ---------- xs : np.ndarray of shape (M, L) Observation matrix consisting of M observations N : int Number of observations lp...
e7f0416e0fa6949e50341b7a0009e574ecf6b0be
15,263
def hamiltonian_c(n_max, in_w, e, d): """apply tridiagonal real Hamiltonian matrix to a complex vector Parameters ---------- n_max : int maximum n for cutoff in_w : np.array(complex) state in d : np.array(complex) diagonal elements of Hamiltonian e : np.array(com...
9b78d86592622100322d7a4ec031c1bd531ca51a
15,264
def unique_badge(): """ keep trying until a new random badge number has been found to return """ rando = str(randint(1000000000, 9999999999)) badge = User.query.filter_by(badge=rando).first() print("rando badge query = {}".format(badge)) if badge: unique_badge() return rando
64a60dd420516bdc08a8ac2102b83e0cf92086ef
15,265
def mid_price(high, low, timeperiod: int = 14): """Midpoint Price over period 期间中点价格 :param high: :param low: :param timeperiod: :return: """ return MIDPRICE(high, low, timeperiod)
7092d057da86b12b10da6928367aee705e14569a
15,266
import pickle def load_pyger_pickle(filename): """ Load pyger data from pickle file back into object compatible with pyger plotting methods :param filename: File name of pickled output from calc_constraints() This is only meant to be used to read in the initial constraints object produced by calc_co...
23f4d4f2e3cae514ed65d62035277417c9b246a8
15,267
from typing import OrderedDict def createitemdict(index, tf2info): """Take a TF2 item and return a custom dict with a limited number of keys that are used for search""" item = tf2info.items[index] name = item['item_name'] classes = tf2api.getitemclasses(item) attributes = tf2api.getitemattribu...
9f9eceb588c7dc031bab633eadc139095806d38a
15,269
def port_list(request, board_id): """Get ports attached to a board.""" return iotronicclient(request).port.list()
0fcf7fc4db60678c7e5ec4606e9b12174966912f
15,270
def pure_python_npairs_per_object_3d(sample1, sample2, rbins, period=None): """ """ if period is None: xperiod, yperiod, zperiod = np.inf, np.inf, np.inf else: xperiod, yperiod, zperiod = period, period, period npts1, npts2, num_rbins = len(sample1), len(sample2), len(rbins) co...
98b45bbbf50eea9e4dfa39cfd9093ec6fc0c0459
15,272
def cal_aic(X, y_pred, centers, weight=None): """Ref: https://en.wikipedia.org/wiki/Akaike_information_criterion """ if weight is None: weight = np.ones(X.shape[0], dtype=X.dtype) para_num = centers.shape[0] * (X.shape[1] + 1) return cal_log_likelihood(X, y_pred, centers, weight) - para_num
fd6f7019dcd6aec7efb21ff159541cee0e56bdfb
15,273
def get_gid(cfg, groupname): """ [description] gets and returns the GID for a given groupname [parameter info] required: cfg: the config object. useful everywhere groupname: the name of the group we want to find the GID for [return value] returns an integer representing t...
ee139abfe8904de1983e505db7bf882580768080
15,274
from typing import Set from typing import Dict from typing import Any def _elements_from_data( edge_length: float, edge_width: float, layers: Set[TemperatureName], logger: Logger, portion_covered: float, pvt_data: Dict[Any, Any], x_resolution: int, y_resolution: int, ) -> Any: """ ...
80bef4fc80a22da823365fcdc756b6e35d19cdf2
15,275
def GetControllers(wing_serial): """Returns control gain matrices for any kite serial number.""" if wing_serial == m.kWingSerial01: airspeed_table = ( [30.0, 60.0, 90.0] ) flap_offsets = ( [-0.209, -0.209, 0.0, 0.0, 0.009, 0.009, -0.005, 0.017] ) longitudinal_gains_min_airspeed =...
e9e557909cfb9a7e885f14d20948436b653f4f31
15,276
def rotate(mat, degrees): """ Rotates the input image by a given number of degrees about its center. Border pixels are extrapolated by replication. :param mat: input image :param degrees: number of degrees to rotate (positive is counter-clockwise) :return: rotated image """ rot_mat = cv2...
6de73e2701fdad422497dd53d271accc1f039128
15,277
def spec_defaults(): """ Return a mapping with spec attribute defaults to ensure that the returned results are the same on RubyGems 1.8 and RubyGems 2.0 """ return { 'base_dir': None, 'bin_dir': None, 'cache_dir': None, 'doc_dir': None, 'gem_dir': None, ...
5f220168e2cc63c4572c29c17cb4192a7a5d1427
15,278
def rdict(x): """ recursive conversion to dictionary converts objects in list members to dictionary recursively """ if isinstance(x, list): l = [rdict(_) for _ in x] return l elif isinstance(x, dict): x2 = {} for k, v in x.items(): x2[k] = rdict(v) ...
dd09486aa76ee1a27306510a1100502bae482015
15,279
import requests from bs4 import BeautifulSoup def get_pid(part_no): """Extract the PID from the part number page""" url = 'https://product.tdk.com/en/search/capacitor/ceramic/mlcc/info?part_no=' + part_no page = requests.get(url) if (page.status_code != 200): print('Error getting page({}): {}'...
8cc01b011e23d3bc972cb5552662b55ab998dba0
15,280
def verbatim_det_lcs_all(plags, psr, susp_text, src_text, susp_offsets, src_offsets, th_shortest): """ DESCRIPTION: Uses longest common substring algorithm to classify a pair of documents being compared as verbatim plagarism candidate (the pair of documents), and removing the none verbatim cases if positive ...
d233f3745bdd458fe65cbbdbc056c8cca611d755
15,281
import multiprocessing import logging import multiprocessing.dummy as m import multiprocessing as m import itertools def autopooler(n, it, *a, chunksize=1, dummy=False, return_iter=False, unordered=False, **ka): """Uses multiprocessing.Pool or multiprocessing.dummy.Pool to r...
489426a16977b632dd16fe351eee167c7eb5fb0d
15,282
def grow_population(initial, days_to_grow): """ Track the fish population growth from an initial population, growing over days_to_grow number of days. To make this efficient two optimizations have been made: 1. Instead of tracking individual fish (which doubles every approx. 8 days which will result O...
88b8283e5c1e6de19acb76278ef16d9d6b94de00
15,283
import PySide.QtGui as QtGui import PyQt5.QtGui as QtGui def get_QBrush(): """QBrush getter.""" try: return QtGui.QBrush except ImportError: return QtGui.QBrush
548226da434077ee1d0d1d2fb4a6762faf5f091d
15,284
def apply_odata_query(query: ClauseElement, odata_query: str) -> ClauseElement: """ Shorthand for applying an OData query to a SQLAlchemy query. Args: query: SQLAlchemy query to apply the OData query to. odata_query: OData query string. Returns: ClauseElement: The modified query...
666dd05856db79ce90f29e864aeaf4188bd425d0
15,285
def get_sql(conn, data, did, tid, exid=None, template_path=None): """ This function will generate sql from model data. :param conn: Connection Object :param data: data :param did: Database ID :param tid: Table id :param exid: Exclusion Constraint ID :param template_path: Template Path ...
45ec23f3e061491ad87ea0a59b7e08e32e5183a2
15,286
import six import base64 def bytes_base64(x): # type: (AnyStr) -> bytes """Turn bytes into base64""" if six.PY2: return base64.encodestring(x).replace('\n', '') # type: ignore return base64.encodebytes(bytes_encode(x)).replace(b'\n', b'')
543b0f1105545cda516890d2d6f4c5a8059c4365
15,287
def is_planar_enforced(gdf): """Test if a geodataframe has any planar enforcement violations Parameters ---------- Returns ------- boolean """ if is_overlapping(gdf): return False if non_planar_edges(gdf): return False _holes = holes(gdf) if _holes.shape[...
0587cd351fcc7355d0767a404e446d91f8c59d4d
15,288
def bson2uuid(bval: bytes) -> UUID: """Decode BSON Binary UUID as UUID.""" return UUID(bytes=bval)
6fc81f03b6eabee3496bab6b407d6c665b001667
15,289
def ape_insert_new_fex(cookie, in_device_primary_key, in_model, in_serial, in_vendor): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("ApeInsertNewFex") method.cookie = cookie method.in_device_primary_key = in_device_primary_key method.in_model = in_model method.in_serial = ...
2d10c37f26357ac9714d0dfe91967f4029857cd5
15,290
import aiohttp import asyncio async def get_pool_info(address, api_url="https://rest.stargaze-apis.com/cosmos"): """Pool value and current rewards via rest API. Useful links: https://api.akash.smartnodes.one/swagger/#/ https://github.com/Smart-Nodes/endpoints """ rewards_url = f"{api_...
34c54c840ed3a412002b99f798c23f495e1eb75d
15,291
def _process_image(filename, coder): """Process a single image file. Args: filename: string, path to an image file e.g., '/path/to/example.JPG'. coder: instance of ImageCoder to provide TensorFlow image coding utils. Returns: image_buffer: string, JPEG encoding of RGB image. height:...
111025b6dddcf7380fd912a84154b551df4be5f3
15,292
def mnist_reader(numbers): """ Read MNIST dataset with specific numbers you needed :param numbers: A list of number from 0 - 9 as you needed :return: A tuple of a numpy array with specific numbers MNIST training dataset, labels of the training set and the length of the training dataset. ...
627a7fd41047383cd5869fe83efea2c2b0e2d25a
15,293
import six def _ensure_list(alist): # {{{ """ Ensure that variables used as a list are actually lists. """ # Authors # ------- # Phillip J. Wolfram, Xylar Asay-Davis if isinstance(alist, six.string_types): # print 'Warning, converting %s to a list'%(alist) alist = [alist]...
bd8115dad627f4553ded17757bfb838cfdb0200b
15,294
def _parse_einsum_input(operands): """Parses einsum operands. This function is based on `numpy.core.einsumfunc._parse_einsum_input` function in NumPy 1.14. Returns ------- input_strings : str Parsed input strings output_string : str Parsed output string operands : list ...
8c95c3d842a29fa637e6190e006638420b8a0d83
15,295
def convert_to_numpy(*args, **kwargs): """ Converts all tf tensors in args and kwargs to numpy array Parameters ---------- *args : positional arguments of arbitrary number and type **kwargs : keyword arguments of arbitrary number and type Returns ------- list ...
8059832fc4841b4cb96dcc77e96dd354dba399c2
15,296
async def delete_contact( contact_key: int, hash: str, resource: Resource = Depends(get_json_resource) ): """ Delete the contact with the given key. If the record has changed since the hash was obtained, a 409 error is returned. """ try: await resource.delete(contact_key, hash) excep...
f984c5ece28ac8b58bb2d2137dcc94e2f3a7bf7c
15,297
import jsonschema def update_model_instance_meta_schema(request, file_type_id, **kwargs): """copies the metadata schema from the associated model program aggregation over to the model instance aggregation """ # Note: decorator 'authorise_for_aggregation_edit' sets the error_response key in kwargs if ...
c6f67f2f6386065919239f7d868797d97aec6874
15,298
def _calculate_permutation_scores_per_col(estimator, X, y, sample_weight, col_idx, random_state, n_repeats, scorer): """Calculate score when `col_idx` is permuted.""" random_state = check_random_state(random_state) # Work on a copy of X to to ensure thread-safety i...
52c49ac3e4fd53490af04c9d862b506214e08f95
15,299
def get_statement_at_line(source: str, lineno: int, checker): """Get statements at line *lineno* from a source string. :param source: The source to get the statements from. :param lineno: Line number which the statement must include. Counted from 1. :param checker: A function that checks each statement...
d2066f5fafa1c20c4b5276e44d82ae95ffa2f59b
15,300
def ptrace(Q, sel): """ Partial trace of the Qobj with selected components remaining. Parameters ---------- Q : :class:`qutip.Qobj` Composite quantum object. sel : int/list An ``int`` or ``list`` of components to keep after partial trace. Returns ------- oper : :cla...
a98e7bea41cff00b44534cecac7f86958ef47ebb
15,301
from operator import index def createConformations(outputfile, forcefield, smiles, sid): """Generate the conformations for a molecule and save them to disk.""" print(f'Generating {index}: {smiles}') try: mol = Molecule.from_smiles(smiles, allow_undefined_stereo=True) fftop = Topology() ...
fce6cb1c7620b755a500e76822aa3ac27b7a12f4
15,302
import numpy import math def two_angle_circular_correlation_coef(angles1, angles2, mean1, mean2): """ Circular correlation measure. SenGupta 2001 """ centered_a = angles1-mean1 centered_b = angles2-mean2 sin_centered_a = numpy.sin(centered_a) sin_centered_b = numpy.sin(centered_b) sin2...
6a95f8726f45105c68b9c0b4f8f13191a88734e2
15,303
from typing import Union import yaml def format_data(data: Union[dict, list]) -> str: """ :param data: input data :return: pretty formatted yaml representation of a dictionary """ return yaml.dump(data, sort_keys=False, default_flow_style=False)
b4e79a8957995fb8e2eaa549a6a208a48574a598
15,304
def eval_on_dataset( model, state, dataset, pmapped_eval_step): """Evaluates the model on the whole dataset. Args: model: The model to evaluate. state: Current state associated with the model (contains the batch norm MA). dataset: Dataset on which the model should be evaluated. Should already ...
dd2296f80db37687de6fc8a4bcf0046d43cda115
15,306
def factorize(n): """ Prime factorises n """ # Loop upto sqrt(n) and check for factors ret = [] sqRoot = int(n ** 0.5) for f in xrange(2, sqRoot+1): if n % f == 0: e = 0 while n % f == 0: n, e = n / f, e + 1 ret.append((f, e)) if n >...
bc4b4a26010f2f18c9989acd2b7d81615b21f8db
15,308
import random def createSimpleDataSet( numOfAttr, numOfObj ): """ This creates a simple data base with 3 attributes The second one is 2 times the first one with some Gauss noise. The third one is just random noise. """ database = [] for i in range(numOfObj): data = data...
dd4e8005634bd49411a785982fe3112acaf8e544
15,309
import tqdm import warnings def clean_data( data, isz=None, r1=None, dr=None, edge=0, bad_map=None, add_bad=None, apod=True, offx=0, offy=0, sky=True, window=None, darkfile=None, f_kernel=3, verbose=False, *, mask=None, ): """Clean data. Par...
d50cb5b723661925c81f215e3bba903b4f9bb56c
15,310
def select_points(): """ Select points (empty) objects. Parameters: None Returns: list: Empty objects or None. """ selected = bpy.context.selected_objects if selected: return [object for object in selected if object.type == 'EMPTY'] print('***** Point (empty) object...
4134277f427518da188d8bcac4d5023d0b39e55a
15,311
def mask_conv1d1(in_channels, out_channels, strides=1, groups=1, use_bias=False, data_format="channels_last", **kwargs): """ Masked 1-dim kernel version of the 1D convolution layer. Parameters: -------...
0c06482e36ef55322ed3b52e68f321750843ef01
15,313
import decimal def decimal_from_tuple(signed, digits, expo): """Build `Decimal` objects from components of decimal tuple. Parameters ---------- signed : bool True for negative values. digits : iterable of ints digits of value each in [0,10). expo : int or {'F', 'n', 'N'} ...
c3b67505440600b5e9f3ce944c9018539b32bbf7
15,314
from typing import Dict def metadata_update( repo_id: str, metadata: Dict, *, repo_type: str = None, overwrite: bool = False, token: str = None, ) -> str: """ Updates the metadata in the README.md of a repository on the Hugging Face Hub. Example: >>> from huggingface_hub impor...
1faf2ae158d598a7538f86ce328ea22b55308507
15,315
def system_types(): """ 系统类型(工作空间类型) :return: """ return Workspace.sys_types().values()
968fbf7993d4ad645fe741ac48702440ba01a2e3
15,318
def get_rnd_simplex(dimension, random_state): """ Uniform random point on a simplex, i.e. x_i >= 0 and sum of the coordinates is 1. Donald B. Rubin, The Bayesian bootstrap Ann. Statist. 9, 1981, 130-134. https://cs.stackexchange.com/questions/3227/uniform-sampling-from-a-simplex Parameters ----...
d5e1105655192fe13bcad5e3dd08a7247461d8bf
15,319
def backup_generate_metadata(request, created_at='', secret=''): """ Generates metadata code for the backup. Meant to be called by the local handler only with shared secret (not directly). """ if not secret == settings.GAEBAR_SECRET_KEY: return HttpResponseForbidden() backup = models.GaebarBackup.all...
30ae381be8454a1df6b47fd5fc55af68f10e8b1f
15,320
import torch def contains_conv(module: torch.nn.Module) -> bool: """ Returns `True` if given `torch.nn.Module` contains at least one convolution module/op (based on `deepcv.meta.nn.is_conv` for convolution definition) """ return any(map(module.modules, lambda m: is_conv(m)))
0f9ae25fa1189c9c576089c913a5d7d9e2739c78
15,321
def _construct_cell(empty=False): """Constructs a test cell.""" cell = scheduler.Cell('top') if empty: return cell rack1 = scheduler.Bucket('rack:rack1', traits=0, level='rack') rack2 = scheduler.Bucket('rack:rack2', traits=0, level='rack') cell.add_node(rack1) cell.add_node(rack2)...
c1b8016b8ff048ab0ecad8c69f960ce3d099bd8c
15,322
def gaussian_kernel(F: np.ndarray) -> np.ndarray: """Compute dissimilarity matrix based on a Gaussian kernel.""" D = squared_dists(F) return np.exp(-D/np.mean(D))
62f97009c791213255d8bdb4efc0fcfa60c20bb0
15,323
def _parse_yearweek(yearweek): """Utility function to convert internal string representations of calender weeks into datetime objects. Uses strings of format `<year>-KW<week>`. Weeks are 1-based.""" year, week = yearweek_regex.search(yearweek).groups() # datetime.combine(isoweek.Week(int(year), int(week)).w...
319166595c506a73d125ed53a11433976aa4f106
15,324
def get_subpixel_indices(galtable, hpix=[], border=0.0, nside=0): """ Routine to get subpixel indices from a galaxy table. Parameters ---------- galtable: `redmapper.Catalog` A redmapper galaxy table master catalog hpix: `list`, optional Healpix number (ring format) of sub-region....
5a2d18f79ef8cc478752ef8059c71a512efced9f
15,325
def is_common_secret_key(key_name: str) -> bool: """Return true if the key_name value matches a known secret name or pattern.""" if key_name in COMMON_SECRET_KEYS: return True return any( [ key_name.lower().endswith(key_suffix) for key_suffix in COMMON_SECRET_KEY_SUFF...
b0250f28638a0ad58a3a45dd8e333610fea378d5
15,326
def showgraphwidth(context, mapping): """Integer. The width of the graph drawn by 'log --graph' or zero.""" # just hosts documentation; should be overridden by template mapping return 0
6e2fad8c80264a1030e5a113d66233c3adc28af8
15,328
def diff_last_filter(trail, key=lambda x: x['pid']): """ Filter out trails with last two key different """ return trail if key(trail[-1]) != key(trail[-2]) else None
82e67a98a1b09e11f2f1ebd76f470969b2dd1a51
15,329
def cpu_times(): """Return a named tuple representing the following system-wide CPU times: (user, nice, system, idle, iowait, irq, softirq [steal, [guest, [guest_nice]]]) Last 3 fields may not be available on all Linux kernel versions. """ procfs_path = get_procfs_path() set_scputimes_n...
70dd518296bc873add8a7164446e908d80e74174
15,330
def calc_centeroid(x, network: DTClustering, n_clusters: int): """クラスタ中心を計算します. Notes: Input x: [batch, sequence, feature, 1] Output: [n_clusters, hidden sequence, hidden feature, 1] """ code = network.encode(x) feature = code.view(code.shape[0], -1) # [batch, sequence * feature] ...
cf0a158d86105e34ad476dbfb7bc6ff911a65e52
15,331
def softXrayMono1(eV, k, m, c, rb_mm, bounce, inOff_deg, outOff_deg, verbose): """ # calculate premirror and grating angles for NSLS-II soft xray monos # eV: energy # k: central line density in mm-1 # m: diffraction order # c: cff 0 < cff < infinity # bounce = 'up' or 'down' # inOff_deg ...
3309b8ec7e3f5433025c4c676bf2966281df4d02
15,333
def createHelmholtz3dExteriorCalderonProjector( context, hminusSpace, hplusSpace, waveNumber, label=None, useInterpolation=False, interpPtsPerWavelength=5000): """ Create and return the exterior Calderon projector for the Helmholtz equation in 3D. *Parameters:* - context (Context) ...
bfb6c139787355d07cb8c82475f34dcc349c55f3
15,334
def prepare_xrf_map(data, chunk_pixels=5000, n_chunks_min=4): """ Convert XRF map from it's initial representation to properly chunked Dask array. Parameters ---------- data: da.core.Array, np.ndarray or RawHDF5Dataset (this is a custom type) Raw XRF map represented as Dask array, numpy ar...
a8c4b442f367759237f77571c51e98bd1cc9d53a
15,335
def colorbar_factory(cax, mappable, **kwargs): """ Create a colorbar on the given axes for the given mappable. .. note:: This is a low-level function to turn an existing axes into a colorbar axes. Typically, you'll want to use `~.Figure.colorbar` instead, which automatically handle...
37b0198ea77db887d92ee4fd45e6df73d49f4223
15,336
import time def fourth_measurer_I_R(uniquePairsDf): """ fourth_measurer_I_R: computes the measure I_R that is based on the minimal number of tuples that should be removed from the database for the constraints to hold. The measure is computed via an ILP and the Gurobi optimizer is used to solve the ILP...
a8e29e0a70dfd2e2a4c151ca25b2f7fd528e25f3
15,337
def is_sublist_equal(list_one, list_two): """ Compare the values of two lists of equal length. :param list_one: list - A list :param list_two: list - A different list :return EQUAL or UNEQUAL - If all values match, or not. >>> is_sublist_equal([0], [0]) EQUAL >>> is_sublist_equal([1],...
717b4287e212498ef85719fbf4d8e5437f16db48
15,338
def black_box_function(x, y): """Function with unknown internals we wish to maximize. This is just serving as an example, for all intents and purposes think of the internals of this function, i.e.: the process which generates its output values, as unknown. """ return -x ** 2 - (y - 1) ** 2 + 1
962c0dd5638ac71ee375f4bb1ba07b2bd241a6e8
15,339
def file_extension(path): """Lower case file extension.""" return audeer.file_extension(path).lower()
264f8afd0a2328d342693b2ec893706760b5c7ae
15,340
import math def motion(x, u, dt): """ motion model """ x[2] += u[1] * dt x[0] += u[0] * math.cos(x[2]) * dt x[1] += u[0] * math.sin(x[2]) * dt x[3] = u[0] x[4] = u[1] return x
e33adae2a6c5934dc7e0662570c42292eacbfd89
15,342
from typing import Union from typing import Callable def sweep( sweep: Union[dict, Callable], entity: str = None, project: str = None, ) -> str: """Initialize a hyperparameter sweep. To generate hyperparameter suggestions from the sweep and use them to train a model, call `wandb.agent` with the sweep...
50ba0d79a8fca5d5eba08b4e739845b797c0c839
15,343
def connection_end_point (id, node_uuid, nep_uuid, cep_uuid): """Retrieve NodeEdgePoint by ID :param topo_uuid: ID of Topology :type uuid: str :param node_uuid: ID of Node :type node_uuid: str :param nep_uuid: ID of NodeEdgePoint :type nep_uuid: str :param cep_uuid: ID of ConnectionEndP...
76dc345732d3209730b6022ba12cb2ca191e4a40
15,344
def remove_melt_from_perplex(perplex,melt_percent=-1): """ Extrapolate high temperature values to remove melt content using sub-solidus values. The assumption is that alpha and beta are constant and temperature-independent at high temperature.""" Tref = 273 Pref = 0 rho = perplex.rho.re...
6d2473d7147cdecdcd64cbb7e3beafd3b5df5c6a
15,345
def similarity_score(text_small, text_large, min_small = 10, min_large = 50): """ complexity: len(small) * len(large) @param text_small: the smaller text (in this case the text which's validity is being checked) @param text_large: the larger text (in this case the scientific stud...
8449b5273909382225f9de43d8fb936424d1a43e
15,346
def abline(a_coords, b_coords, ax=None, **kwargs): """Draw a line connecting a point `a_coords` with a point `b_coords`. Parameters ---------- a_coords : array-like, shape (2,) xy coordinates of the start of the line. b_coords : array-like, shape(2,) xy coordiantes of the end of th...
e262b689046ac5dd75152b8472a841c7a1e5db29
15,347
def get_extensions(): """ Returns supported extensions of the DCC :return: list(str) """ return ['.hip', '.hiplc', '.hipnc', '.hip*']
414391db5cd4f8989967100bae347e741ca4b46c
15,348
def calc_spatially_diffusion_factors( regions, fuel_disagg, real_values, low_congruence_crit, speed_con_max, p_outlier ): """ Calculate spatial diffusion values Arguments --------- regions : dict Regions fuel_disagg : dict Disa...
95361bb3f8ba5d3d47cd1a4ad065ec857e291f7b
15,350
def get_set(path): """Returns a matrix of data given the path to the CSV file. The heading row and NaN values are excluded.""" df = pd.read_csv(path, sep=';', encoding='latin') return df.dropna(subset=['PMID1', 'PMID2', 'Authorship'], how='any').values
aa701f440a9535d534826a50e8803fa0095bda25
15,351
def gaussian_target(img_shape, t, MAX_X=0.85, MIN_X=-0.85, MAX_Y=0.85, MIN_Y=-0.85, sigma2=10): """ Create a gaussian bivariate tensor for target or robot position. :param t: (th.Tensor) Target position (or robot position) """ X_range = img_shape[1] Y_range = img_shape[2] XY_range = np.arang...
47fbb46e2e46b1a4cc2cec3906e9c0dfb5282c0e
15,354
def XMLToPython (pattern): """Convert the given pattern to the format required for Python regular expressions. @param pattern: A Unicode string defining a pattern consistent with U{XML regular expressions<http://www.w3.org/TR/xmlschema-2/index.html#regexs>}. @return: A Unicode string specifyin...
14072879e11ea0425903be314fdba6fb8bfd2538
15,355
import fcntl import termios import struct def __termios(fd): """Try to discover terminal width with fcntl, struct and termios.""" #noinspection PyBroadException try: cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except Exception: retur...
78f3450d65a453cfd22c575bbddb77fcfbef1496
15,356