content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def generate_fc2_filedata(filepath_tests): """Generate a `SinglefileData` instance with fc2.hdf5 file.""" def _generate_fc2_filedata(structure_id: str = "NaCl-64"): if structure_id == "NaCl-64": filepath = os.path.join( filepath_tests, "parsers", ...
414604713246399616b8ca139aade56f810b14a0
3,622,600
def get_supported_languages(): """Return the list of supported language. """ if getattr(PARSER, 'filename', None): return list(sorted(lang for lang in PARSER.sections())) return list(sorted(DEFAULT.keys()))
9e270e896da6a60bf3a08013a331d889a46e981a
3,622,601
def createCFileBuilders(env): """This is a utility function that creates the CFile/CXXFile Builders in an Environment if they are not there already. If they are there already, we return the existing ones. This is a separate function because soooo many Tools use this functionality. The ret...
07c6589bc4f49538c4600806a7b80794e418b034
3,622,602
def get_requirements(integration: Integration, packages: set[str]) -> set[str]: """Return all (recursively) requirements for an integration.""" ensure_cache() all_requirements = set() to_check = deque(packages) while to_check: package = to_check.popleft() if package in all_requir...
1a582a63b09748470337a84e350d1788c909e8a9
3,622,603
def timestr_mod24(timestr): """ Given a GTFS HH:MM:SS time string, return a timestring in the same format but with the hours taken modulo 24. """ try: hours, mins, seconds = [int(x) for x in timestr.split(":")] hours %= 24 result = "{:02d}:{:02d}:{:02d}".format(hours, mins, s...
ea049f4b31861de56b04dba6f4356ed46930af44
3,622,604
def set_ext_api(file_path): """Smart Function to set Extension.""" ext = file_path.split('.')[-1] if ext == 'plist': return 'plist' elif ext == 'xml': return 'xml' elif ext in ['sqlitedb', 'db', 'sqlite']: return 'db' elif ext == 'm': return 'm' else: ...
816a7f33c659ff3e0089502530fb916a40982d79
3,622,605
from pathlib import Path def gen_ipc_path(base_mac, pipe) -> Path: """ Builds a path that should represent some RX pipe """ base_path = Path("/tmp/ripple_ipc/rx") base_path.mkdir(exist_ok=True) return _gen_ipc_path(base_path, base_mac, pipe)
93d86a172688f80a49004f62c1f74f8427b3bf3f
3,622,606
def _get_cert_dates(pem_cert): """Returns the dates in the cert""" cert = x509.load_pem_x509_certificate(pem_cert.encode(), default_backend()) logger.debug( "Certificate with serial '%s', has not before: '%s' and not after: '%s' (UTC)", cert.serial_number, cert.not_valid_before, ...
524b618e848fb7124b02f0f3c9119bd460eb676b
3,622,607
def animations(): """animations() -> tuple Returns a list of animatable things the user wants to work on. If this is a command being executed from a menu item in a curve editor, a list of the names of all selected curves is returned. If this list is empty a "No curves selected" error is produced. If this is a comm...
a30923e499824739c8a0429bdb6a8f10f42928ba
3,622,608
import os import requests from datetime import datetime import asyncio def updateByManifest(path, dryRun=False): """ Attempts to update only the recently updated datafiles by using a manifest file. Returns False if updating failed and a full update should be performed; returns True if updating was a s...
ec175f464cb4051d35cf6bb4dc6e78ee390fdc29
3,622,609
import html def toggle_language(n_clicks, target_lang): """ Toggles the language between English and Chinese. Args: n_clicks (int): Number of times the button has been clicked. target_lang (str): The target language to change to (children attribute of #toggle-language element) """ ...
a54d31b4eec8d1570c2e7de15e2f87b465c8ef50
3,622,610
def create_handler(event, context): """ Called when CloudFormation custom resource sends the create event """ return create_processing_job(event)
65b129095915e2f4653101e0f83cb15a3731add2
3,622,611
def finish_multiplier(): """Starts at 1.5x in the middle of the grid, increases to linearly to 2x for 1st and last place.""" multiplier_floor = 1.15 current_position = ir.car_position() grid_size = ir.field_size() mid_positions = grid_size/2 if grid_size % 2 == 1: mid_positions = [mid_p...
47878f5d61fe8111a0ae04e929997b86dc424b78
3,622,612
def combined_roidb(split, task, num_im, num_val_im): """ Combine multiple roidbs """ imdb = get_vg_imdb(split, task, num_im, num_val_im) print('Loaded dataset `{:s}` for training'.format(imdb.name)) roidb = get_training_roidb(imdb) return imdb, roidb
2ae38d4fd74637862581d68464b68095e1c28756
3,622,613
from typing import Optional def gen_payment_op( dest: xdr_type.AccountID, src: Optional[xdr_type.AccountID] = None, amount: int = 10 ) -> xdr_type.Operation: """Generate a payment operation. """ body = xdr_pack.nullclass() body.type = xdr_const.PAYMENT body.paymentOp = xdr_type.PaymentOp( ...
369d5071b70af828f2754142cc13926cb0835f5a
3,622,614
import os def _get_copyrights_from_files(license_files): """ Get all of the copyright notifications from a list of files. """ copyright_notices = [] for license_file in license_files: # If the license_file is a folder, skip it if not os.path.isfile(license_file): contin...
dd1b0edb7478e663ce51f93560cd58cb4f2c26f2
3,622,615
def get_affine_transform(center, scale, rot, output_size, shift=np.array([0, 0], dtype=np.float32), inv=False): """ adapted from CenterNet: https://github.com/xingyizhou/CenterNet/blob/master/src/lib/utils/image.py center: ndarray: (cx, cy) scale: (w, h) rot: angle in deg output_size: int or (w,...
62f74e368b4f3943044e46afae2b41347b13ddf2
3,622,616
def hostip(req=None, black_list=None, pref_list=None, logger=None): """ Look up the ip number for a given requested interface name. If interface is not given, do some magic. """ # we only determine hostip once global _hostip if _hostip: return _hostip # List of interfaces that ...
096510a4229c88286b8ed4266d2057f820ea3c7d
3,622,617
def test_sgf(filename): """Parses a sgf file to a game dict. Args: filename: str, path of the sgf file Returns: None if one of these to Errors occurs: * sgf contains no moves, affects about 1% of files in KGS dataset * move in the sgf breaks the minigo ko rule, affects about...
a88e1b9ac3d553b5aa155bd2023c87798c433497
3,622,618
def dtex_cii_1(tcii, tau_cii, tbg): """ """ return np.power(tex_cii(tcii, tau_cii, tbg), 2.) * 1./(1 + tstar*(1. - np.exp(-tau_cii))/(tcii + J(tbg)))
67770325bf78dcf42e209b65636aabfe1199e14d
3,622,619
from typing import Optional import re def get_pragma_spec(source: str) -> Optional[NpmSpec]: """ Extracts pragma information from Vyper source code. Args: source: Vyper source code Returns: NpmSpec object or None, if no valid pragma is found """ pragma_match = next(re.finditer(r"(?:\n|...
8183ae85682db16157d637979ffe5958d4927bf7
3,622,620
import os def git_log(start, end, workingdir=None): """Run a ``git log`` command that will provide a nicely formatted list of commits between ``start`` and ``end`` times. If ``workingdir`` is provided, change to that directory before running the command.""" if workingdir: olddir = os.getcwd() ...
445fd241ceeff80224a0a7fe6491c84264a7340e
3,622,621
import pytz from datetime import datetime def parse_time(input_time): """Parse an Atom time stamp.""" parsed = None try: parsed = timezone.make_aware(timezone.datetime(*input_time[:-3]), timezone.utc) except (pytz.NonExistentTimeError, pytz.AmbiguousTimeErr...
865c525b4d3811d140bb497929165463d31f25f4
3,622,622
def add_solution( respy_obj, periods_rewards_systematic, states_number_period, mapping_state_idx, periods_emax, states_all, *args, ): """Add solution to class instance.""" respy_obj.unlock() respy_obj.set_attr("periods_rewards_systematic", periods_rewards_systematic) respy_ob...
ea0660fe5956bf5e8f6706a12e766a0cc5e2f2db
3,622,623
def sinusoid(t,A,P,phi,offset): """ A simple sinusoid model """ return A*np.sin(2.*np.pi*t/P + phi)+offset
0a4eb494a623dc8f6ab28ad1d5a025ccbb2157af
3,622,624
def sanitize_bucket_and_host(bucket): # type: (str) -> Tuple[str, str] """ if bucket is in following format : 'xxx.amazonaws.com/bucket_name', Returns a 2-values tuple ('bucket_name', 'xxx.amazonaws.com') """ # first case: we got a "<host>/<bucket_name>" input if "/" in bucket: host,...
706bedb456474fe75e4553c793470908702409e5
3,622,625
from unittest.mock import call def move_roles_to_base_role_config_group(resource_root, service_name, role_names, cluster_name="default"): """ Moves roles to the base role config group. The roles can be moved from any role config group belonging to the same service. The role type of the roles may vary. E...
f2c3951946a9b8d32874532ef8e8e3daab0eddbc
3,622,626
def stamp_allowing_unusual_version_table( config: Config, revision: str, sql: bool = False, tag: str = None, version_table: str = DEFAULT_ALEMBIC_VERSION_TABLE) -> None: """ Stamps the Alembic version table with the given revision; don't run any migrations. This ...
c534748b70875dbf9c414fce2f422e82cf0d2405
3,622,627
def when(*contexts: Context): """Returns a function wrapper. A function decorated with `when` will exit early if any supplied context in `contexts` is active. The first supplied context to block will be reported as a message. Consider supplying permanent conditions first. For example, to block a function when a m...
c232ccb63f41793a0cd68b187f1e41e7feb9532c
3,622,628
import re from typing import Union def read(filename: PathLike, **kwargs) -> Union[MuData, AnnData]: """ Read MuData object from HDF5 file or AnnData object (a single modality) inside it This function is designed to enhance I/O ease of use. It recognises the following formats: - FILE.h5mu ...
0ff959f1f016573fee976b11b1cd74bb752f0f80
3,622,629
from typing import Iterator from typing import Tuple from typing import Sequence from typing import Dict from typing import List def group_nodes(graph: ModuleGraph) -> Iterator[Tuple[str, str, Sequence[BaseNode]]]: """ Detect groups of reachable nodes in the graph. This function groups nodes in two ways:...
f68725648c240b6132a7c8dcf7dfffe2c86b5fa5
3,622,630
import re def highlight_regex(str_, pat, reflags=0, color='red'): """ FIXME Use pygments instead """ matches = list(re.finditer(pat, str_, flags=reflags)) colored = str_ for match in reversed(matches): start = match.start() end = match.end() colored_part = ub.color_text...
067dbc3dbbc8e34bf3484b9c1059cef620de52f4
3,622,631
def get_environment(env_name: str) -> Environment: """ Get environment for given env name :return: Environment or None """ _check_active_client() envs = _merlin_client.list_environment() # type: ignore for env in envs: if env.name == env_name: return env return None
d13c4eb4a15e654da2d6bdfb9a02e28b9f2f41b5
3,622,632
def cluster_otus(workflow, method, fasta_file, reference_fasta, output_folder): """ Cluster the otus with usearch Args: workflow (anadama2.workflow): an instance of the workflow class. method (string): tools for sequence analysis - usearhc(default) or vsearch fasta_file (string): th...
e7ec21806a44bdf7f3c543120482fb4f6de0e41b
3,622,633
def get_mirtarbase(): """Get generic mirtarbase entry.""" return _get_data(mirtarbase.Mirtarbase)
03c0df18eebdf9b46525f16b723fa90bc65a50fb
3,622,634
def build_postprocessor(): """Build the default postprocessors.""" processor = PostProcessor() # processor.reg.add(function, name, priority) return processor
1dc50f7161b8af83cb1cba36edf84605c76b57c1
3,622,635
def mod(source): """Create kernel module shared among multiple tests.""" return source.get_module_for_symbol("snd_request_card")
484afb203021497614ee18c7ac99200e4cb39a12
3,622,636
import torch def load_data(data_file, one_hot: bool = True, one_hot_dim: int = None, code_map=None): # TODO: remove the radii selection lines # TODO: Currently the one-hot encoding is done in memory all at once. Potentially it needs to be moved to a custom DataLoader like ExpertTrajectory above """For Ara...
35d9db25a2bb45c8af9de2bd707184b297d1e24e
3,622,637
def getAvailableTimesOnDate(client, date): """Function that first loads the page for a date and then returns the list of free time slots on that day.""" loadDate(client, date) return getAvailableTimes(client.html)
bad64a867a87d25c6e6be5e0412703966037d4ca
3,622,638
import six def make_utf8(x): """Encode a string as UTF8 Respect both python2 and python3.""" if isinstance(x, six.text_type): return x elif isinstance(x, six.binary_type): return x.decode('utf8') else: raise ValueError('Expected string type, got type %s' % str(type(x)))
f41c7b0933c21f1659cab00df3fa2c50ab4e2bcf
3,622,639
from typing import get_args import torch import math def forward_step(data_iterator, model, input_tensor): """Forward step.""" args = get_args() timers = get_timers() # Get the batch. timers('batch-generator').start() query_tokens, query_mask, \ context_tokens, context_mask, context_indic...
4538d89a532416eaec8e2268f593beac8a983eb9
3,622,640
from typing import Tuple from typing import Dict import os import json def load_savedmodel(savedmodel_dir: str) -> Tuple[tf.compat.v1.Session, Dict[str, any]]: """ Loads a Lobe exported Tensorflow SavedModel and returns the session with the model loaded and our signature file. """ # make sure our exported SavedM...
017411dfc3c75facd221dfe3a1a05351977df66e
3,622,641
from pathlib import Path from typing import Union def _join_subpath(root: Path, source: Union[str, Path], destination: Path) -> Path: """ Appends to destination, source-relative path to root. Written for use with os.walk() to match subfolders during walk. For example: root =...
493effdf898ba0b07059b092eb6f29ead770a3d4
3,622,642
import os def makepath(subsystem, group, pseudofile=None): """Pieces together a full path of the cgroup. """ mountpoint = _get_mountpoint(subsystem) group = group.strip('/') if pseudofile: return os.path.join(mountpoint, group, pseudofile) return os.path.join(mountpoint, group)
7ec0e71443a7a9de1b0128186abe6fe547ac997c
3,622,643
import six def srt_formatter(subtitles, padding_before=0, padding_after=0): """ Serialize a list of subtitles according to the SRT format, with optional time padding. """ sub_rip_file = pysrt.SubRipFile() for i, ((start, end), text) in enumerate(subtitles, start=1): item = pysrt.SubRipItem...
3aaa355ee4fd578c32fbe8d00c6893b46dbd1b0e
3,622,644
from datetime import datetime def are_in_same_quarter(first: datetime.date, second: datetime.date) -> bool: """Find out if two dates are in the same quarter. Args: first (datetime.date): The first date. second (datetime.date): The second date. Returns: bool: True if the dates aar...
f16b16f61805a086d1ae2af36ff2ae3ae2ffdb06
3,622,645
from typing import Optional from typing import List from typing import Tuple def get_plot_colours(n: int = 10, colourmap: Optional[str] = None) -> List[Tuple[float]]: """ Return iterable list of RGB colour values that can be used for custom plotting functions Returns a list of RGB colours values, potenti...
8e7107f2453abf01107d2547a0ca65fca87e36e8
3,622,646
from pathlib import Path from datetime import datetime import re def get_output_file_globbing_template(output_dir: Path, file_prefix: str, file_suffix: str) -> Path: """ Returns a canonical path with the given parameters where the start and end times are replaced with a globbing expression (?). :para...
e7ab73e55bc9c079f652bc066414b30db61b304b
3,622,647
def evaluate_reaction_rate(results, cell, nuc, rxn): """ Evaluates a single nuclide reaction rate in a single cell from a results list. Parameters ---------- results : list of Results The results to extract data from. Must be sorted and continuous. cell : str Cell name to evaluate ...
88e0b1d90eb3ae600185c0454bd2236b268a68de
3,622,648
def roundFloatsInDict(data, decimals): """Recursively rounds all floats in the dictionary to the specified decimal digits. If a float value is smaller than 10e-decimals it is set to zero. Args: data(dict): data dictionary decimals(int): number of decimals floats should be rounded to R...
7a16fad75f378665f5605cbec841e76dc2c91094
3,622,649
def _get_vuln_info_from_cve(full_cve): """Return the vulnerable configurations of operating system and software for a given CVE. Args: full_cve (dict): Full CVE data as a JSON dictionary from API call. Returns (dict, dict): ({os: [version,]}, {software: [version,]) """ vulnerable_confi...
41c6bfefe53fc9dee45edb93787f3d378b76d836
3,622,650
def toggle_results_visible(session, context, poll): """Change the results visible settings of a poll.""" if poll.created: return i18n.t('callback.poll_already_created', locale=context.user.locale) poll.results_visible = not poll.results_visible open_anonymization_settings(context.query.message...
3056aa5af830439898f4c0dcd51810f3a513d401
3,622,651
def fnCalculate_DatetimeEpoch(timevec, index, timestamp): """ Find the datetime object for the time index. Created: 24 May 2017 in testepochfunc.py Edited: 29.08.17: Commented out everything, better to use datetime methods. As set up originally, results would be imprecise ...
2e3a76e94178c14161dc40d166df7e7fc3e2cbb1
3,622,652
from typing import Optional from typing import Tuple from typing import Union from typing import List def fetchFTPURL(remote_file:URIType, cachedFilename:AbsPath, secContext:Optional[SecurityContextConfig]=None) -> Tuple[Union[URIType, ContentKind], List[URIWithMetadata]]: """ Method to fetch contents from ft...
1a3f10b6427ce43859d9ad0dae6dc1574ea3f84b
3,622,653
from datetime import datetime import pytz def compute_stage4(lon, lat, year): """Build a daily dataframe for the stage4 data""" nc = netCDF4.Dataset("/mesonet/data/stage4/%s_stage4_hourly.nc" % (year,)) lons = nc.variables["lon"][:] lats = nc.variables["lat"][:] dist = ((lons - lon) ** 2 + (lats -...
615599e335756df2b82e97b34ccf6a06db0050cd
3,622,654
def celery_place_order(data, staff_id): """使用Celery + djcelery实现快递异步下单 使用djcelery可以在任务中方便的直接操作Django数据库, 而且最终的任务可以在Django的后台中查看和修改相关的任务""" # 创建快递操作对象 express = ProjectExpress() result = express.place_order(request_data=data) if result.get('Success'): ExpressInfo.objects.create( ...
d93cf3d697365b89b0604656117bb15a977f5f72
3,622,655
def measure_torsion_angles(residues): """Calculates the dihedral angles for a list of backbone atoms. Parameters ---------- residues : [ampal.Residue] List of `Residue` objects. Returns ------- torsion_angles : (float, float, float) One triple for each residue, containing t...
4392b09f9c09afd0a75048d590bdfe582d2ae23a
3,622,656
from functools import reduce def constant_time_compare(x, y): """ Compares two byte strings in a way such that execution time is constant regardless of how much alike the input values are, provided that they are of the same length. Comparisons between user input and secret data such as calculated...
fe7fc348d367907eee2c9df3b7d0fbe232072714
3,622,657
def get_objective_sbml_fbc_ids(model_source): """ Get the SBML-FBC id of the active objective Args: model_source (:obj:`str`): path to model Returns: :obj:`tuple`: * :obj:`str`: SBML-FBC id of the active objective * :obj:`list` of :obj:`str`: SBML-FBC id of the obj...
1c6975032879c872e438392ec6be23e8caf9d0e3
3,622,658
def isNOAAACE(filename): """ Checks whether a file is NOAA ACE format. """ try: tempf = open(filename, 'rt') temp1= tempf.readline() temp2= tempf.readline() temp3= tempf.readline() except: return False try: if not temp1.startswith(':'): ...
f2787ef1e3110aa4105af9bfe7267bfa5d2c0b84
3,622,659
import ctypes def uiNewRadioButtons(): """ Creates a new radio buttons. :return: uiRadioButtons """ clibui.uiNewRadioButtons.restype = ctypes.POINTER(uiRadioButtons) return clibui.uiNewRadioButtons()
e63179601033359ba2cee0dd2aeae0af35d7e4ce
3,622,660
def gradient_binarizing_scalers(grads_and_vars, clip_factor): """ Get the scalers.""" gradients, variables = zip(*grads_and_vars) scalers = [] for gradient in gradients: if gradient is None: scalers.append(None) continue if (clip_factor > 1.0e-5): mea...
a95869f41064cb5be2378770f8f969483fd1e2c0
3,622,661
import time def cov_spk_ker(spk, object=False, time_format='TDB', support_ker ='', report=False, unload=True): """ Provides time coverage summary for a given object for a given SPK file. Several options are available. This function is based on the following SPICE API: http://naif....
f757fb35d4f58ae921916c40176868bdbdc635ea
3,622,662
def _str2bool(string): """Converts either 'true' or 'false' (not case-sensitively) into a boolean.""" if string is None: return False else: string = string.lower() if string == 'true': return True elif string == 'false': return False else: raise ValueError( 'String should either...
97755d1901a836bb1e3ce062afdbffc8b5b92de1
3,622,663
import math def _get_alpha_bar_from_time(t): """ Noise scheduling method proposed by Nichol et. al to avoid too noisy image especially for smaller resolution. This strategy creates beta as follows: alpha_bar(t) = f(t) / f(0) f(t) = cos((t / T + s) / (1 + s) * PI / 2) ** 2 beta(t) ...
ecb79239e2181d6e17db0b30885ec68d48b0a2d3
3,622,664
def decrementAny(tup): """ the closest tuples to tup: decrementing by 1 along any dimension. Never go into negatives though. """ res = [] for i, x in enumerate(tup): if x > 0: res.append(tuple(list(tup[:i]) + [x - 1] + list(tup[i + 1:]))) return res
44d5c968231cfb761c641892883a85c6a168c338
3,622,665
import unittest def mock_open(mock=None, read_data=''): """ A helper function to create a mock to replace the use of :func:`open()`. It works for :func:`open()` called directly or used as a context manager. :param mock: mock object to configure, by default a :class:`~asynctest.MagicM...
8379d4da696254e029641cab97d8ff5783265f43
3,622,666
import json def create_notification(): """Allows creation of a new alert Takes a JSON payload like: { "feed_urls": [ "http://feed.com/feed.xml" ], "subject": "This is an email subject", "body" : "<p>Some HTML here</p>" } """ # TODO: Should be able ...
83bc3617d9aca42f4f2086afd279c5dd11fd3ecc
3,622,667
def ExtractModuleIdIfValidBreakpad(file_path): """Extracts breakpad file's module id if the file is valid. A breakpad file is valid for extracting its module id if it has a valid MODULE record, formatted like so: MODULE operatingsystem architecture id name For example: MODULE mac x86_64 1240DF90E9AC39038E...
e846cf05976c2c1622160d1a2a639d605e072417
3,622,668
from datetime import datetime import pytz def _timestamp_to_iso_str(timestamp): """ Converts the timestamp value into a iso str Args: timestamp(float): the timestamp to convert Returns: str: converted timestamp """ return datetime.fromtimestamp(timestamp).replace(tzinfo=pytz....
89257c74a96c5335bc25ef617e41c0eeeb31021e
3,622,669
import pkg_resources import joblib def load_classifier(clf_name): """ Load classifier. ... Parameters ---------- clf_name : str Name of classifier to load. Returns ------- clf : scikit-learn classifier Classifier. """ clf_path = pkg_resources.resource_fil...
6a5278fbce2ba107a76d114859b3eb58d107271a
3,622,670
import calendar import time def login(): """ Try to log a new user in. If a correct username and password have been provided we return a jwt to the user that can be used to login into any part of meerkat. Parameters are passed in the POST request data. Args: username (str): The users user...
d5744cff57ab0f504d7da3a5c174a1fc8d1935e9
3,622,671
import random import operator def TournamentSelectDBOne(size, prob_selection,db_list): """ Function: SelectDBOne ====================== Select one individual from a database using Tournament selection @param size: number of individual choosen at random from the population @param prob_select...
1ca2ddeb8119ce2f8def450d1ca2b51977e5410b
3,622,672
import resource def read(hash, args={}): """ Read allowance by hash """ return resource.read(**{**{ 'type': 'allowance', 'key': hash, }, **args})
52889a507e367eefc283275c9f984597e0d88242
3,622,673
def predict(request: PredictRequest): """ Predict allergens from request :param request: incoming api request :return: """ check_model_exists(request) response = modelResolver.predict(model_name=request.model, data=preprocessor.process(request.data), ...
6fa566ab36ac4f665a43ce06478acbfa6b4ec91b
3,622,674
import numpy def validate(data, labels, toStandardise=False, overSamplingPercentages = None, toShuffle=False, saveFile = False, randomState=None, samplingMethodology=smoteTransform, kfolds=10): """Generates data-points (fp and tp) for generating a ROC curve through oversampling and und...
9ed24a7e7c8b30199d050e5ce8b8c0259cb8911e
3,622,675
def is_select(a): """Return `True` if `a` is a Z3 array select application. >>> a = Array('a', IntSort(), IntSort()) >>> is_select(a) False >>> i = Int('i') >>> is_select(a[i]) True """ return is_app_of(a, Z3_OP_SELECT)
712c1acc5984cf558eb46161d80c3a29f77fe7a6
3,622,676
def log_vector(tag, values): """ log_histogram Logs a vector of values. """ values = np.array(values).flatten() # Fill fields of histogram proto hist = HistogramProto() hist.min = 0 hist.max = len(values) - 1 hist.num = len(values) hist.sum = float(np.sum(np.arange(hist.num)...
a0de2f0fef23ee555ea3d31095c4877203a0cc30
3,622,677
def subtract_mean_vector(frame): """ Re-center the vectors in a DataFrame by subtracting the mean vector from each row. """ return frame.sub(frame.mean(axis='rows'), axis='columns')
4a6207889b958aebd608c349ad889e109ab3f4a9
3,622,678
def reduce_level(ast): """ The function removes from the abstract syntax tree a declaration current level (pointer or array). For instance it makes from AST of 'int *a' it makes AST for 'int a'. :param ast: Current abstract syntax tree. :return: Abstract syntax tree for the pointer or an array elem...
6d7e61265555106efe9f0733ec5f40b51bdaedf8
3,622,679
def to_location(maiden: str, center: bool = False) -> tuple[float, float]: """ convert Maidenhead grid to latitude, longitude Parameters ---------- maiden : str Maidenhead grid locator of length 2 to 8 center : bool If true, return the center of provided maidenhead grid square...
fddcbdab4f3e0f812dd7fac3509e66bc63f8fb84
3,622,680
def threshold_amplitude(x, metric, samples, percentile, frange, Fs, filter_fn=None, filter_kwargs=None): """ Exclude from analysis the samples in which the amplitude falls below a defined percentile Parameters ---------- x : numpy array raw time series metric : numpy array s...
a1e4165877862134f174c54f23ab14edf8290792
3,622,681
def opcode_by_value(val: int) -> OpCode: """ Mapping: Retrieves the OpCode object with the given value. Throws: LookupError: if there is no opcode defined with the given value. """ if val not in BYTECODES: raise LookupError("No opcode with value '0x{:02X}'.".format(val)) return BY...
8d438a282cb642dc409c7d14dd382433659304a3
3,622,682
import math def random_mini_batches(X, Y, mini_batch_size = 64, seed = 0): """ Creates a list of random minibatches from (X, Y) Arguments: X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci) Y -- true "label" vector (containing 0 if cat, 1 if non-cat), of shape (1, numb...
8ffd7ea8a1c019fbc8d3b78e634128af8cf8978c
3,622,683
def flipDP(directionPointer: int) -> int: """ Cycles the directionpointer 0 -> 1, 1 -> 2, 2 -> 3, 3 -> 0 :param directionPointer: unflipped directionPointer :return: new DirectionPointer """ if directionPointer != 3: return directionPointer + 1 return 0
928347a5c1934c822c77434ca9a91d913ef7f3b5
3,622,684
def projection_type_validator(x): """ Property: Projection.ProjectionType """ valid_types = ["KEYS_ONLY", "INCLUDE", "ALL"] if x not in valid_types: raise ValueError("ProjectionType must be one of: %s" % ", ".join(valid_types)) return x
049945caf31378648814034953dfab1ea8199816
3,622,685
def extract_dataset(filepath, dataset_name=''): """ extracts the dataset of the dataset you are interested in :param filepath: the .mat filepath :param dataset_name: the name of the dataset you are interested in :return: a n-dimensional array for the dataset. """ # print(dataset_name) wi...
8cfafc898254490ed85660becb9b22985b751b04
3,622,686
def get_datatype(data): """ rules defining the sidtype, based on the data dict of the sid. The keys are always given. The values can be empty. :param data: :return: """ subtype = "project" if "entity" in data.keys(): subtype = "entity" if data.get("type"): subt...
a7677db6d6aa9a9ccdcbdd9f6fd9d87032fcd18f
3,622,687
import os import subprocess def build(env_meta_path): """ Builds the package for `env_meta_path`. Parameters ---------- env_meta_path : str path pointing to a 'meta.yaml' file. Returns ------- success : the path to the build package failure : None """ if not os....
b4802347c3e22ff7b6ae0e8b77ebd31815ebcc7b
3,622,688
async def app(): """ For start gunicorn in production :return: """ return create_app()
c49c61426914631db6ea79c0120e149e0222fed9
3,622,689
def pre_process_data_frame(data_frame, convert_categorical_to_numeric=False): """Pre-process the passed data frame""" # replace the missing values data_frame = replace_missing_values(data_frame) # normalize numeric columns data_frame = normalize_numeric_columns(data_frame) # convert categori...
34442a0558694a0693757eca437214290e845605
3,622,690
from datetime import datetime def datestr(then, now=None): """ Converts a (UTC) datetime object to a nice string representation. >>> from datetime import datetime, timedelta >>> d = datetime(1970, 5, 1) >>> datestr(d, now=d) '0 microseconds ago' >>> for t, v in { ...
6087b5ef4299d0162fb61d6a243fceca65b21251
3,622,691
def main(input_file): """Solve puzzle and connect part 1 with part 2 if needed.""" inp = read_input(input_file) transformations = get_all_transformations(inp) p1 = part_1(inp, transformations) print(f"Solution to part 1: {p1}") p2 = part_2(transformations) print(f"Solution to part 2: {p2}") ...
0fe8bbc00c91f2af1574f1ae105873cd5b31448f
3,622,692
def wshed_raw(labels, im): """ return wshed lines """ ia = lambda x: sitk.GetImageFromArray(x) ai = lambda x: sitk.GetArrayFromImage(x) feature_img = ia(im) ws_img = sitk.MorphologicalWatershed(feature_img, level=0, markWatershedLine=True, fullyConnected=True) ws = ai(ws_img) ws = ws...
a147282e1c7a61fdc0428652c094f84818cf4ab5
3,622,693
def process_link(link): """ Get text and link from an anchor """ return link.text_content(), link.get('href')
34429289076c8518b076fdf0f228eb6948109c6c
3,622,694
from typing import Optional from typing import Union import json def update_stack( profile: Optional[Union[str, bool]] = False, region: Optional[Union[str, bool]] = False, replace: bool = False, local_path: Union[str, bool] = False, root: bool = False, wait: bool = False, extra: bool = Fal...
5001ec30d3141d3598865e2496f775091435c603
3,622,695
from typing import Optional def dot_product_attention( query: jnp.ndarray, key: jnp.ndarray, value: jnp.ndarray, *, bias: Optional[jnp.ndarray] = None, bias_kv: Optional[jnp.ndarray] = None, broadcast_dropout: bool = True, dropout_rate: float = 0.1, dtype: jnp.dtype = jnp.float32, ...
c4c291f89b2744854c96b750550c771baa3bf92c
3,622,696
def stringify_children(node): """Read and stringify the children of each nxml node.""" section_parts = [] for ch in node.getchildren(): string_text = '' ch_tag = ch.tag if ((ch_tag == 'title') or (ch_tag == 'p')): sec_tree = ch.xpath("text()") for txt in sec_tree: txt = txt.rstrip() if len(txt) >...
82336915ea6b8451de430ec41ece94e21d08adc5
3,622,697
def convolutional_block(X, f, filters, stage, block, s=2): """ Implementation of the convolutional block as defined in Figure 4 Arguments: X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev) f -- integer, specifying the shape of the middle CONV's window for \ the main path filters ...
bf16ba5429bf377fb048ccb863f0ab5c6c893ac3
3,622,698
from typing import Optional def get_alarm_history_collection(alarm_historytype: Optional[str] = None, alarm_id: Optional[str] = None, timestamp_greater_than_or_equal_to: Optional[str] = None, timestamp_less_than: Option...
55dc491d63b9e1a28fde1b234d61abc4a204e6d0
3,622,699