content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def n(request) -> int: """A test fixture enumerate values for `n`.""" return request.param
faec9637483670bec5d2bc687f2ee03d8c3839ea
3,100
def decode(ciphered_text): """ Decodes the ciphered text into human readable text. Returns a string. """ text = ciphered_text.replace(' ', '') # We remove all whitespaces return ''.join([decode_map[x] if decode_map.get(x) else x for x in text])
717e837a4750d4c281e2ca635e141f40cf1e30ee
3,101
from datetime import datetime def parse(s): """ Date parsing tool. Change the formats here cause a changement in the whole application. """ formats = ['%Y-%m-%dT%H:%M:%S.%fZ','%d/%m/%Y %H:%M:%S','%d/%m/%Y%H:%M:%S', '%d/%m/%Y','%H:%M:%S'] d = None for format in formats: try: ...
c665dd91a03a6d9876b8c36a46699b813c540cea
3,102
def openstack(request): """ Context processor necessary for OpenStack Dashboard functionality. The following variables are added to the request context: ``authorized_tenants`` A list of tenant objects which the current user has access to. ``regions`` A dictionary containing informati...
c914beb55a8609f2c363ac5e070f5531d7ce6abc
3,103
def get_align_mismatch_pairs(align, ref_genome_dict=None) -> list: """input a pysam AlignedSegment object Args: align (pysam.AlignedSeqment object): pysam.AlignedSeqment object ref_genome_dict (dict, optional): returned dict from load_reference_fasta_as_dict(). Defaults to None. Returns: ...
79886dbbdc764e115a72728060faaf155f3fea7a
3,104
def get_int(name, default=None): """ :type name: str :type default: int :rtype: int """ return int(get_parameter(name, default))
4a07f1286e54fd9e55b97868af1aa1bae595b795
3,105
def run_test(series: pd.Series, randtest_name, **kwargs) -> TestResult: """Run a statistical test on RNG output Parameters ---------- series : ``Series`` Output of the RNG being tested randtest_name : ``str`` Name of statistical test **kwargs Keyword arguments to pass to...
045ebe4756c24672cffdb3c43d6f0158809967d1
3,106
def radians(x): """ Convert degrees to radians """ if isinstance(x, UncertainFunction): mcpts = np.radians(x._mcpts) return UncertainFunction(mcpts) else: return np.radians(x)
49facfcfbeac91e9ac40b91ed8dc43b25ce157a6
3,107
def screen_poisson_objective(pp_image, hp_w,hp_b, data): """Objective function.""" return (stencil_residual(pp_image, hp_w,hp_b, data) ** 2).sum()
43a1ff6594cd493a0122e8c1305b84f25550fb59
3,108
def learn(request, artwork_genre=None): """ Returns an art genre. """ _genre = get_object_or_404(Genre, slug=artwork_genre) return render_to_response('t_learn.html', {'genre': _genre}, context_instance=RequestContext(request))
fe4e4477e7d2764ac41a58967ad1bc5296f10715
3,109
def plot_column(path: str, column: str, outpath: str = ""): """Plot a single column and save to file.""" df = to_df(path) col_df = df.set_index(["name", "datetime"])[column].unstack("name") ax = col_df.plot(grid=True) ax.set_xlabel("Time") ax.set_ylabel(LABEL_MAP[column]) if outpath: ...
58d5033a3bb86986e30582bf3fedf36842aeded9
3,110
def get_loader(): """Returns torch.utils.data.DataLoader for custom Pypipes dataset. """ data_loader = None return data_loader
0e3b0107e355169049dbdfa45cba9abdf479dcbe
3,111
def attention_decoder_cell_fn(decoder_rnn_cell, memories, attention_type, decoder_type, decoder_num_units, decoder_dropout, mode, batch_size, beam_width=1, decoder_initial_state=None, reuse=False): """Create an decoder cell with attention. It takes decoder...
ffd0199d7c0bf9f9bfb5d4a6e1d7eac4767e84d3
3,112
async def post_user_income(user: str, income: Income): """ This functions create a new income in the DB. It checks whether the user exists and returns a message in case no user exists. In the other case, creates a new document in DB with the users new Income. user: users uuid. income: Incom...
3d155d72fc1e00f45ca93b804d25d1051e7c47ab
3,113
from typing import Optional def bind_rng_to_host_device(rng: jnp.ndarray, axis_name: str, bind_to: Optional[str] = None) -> jnp.ndarray: """Binds a rng to the host/device we are on. Must be called from within a pmapped function. Note that when binding to ...
a7b50e6be3fd88f6a1341e0e43017baea305c31c
3,114
def get_child_ids(pid, models, myself=True, ids: set = None) -> set: """ 获取models模型的子id集合 :param pid: models模型类ID :param models: models模型对象 :param myself: 是否包含pid :param ids: 所有ID集合(默认为None) :return: ids(所有ID集合) """ if ids is None: ids = set() queryset = models.objects.fi...
b5d9b10497eada8b3cafc32f4260ace091bbc0bf
3,115
def get_tenant_id(khoros_object, community_details=None): """This function retrieves the tenant ID of the environment. .. versionadded:: 2.1.0 :param khoros_object: The core :py:class:`khoros.Khoros` object :type khoros_object: class[khoros.Khoros] :param community_details: Dictionary containing c...
7fe29990d7b6b99e4b677edfdb1cd32ca785654a
3,116
import tokenize def obfuscatable_variable(tokens, index): """ Given a list of *tokens* and an *index* (representing the current position), returns the token string if it is a variable name that can be safely obfuscated. Returns '__skipline__' if the rest of the tokens on this line should be skipp...
487bfd926b77260980875496991a7bcc2bc8df3f
3,117
import csv def concat_data(labelsfile, notes_file): """ INPUTS: labelsfile: sorted by hadm id, contains one label per line notes_file: sorted by hadm id, contains one note per line """ with open(labelsfile, 'r') as lf: print("CONCATENATING") with open(notes_file, 'r') a...
b6403c4ec7797cd7d08e01e7b9a9365708bdee6f
3,118
def replace_text_comment(comments, new_text): """Replace "# text = " comment (if any) with one using new_text instead.""" new_text = new_text.replace('\n', ' ') # newlines cannot be represented new_text = new_text.strip(' ') new_comments, replaced = [], False for comment in comments: if c...
4b1284966eb02ca2a6fd80f8f639adcb4f1fde6c
3,119
def init_show_booking_loader(response, item=None): """ init ShowingBookingLoader with optional ShowingBooking item """ loader = ShowingBookingLoader(response=response) if item: loader.add_value(None, item) return loader
2d9c790e487ab7009c70e83a8ecb5d5e93732ff7
3,120
def get_dpifac(): """get user dpi, source: node_wrangler.py""" prefs = bpy.context.preferences.system return prefs.dpi * prefs.pixel_size / 72
dc598635eb8fdf0b3fe8b6acc3f497a65a18f099
3,121
from typing import List def seq_row( repeats: int = 1, trigger: str = Trigger.IMMEDIATE, position: int = 0, half_duration: int = MIN_PULSE, live: int = 0, dead: int = 0, ) -> List: """Create a 50% duty cycle pulse with phase1 having given live/dead values""" row = [ repeats, ...
5d331f1f67f5799165f3966249e199ca43e0ec27
3,122
def call_nelder_mead_method( f, verts, x_tolerance=1e-6, y_tolerance=1e-6, computational_budget=1000, f_difference=10, calls=0, terminate_criterion=terminate_criterion_x, alpha=1, gamma=2, rho=0.5, sigma=0.5, values=[], ): """Return an approximation of a local op...
02e16b477a977239a8dc256150cdbc983235f81c
3,123
def get_auth_claims_from_request(request): """Authenticates the request and returns claims about its authorizer. Oppia specifically expects the request to have a Subject Identifier for the user (Claim Name: 'sub'), and an optional custom claim for super-admin users (Claim Name: 'role'). Args: ...
1e2aaf4f26b11defea65796331f160fd22267cf2
3,124
import io def decrypt(**kwargs): """ Returns a CryptoResult containing decrypted bytes. This function requires that 'data' is in the format generated by the encrypt functionality in this SDK as well as other OCI SDKs that support client side encryption. Note this function cannot decrypt data...
ba27e39abd0c72db5acd2530b7a4128b3f073dc6
3,125
from typing import Union from typing import Tuple from typing import Dict from typing import Any import io def format_result(result: Union[Pose, PackedPose]) -> Tuple[str, Dict[Any, Any]]: """ :param: result: Pose or PackedPose object. :return: tuple of (pdb_string, metadata) Given a `Pose` or `Packed...
15b3c6ce32a3a5ab860d045ba8679e0299f122f6
3,126
def str_array( listString): """ Becase the way tha Python prints an array is different from CPLEX, this function goes the proper CPLEX writing of Arrays :param listString: A list of values :type listString: List[] :returns: The String printing of the array, in CPLEX format :rtype: String """ ...
46737bb05f310387d69be6516ebd90afd3d91b08
3,127
def read_gene_annos(phenoFile): """Read in gene-based metadata from an HDF5 file Args: phenoFile (str): filename for the relevant HDF5 file Returns: dictionary with feature annotations """ fpheno = h5py.File(phenoFile,'r') # Feature annotations: geneAnn = {} for key...
86e1b26a5600e1d52a3beb127ef8e7c3ac41721a
3,128
from typing import Optional import binascii def hex_xformat_decode(s: str) -> Optional[bytes]: """ Reverse :func:`hex_xformat_encode`. The parameter is a hex-encoded BLOB like .. code-block:: none "X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'" Original purpose and notes: - SPECIAL ...
8f868d4bbd5b6843632f9d3420fe239f688ffe15
3,129
def threshold(data, direction): """ Find a suitable threshold value which maximizes explained variance of the data projected onto direction. NOTE: the chosen hyperplane would be described mathematically as $ x \dot direction = threshold $. """ projected_data = np.inner(data, direction) sorted_x ...
7fdab7f87c3c2e6d937da146ce5a27074ea92f52
3,130
def StrType_any(*x): """ Ignores all parameters to return a StrType """ return StrType()
d1faac14a91cd6149811a553113b25f34d5d4a54
3,131
import requests import os def _download(url, dest, timeout=30): """Simple HTTP/HTTPS downloader.""" # Optional import: requests is not needed for local big data setup. dest = os.path.abspath(dest) with requests.get(url, stream=True, timeout=timeout) as r: with open(dest, 'w+b') as data: ...
7fe29752866707e3bbcb4f5e5b8a97507a7b71f8
3,132
def height(tree): """Return the height of tree.""" if tree.is_empty(): return 0 else: return 1+ max(height(tree.left_child()),\ height(tree.right_child()))
a469216fc13ed99acfb1bab8db7e031acc759f90
3,133
def applyTelluric(model, tell_alpha=1.0, airmass=1.5, pwv=0.5): """ Apply the telluric model on the science model. Parameters ---------- model : model object BT Settl model alpha : float telluric scaling factor (the power on the flux) Returns ------- model : model object BT Settl model times...
7eaf7cafe1f8b5f4c273858f289d2c1c3865680b
3,134
def max_power_rule(mod, g, tmp): """ **Constraint Name**: DAC_Max_Power_Constraint **Enforced Over**: DAC_OPR_TMPS Power consumption cannot exceed capacity. """ return ( mod.DAC_Consume_Power_MW[g, tmp] <= mod.Capacity_MW[g, mod.period[tmp]] * mod.Availability_Derate[g, tmp] ...
2c1845253524a8383f2256a7d67a8231c2a69485
3,135
import os async def list_subs(request: Request): """ List all subscription objects """ # Check for master token if not request.headers.get("Master") == os.environ.get("MASTER_TOKEN"): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid aut...
226a7de95b6557d6ff006401190816ad2a5d0222
3,136
def check_archs( copied_libs, # type: Mapping[Text, Mapping[Text, Text]] require_archs=(), # type: Union[Text, Iterable[Text]] stop_fast=False, # type: bool ): # type: (...) -> Set[Union[Tuple[Text, FrozenSet[Text]], Tuple[Text, Text, FrozenSet[Text]]]] # noqa: E501 """Check compatibility of ar...
d500e0b89ca3edd4e76630a628d9e4d970fadbf1
3,137
def create_data_table(headers, columns, match_tol=20) -> pd.DataFrame: """Based on headers and column data, create the data table.""" # Store the bottom y values of all of the row headers header_tops = np.array([h.top for h in headers]) # Set up the grid: nrows by ncols nrows = len(headers) nc...
56b1cb21afa7813138d03b56849b594e18664348
3,138
def interp2d_vis(model, model_lsts, model_freqs, data_lsts, data_freqs, flags=None, kind='cubic', flag_extrapolate=True, medfilt_flagged=True, medfilt_window=(3, 7), fill_value=None): """ Interpolate complex visibility model onto the time & frequency basis of a data visibil...
6ac4fad738691f470e36252fc7544e857c8fdca0
3,139
def eps_divide(n, d, eps=K.epsilon()): """ perform division using eps """ return (n + eps) / (d + eps)
2457e5fc4458521b4098cfb144b7ff07e163ba9c
3,140
import requests def get_mc_uuid(username): """Gets the Minecraft UUID for a username""" url = f"https://api.mojang.com/users/profiles/minecraft/{username}" res = requests.get(url) if res.status_code == 204: raise ValueError("Users must have a valid MC username") else: return res.js...
fceeb1d9eb096cd3e29f74d389c7c851422ec022
3,141
import os import netrc import trace def _resolve_credentials(fqdn, login): """Look up special forms of credential references.""" result = login if "$" in result: result = os.path.expandvars(result) if result.startswith("netrc:"): result = result.split(':', 1)[1] if result: ...
0b2a31d23f2937d41a8c81e02b7a64cf013e5580
3,142
def api(default=None, api=None, **kwargs): """Returns the api instance in which this API function is being ran""" return api or default
3d636408914e2888f4dc512aff3f729512849ddf
3,143
def parse_json(data): """Parses the PupleAir JSON file, returning a Sensors protobuf.""" channel_a = [] channel_b = {} for result in data["results"]: if "ParentID" in result: channel_b[result["ParentID"]] = result else: channel_a.append(result) sensors = list(...
11ded094b71d6557cc7c1c7ed489cdcbfe881e0b
3,144
import logging import traceback def asynchronize_tornado_handler(handler_class): """ A helper function to turn a blocking handler into an async call :param handler_class: a tornado RequestHandler which should be made asynchronus :return: a class which does the same work on a threadpool """ cl...
0e7d3b46b199cdf1aa1a31a19ed3d54f0abbce16
3,145
def convert_single_example(ex_index, example: InputExample, tokenizer, label_map, dict_builder=None): """Converts a single `InputExample` into a single `InputFeatures`.""" # label_map = {"B": 0, "M": 1, "E": 2, "S": 3} # tokens_raw = tokenizer.tokenize(example.text) tokens_ra...
3dca77aa191f821c9785c8431c4637e47582a588
3,146
def create_scenariolog(sdata, path, recording, logfilepath): """ シナリオのプレイデータを記録したXMLファイルを作成する。 """ element = cw.data.make_element("ScenarioLog") # Property e_prop = cw.data.make_element("Property") element.append(e_prop) e = cw.data.make_element("Name", sdata.name) e_prop.append(e) ...
d55bee540361496d5a9d456be7a99d88b2f0dcf6
3,147
async def converter_self_interaction_target(client, interaction_event): """ Internal converter for returning the received interaction event's target. Applicable for context application commands. This function is a coroutine. Parameters ---------- client : ``Client`` The cli...
66975897b9f8a7d0b224f80d1827af3ea07eb51d
3,148
from typing import List def publication_pages(publication_index_page) -> List[PublicationPage]: """Fixture providing 10 PublicationPage objects attached to publication_index_page""" rv = [] for _ in range(0, 10): p = _create_publication_page( f"Test Publication Page {_}", publication_i...
5d9b75bcbdc5c9485cc83ddc2befeb946f447227
3,149
from typing import List def rp_completion( rp2_metnet, sink, rp2paths_compounds, rp2paths_pathways, cache: rrCache = None, upper_flux_bound: float = default_upper_flux_bound, lower_flux_bound: float = default_lower_flux_bound, max_subpaths_filter: int = default_max_subpaths_filter, ...
ac7539d1d8f0f9388c9d6bef570362d62ec90414
3,150
import torch def wrap(func, *args, unsqueeze=False): """ Wrap a torch function so it can be called with NumPy arrays. Input and return types are seamlessly converted. """ args = list(args) for i, arg in enumerate(args): if type(arg) == np.ndarray: args[i] = torch.from_nump...
5a5491e2b911235d7bf858b19d0d32a9e8da20e6
3,151
def STOCHF(data, fastk_period=5, fastd_period=3, fastd_ma_type=0): """ Stochastic %F :param pd.DataFrame data: pandas DataFrame with open, high, low, close data :param int fastk_period: period used for K fast indicator calculation :param int fastd_period: period used for D fast indicator calculatio...
3412a6832f54b2dfbaff7eb25de0f6644d914934
3,152
def playerid_reverse_lookup(player_ids, key_type=None): """Retrieve a table of player information given a list of player ids :param player_ids: list of player ids :type player_ids: list :param key_type: name of the key type being looked up (one of "mlbam", "retro", "bbref", or "fangraphs") :type ke...
e5bbe46567d1c8e517020d9cb9f551249ea8f515
3,153
def get_delta_z(z, rest_ghz, ghz=None): """ Take a measured GHz value, and calculates the restframe GHz value based on the given z of the matched galaxy :param z: :param ghz: :return: """ # First step is to convert to nm rom rest frame GHz set_zs = [] for key, values in transitions....
acb0069c56fb34aeaba302368131400f3c35d643
3,154
def hist_orientation(qval, dt): """ provided with quats, and time spent* in the direction defined by quat produces grouped by ra, dec and roll quaternions and corresponding time, spent in quats params: qval a set of quats stored in scipy.spatial.transfrom.Rotation class params: dt corresponding to...
bbdecc58a9a3dc248d68b73018cd5f1d803ddbfd
3,155
def tcpip(port=5555, debug=False): """ 切换到tcpip模式(网络模式) :param port: 端口(默认值5555) :param debug: 调试开关(默认关闭) :return: 不涉及 """ return adb_core.execute(f'tcpip {port}', debug=debug)
3794ceeff32c20a8f4a525b0083866a781973ec8
3,156
def proclamadelcaucacom_story(soup): """ Function to pull the information we want from Proclamadelcauca.com stories :param soup: BeautifulSoup object, ready to parse """ hold_dict = {} #text try: article_body = soup.find('div', attrs={"class": "single-entradaContent"}) mainte...
e8bcf0faaa7731b71e7b9db33e454b422b3285bc
3,157
def asarray_fft(x, inverse): """Recursive implementation of the 1D Cooley-Tukey FFT using np asarray to prevent copying. Parameters: x (array): the discrete amplitudes to transform. inverse (bool): perform the inverse fft if true. Returns: x (array): the amplitudes of the origin...
87f86f8529f5c54535d9a188c454f762f96a7a58
3,158
import os def get_long_description(): """ Returns the long description of Wapyce. :return: The long description of Wapyce. :rtype: str """ with open( os.path.join(BASE_DIRECTORY, 'README.md'), 'r', encoding='utf-8' ) as readme_file: return readme_file.read...
f9dd5ba3cc94907b8b38a3bfacfd6c8e551b3c98
3,159
import jinja2 def wrap_locale_context(func): """Wraps the func with the current locale.""" @jinja2.contextfilter def _locale_filter(ctx, value, *args, **kwargs): doc = ctx['doc'] if not kwargs.get('locale', None): kwargs['locale'] = str(doc.locale) return func(value, *...
a2f720e9ed38eb2bf0f546ab392f295d969f7ab7
3,160
from numpy import loadtxt from scipy.interpolate import UnivariateSpline def mu_Xe(keV=12): """Returns inverse 1/e penetration depth [mm-1 atm-1] of Xe given the x-ray energy in keV. The transmission through a 3-mm thick slab of Xe at 6.17 atm (76 psi) was calculated every 100 eV over an energy range ...
5f106871e7517ef910739b74a13d2139e03ed480
3,161
import hashlib def file_md5(input_file): """ :param input_file: Path to input file. :type input_file: str :return: Returns the encoded data in the inputted file in hexadecimal format. """ with open(input_file, 'rb') as f: data = f.read() return hashlib.md5(data).hexdigest()
4a7ea12e3b5e0429787eb65e651852e49b40ecf7
3,162
def signup(request): """Register a new user. This view has multiple behaviours based on the request composition. When some user is already signed in, the response ask the user to first sign out. When the request has no data about the new user, then the response carries the registration form. When t...
f1534df25459396485ed83d96fd8e488d39b0925
3,163
from typing import Dict def message_args() -> Dict[str, str]: """A formatted message.""" return {"subject": "Test message", "message": "This is a test message"}
4d25d5c9f54aa0997f2e619f90eb6632717cf0d3
3,164
def to_drive_type(value): """Convert value to DriveType enum.""" if isinstance(value, DriveType): return value.value sanitized = str(value).upper().strip().replace(" ", "_") try: return DriveType[sanitized].value except KeyError as err: raise ValueError(f"Unknown drive type:...
10183ac3ad15c2e01d9abf262f097dc6b366e7ab
3,165
def upload_authorized_key(host, port, filepath): """UPLOAD (key) upload_authorized_key""" params = {'method': 'upload_authorized_key'} files = [('key', filepath, file_get_contents(filepath))] return _check(https.client.https_post(host, port, '/', params, files=files))
68ada5d834ff77c4ee1b09815a6b094c30a42c1b
3,166
def thermalize_cutoff(localEnergies, smoothing_window, tol): """Return position where system is thermalized according to some tolerance tol, based on the derivative of the smoothed local energies """ mean = np.mean(localEnergies) smoothLocalEnergies = smoothing(localEnergies, smoothing_window) ...
d72904596ab88298232e9c2ed0fac151e3e66a71
3,167
def annualize_metric(metric: float, holding_periods: int = 1) -> float: """ Annualize metric of arbitrary periodicity :param metric: Metric to analyze :param holding_periods: :return: Annualized metric """ days_per_year = 365 trans_ratio = days_per_year / holding_periods return (1...
0c84816f29255d49e0f2420b17abba66e2387c99
3,168
import argparse import sys def parse_args(): """Command line arguments parser.""" app = argparse.ArgumentParser() app.add_argument("in_chain", help="Input chain file or stdin") app.add_argument("reference_2bit", help="Reference 2bit file") app.add_argument("query_2bit", help="Query 2bit file") ...
a0ef04f4769e247dea8816b70807f10c7efd5571
3,169
def get_latest_tag(): """ Find the value of the latest tag for the Adafruit CircuitPython library bundle. :return: The most recent tag value for the project. """ global LATEST_BUNDLE_VERSION # pylint: disable=global-statement if LATEST_BUNDLE_VERSION == "": LATEST_BUNDLE_VERSION = g...
2195d2cde7e2ff67a110b1a1af2aa8cebad52294
3,170
def detail(request, name): """ List all details about a single service. """ service = CRITsService.objects(name=name, status__ne="unavailable").first() if not service: error = 'Service "%s" is unavailable. Please review error logs.' % name return ...
bca02ed15926222899db625ba908075ca5c9a13c
3,171
def read_gold_conll2003(gold_file): """ Reads in the gold annotation from a file in CoNLL 2003 format. Returns: - gold: a String list containing one sequence tag per token. E.g. [B-Kochschritt, L-Kochschritt, U-Zutat, O] - lines: a list list containing the original line spli...
1e11513c85428d20e83d54cc2fa2d42ddd903341
3,172
import functools def translate_nova_exception(method): """Transforms a cinder exception but keeps its traceback intact.""" @functools.wraps(method) def wrapper(self, ctx, *args, **kwargs): try: res = method(self, ctx, *args, **kwargs) except (nova_exceptions.ConnectionRefused, ...
186b7f944b03073c758b4af5f4ccfcaa80e8f5e8
3,173
def _update_form(form): """ """ if not form.text(): return form.setStyleSheet(error_css) return form.setStyleSheet(success_css)
94e241a98aa6c8305965d4149f4d60e28843aea7
3,174
import torch from torch_adapter import TorchAdapter from openvino.inference_engine import IEPlugin from openvino_adapter import OpenvinoAdapter from torch_adapter import TorchAdapter import importlib def create_adapter(openvino, cpu_only, force_torch, use_myriad): """Create the best adapter based on constraints p...
4fd0fc51c7758d32a1eac4d86d1b5dc6b90d20b7
3,175
def _make_ecg(inst, start, stop, reject_by_annotation=False, verbose=None): """Create ECG signal from cross channel average.""" if not any(c in inst for c in ['mag', 'grad']): raise ValueError('Unable to generate artificial ECG channel') for ch in ['mag', 'grad']: if ch in inst: ...
27d1ef6da9c9d491de4b9806c85528f1226b2c3d
3,176
def lorentzian(freq, freq0, area, hwhm, phase, offset, drift): """ Lorentzian line-shape function Parameters ---------- freq : float or float array The frequencies for which the function is evaluated freq0 : float The center frequency of the function area : float hwhm: float ...
2f9b2ede75773c2100941e16fd14210b1a85a453
3,177
def findTilt(root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 return findTilt_helper(root)[1]
1338a704f754678f88dedaf5a968aa3bfe4ff17f
3,178
def generate_report(): """ Get pylint analization report and write it to file """ files = get_files_to_check() dir_path = create_report_dir() file_path = create_report_file(dir_path) config_opts = get_config_opts() pylint_opts = '--load-plugins pylint_flask' + config_opts pylint_stdo...
655345a128847285712f683274637201ee264010
3,179
import os import pickle def read_files(year,month,day,station): """ """ doy,cdoy,cyyyy,cyy = ymd2doy(year,month,day) # i have a function for this .... rinexfile = station + cdoy + '0.' + cyy + 'o' navfilename = 'auto' + cdoy + '0.' + cyy + 'n' if os.path.isfile(rinexfile): pr...
4a3bb0344607fce34037cd4a50ac273fde166027
3,180
def make_trampoline(func_name): """ Create a main function that calls another function """ mod = ir.Module('main') main = ir.Procedure('main') mod.add_function(main) entry = ir.Block('entry') main.add_block(entry) main.entry = entry entry.add_instruction(ir.ProcedureCall(func_name, [])) ...
1dcaf61cbadde4fdd8e94958658ce8b1b69612f1
3,181
import os import sys def main(global_config, **settings): """Return a Pyramid WSGI application.""" if not settings.get('sqlalchemy.url'): try: settings['sqlalchemy.url'] = os.environ['BLOG2017_DB'] except KeyError: print('Required BLOG2017_DB not set in global os enviro...
19e2bd9e097fc812c980626183a4ea98e88697d0
3,182
def model_fields(dbo, baseuri=None): """Extract known fields from a BQ object, while removing any known from C{excluded_fields} @rtype: dict @return fields to be rendered in XML """ attrs = {} try: dbo_fields = dbo.xmlfields except AttributeError: # This occurs when the ...
59a07057dccb116cc4753a4973a3128ccc79c558
3,183
def get_bsj(seq, bsj): """Return transformed sequence of given BSJ""" return seq[bsj:] + seq[:bsj]
d1320e5e3257ae22ca982ae4dcafbd4c6def9777
3,184
from typing import Dict import warnings import math def sample(problem: Dict, N: int, calc_second_order: bool = True, skip_values: int = 0): """Generates model inputs using Saltelli's extension of the Sobol' sequence. Returns a NumPy matrix containing the model inputs using Saltelli's sampling ...
a3a356fd037b879c71cb6dc2e4751350857302e8
3,185
def standardize(table, option): """ standardize Z = (X - mean) / (standard deviation) """ if option == 'table': mean = np.mean(table) std = np.std(table) t = [] for row in table: t_row = [] if option != 'table': mean = np.mean(row) std ...
337ec0d22340ca74e54236e1cb39829eab8ad89b
3,186
def raw_input_nonblock(): """ return result of raw_input if has keyboard input, otherwise return None """ if _IS_OS_WIN32: return _raw_input_nonblock_win32() else: raise NotImplementedError('Unsupported os.')
90cc9febcaa4866334b69b19809565795a07de49
3,187
def get_batch_hard(draw_batch_size,hard_batchs_size,semihard_batchs_size,easy_batchs_size,norm_batchs_size,network,dataset,nb_classes, margin): """ Create batch of APN "hard" triplets Arguments: draw_batch_size -- integer : number of initial randomly taken samples hard_batchs_size -- interger : sel...
da6dc7f69354b0b74b59717140c6c46826925050
3,188
import math def sine( start, end, freq, amp: Numeric = 1, n_periods: Numeric = 1 ) -> TimeSerie: """ Generate a sine TimeSerie. """ index = pd.date_range(start=start, end=end, freq=freq) return TimeSerie( index=index, y_values=np.sin( np.linspace(0, 2 * math.pi * n_...
df4254f9fafcb61f0bcf492edf1847d89f4debb0
3,189
def get_from_address(sending_profile, template_from_address): """Get campaign from address.""" # Get template display name if "<" in template_from_address: template_display = template_from_address.split("<")[0].strip() else: template_display = None # Get template sender template...
8617d2b793b76456cb7d1a17168f27fd1d548e6d
3,190
import ctypes def is_dwm_compositing_enabled(): """Is Desktop Window Manager compositing (Aero) enabled. """ enabled = ctypes.c_bool() try: DwmIsCompositionEnabled = ctypes.windll.dwmapi.DwmIsCompositionEnabled except (AttributeError, WindowsError): # dwmapi or DwmIsCompositionEna...
9b31b3ef62d626008d2b6c6ef59446be79da89f6
3,191
def fgsm(x, y_true, y_hat, epsilon=0.075): """Calculates the fast gradient sign method adversarial attack Following the FGSM algorithm, determines the gradient of the cost function wrt the input, then perturbs all the input in the direction that will cause the greatest error, with small magnitude. ...
a71d2042ea1f5efa0a3f6409836da52bf323aa5c
3,192
def tour_delete(request,id): """ delete tour depending on id """ success_message, error_message = None, None form = TourForm() tour = get_object_or_404(Tour, id=id) tours = Tour.objects.all() if request.method=="POST": tour.delete() success_message = "deleted tour" ...
c42e355734444d858555ad627f202f73161cbedf
3,193
import random def d3(): """Simulate the roll of a 3 sided die""" return random.randint(1, 3)
c2eac44bb36b7e35c66894bce3467f568a735ca1
3,194
import os def split_file_name(file_name): """ splits the name from the file name. :param file_name: :return: """ return os.path.splitext(file_name)[0]
f13609671ca6d9c562cef7b371147bd89d8815c6
3,195
import subprocess def run_as_root(command, printable=True, silent_start=False): """ General purpose wrapper for running a subprocess as root user """ sudo_command = "sudo {}".format(command) return run_command(sudo_command, error_msg="", stdout=subproc...
b5abedfe6ffe4d6e5182f1cd69b8132b29755d97
3,196
def _search_qr(model, identifier, session): """Search the database using a Query/Retrieve *Identifier* query. Parameters ---------- model : pydicom.uid.UID Either *Patient Root Query Retrieve Information Model* or *Study Root Query Retrieve Information Model* for C-FIND, C-GET or C-MOVE...
29fe8831b1e44a381202b48212ff7c40c4c8d7fd
3,197
import json def retrieve_zoom_metadata( stage=None, zoom_api=None, file_key=None, log=None, **attributes ): """General function to retrieve metadata from various Zoom endpoints.""" if "id" in attributes: api_response = zoom_api(id=attributes["id"]) elif "meeting_id" in attributes: api_...
68c92e00693cf1deb4153bd71cd15046642a7c7d
3,198
def find_max_value(binary_tree): """This function takes a binary tree and returns the largest value of all the nodes in that tree with O(N) space and O(1) time using breadth first traversal while keeping track of the largest value thus far in the traversal """ root_node = [] rootnode.push(binar...
a797ea1598195cfcfe1abf00d73562c59617ad9b
3,199