content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def dump(filename, outfile="", parameters=[]): """ The rrdtool Python bindings don't have support for dump, so we need to use the external dump function. >>> rrdfile = '/tmp/test.rrd' >>> parameters = [ ... '--start', ... '920804400', ... 'DS:speed:COUNTER:600:U:U', ... 'RRA...
0b148f3af5dc941b21b2bbd089a6702bf03166ac
3,617,700
import logging def get_circular_orbit_speed(body="Earth", altitude=160): """ Get speed of LEO (Low Earth Orbit) at designated altitude. Keyword Arguments: altitude {int} -- distance above Earth surface in km (default: {160}) Returns: [int] -- speed in km/s. """ if body == "Sun":...
ff874bd070e47ccb31bdce6c5dc9806ad6bc3581
3,617,701
def load_sce_and_metadata(file_path, local_env_yaml): """ For the given SCE audit file (file_path) under the specified environment (local_env_yaml), parse the file while expanding Jinja macros and read any metadata headers the file contains. Note that the last keyword of a specified type is the reco...
b416053721d90aca79f68ac53d4d1deec8e54b3d
3,617,702
import os import sqlite3 import getpass def migrate_user(auth, client, cfgobj): """ Migration function that reads data from old matomat sqlite and creates user in the backend :auth: dict :client: userauth object :cfgobj: config dict :returns: bool """ # Check if configured database i...
4be0df30714c30f498425f07b7e97895e5968237
3,617,703
def datetime_interpretation(raw): """Converts human-readable datetime into normal datetime instance. Args: raw (str or unicode): source string with datetime data. Returns: datetime: result datetime instance. None: if couldn't read value. """ if isinstance(raw, (unicode, str...
fb13511fa17ef5883a9f952aec24092397821d40
3,617,704
def model_3d_deep(n_classes: int, input_size: int, **kwargs) -> tf.keras.Sequential: """ Deep 3D convolutional model from: https://arxiv.org/pdf/1907.11935.pdf :param n_classes: Number of classes in the dataset :param input_size: Size of the input sample :param kwargs: Additional arguments. :re...
18dbf5500ec0db766778b4e58f93440d225b23dd
3,617,705
from typing import Counter def _pairing_consistency_check(files, errors): """checks the datastructure for consistency""" file_list = sorted([f for f in files if not files[f].get('symlink')]) pair_list = [] for f, info in files.items(): # skip links for secondary aliases if info.get('sy...
f49a1554dd920adfde65d10a95bfd7d574836a4d
3,617,706
import os def get_data_files(dir): """ Return alphabetical sorted list of all found XML data files in directory, excluding the main database file (MSDN_INFO_FILE). Argument: dir -- path where XML data files reside """ data_files = os.listdir(dir) if MSDN_INFO_FILE in data_files: d...
8be3598990d8cf948f026546fd43acded5de2880
3,617,707
def non_related_filter(questions_df, non_related_ids): """ Splits a questions dataframe between related and non-related discussions, based on an Ids list of non-related discussions. :param questions_df: > A pandas dataframe of stackoverflow questions containing posts Ids; :param non_...
b7e64287b2bdb6a8999bcd8e7efd8e2787b991dd
3,617,708
def _configure_features_for_binary( ctx, requested_features = [], unsupported_features = []): """Creates and returns the feature configuration for binary linking. This helper automatically handles common features for all Swift binary-creating targets, like code coverage. Args: ...
156e348b77d160b1d237808f90b5f5d98a8511d6
3,617,709
def update_assessment( db_session: Session, old_assessment: RestBewertungCreate, new_assessment: RestBewertungCreate ) -> RestBewertungReturn: """Update the comment and rating of a existing assessment Args: db_session (sqlalchemy.orm.Session): Session to the DB -> See `db: Session = Depends(get_db)...
2eeaeb8d672d0fdbbbc0a3149cdc2349dd8d9e99
3,617,710
def index(request): """index Args: request (request): api request """ return JsonResponse({"data": "theres nothing at this endpoint"})
06a36cc2665d72598063258c55cd78c8741f8596
3,617,711
import math def sin(x): """Return sin of x (x is in radians)""" return math.sin(x)
c5b091892e54df064b61a109812b3ea1206b1713
3,617,712
def get_resource_path(): """Return the path to general resources. Returns the path to general resources, terminated with separator. Resources are kept outside package folder in "resources". Based on function by Yaroslav Halchenko used in Neurosynth Python package. Returns ------- resource_...
2486d552c43f2fd4a1d191c62a44ea7732afd676
3,617,713
import test def launch(launcher, use_pycuerun=True): """ Launch the given L{OutlineLauncher}. :type launcher: L{OutlineLauncher} :param launcher: The OutlineLauncher to launch. :type use_pycuerun: bool :param use_pycuerun: Enable/Disable pycuerun. :rtype: opencue.Entity.Job :return: ...
ebeb09d3e2b02e42bb04ef8905d2cf3b8582c4fa
3,617,714
def _paramMinCount(callableObject): """ Given a callable object (function, method or callable instance), return pair (min,d) where min is minimum # of args required, and d is number of default arguments. The 'self' parameter, in the case of methods, is not counted. """ if type(callableObject...
d3ff64ce2c2ca4a25f225bc58ec0e30d352cb259
3,617,715
def acceleration(syn, obs, nt, dt, *args, **kwargs): """ Acceleration waveform for migration, second derivative of obs """ adj[1:-1] = (-obs[2:] + 2. * obs[1:-1] - obs[0:-2]) / (2. * dt) return adj
cb7e320cb4eaaaf7733681608428e1d16f755ca1
3,617,716
from sys import version def get_updated_version_copy(existing_version: version.Version, major: int = None, minor: int = None, micro: int = None) -> version.Version: """get_updated_version_copy Generates a copy of a version.Version with the specified major, minor, micro version. ...
bc5e4e8b1b4f85fe2dce09bb95d0dabfc3794b04
3,617,717
def format_pin(pnum, relatedpnum): """Formats a Parcel ID Number (PIN) from a BS&A PNUM.""" try: if relatedpnum is None or relatedpnum.startswith('70-15-17-6'): p = pnum else: p = relatedpnum p = p.split('-') del p[0] p = ''.join(p) except Inde...
8338fd5b329cf37d3fa59cd1b7d1f71e6694d706
3,617,718
from datetime import datetime def condense_log_events(log_stream, log_events): """Condense log events into single strings. expects list of dicts.""" condensed_events = [] for event in log_events: event_datetime = datetime.fromtimestamp(event['timestamp'] / 1000) message = "{} | {} | {}".fo...
94bfdc73d9fad7151162ca3e1bf114cc11950067
3,617,719
import os def list_repofiles(c, name): """get files from manifest from working or devel repo """ if name in all_repos: path, files = get_repofiles(c, name) else: if name == '.': path = '.' else: path = os.path.join(DEVEL, '_' + name) if not o...
d8288e3e3245648cebd724e49e7f31045a31bdde
3,617,720
import os def trickle(session_config): """Return a dict with "trickled down" / inherited config values. This will only work if config has been expanded to full form with :meth:`config.expand`. tmuxp allows certain commands to be default at the session, window level. shell_command_before trickles...
a429f4102f40ced0ee47ad3ed39d1f678e35c3ab
3,617,721
import datetime as dt def current_year(): """ Returns the current year. """ now = dt.datetime.now() return now.year
34fe2695dfb224d0db39af7dffc084058b93518a
3,617,722
import re import threading def register(): """ The register page endpoint --- get: parameters: None responses: 200: The register page html post: parameters: None responses: 301: redirects to login if re...
cad5d166463bf9c924fb9f8132104bf494b4a5c4
3,617,723
def get_router_port(endpoint): """ get the network device and port of where the endpoint is connected to. Args: endpoint (endpoint): endpoint A routerport is a dict with the following keys: router (string): name of the netork device port (string): port on the router....
30c331169a0c5e1a6b0bf91b8ad43c1db64dc532
3,617,724
import networkx def createGraph(input_edge_list): """ From list of edges create and return a graph. :param input_edge_list: list of edges :returns G: the graph """ # first thing, how are the nodes separated in an edge with open(input_edge_list, 'r') as f: l = f.readline() ...
5a92864aa78cc99218c45031c80a6b89a836f134
3,617,725
def dummy_callable(obj): """A callable that you probably shouldn't be using :)""" return []
2a0c71bd1a558d3df1c40c5a384fa98bf3cc15ad
3,617,726
from typing import List def get_accessory_files(model_id: str) -> List[DojoSchema.ModelAccessory]: """ Get the `accessory files` for a model. Each `accessory file` represents a single file that is created to be associated with the model. Here we store key metadata about the `accessory file` which...
c946af602e4433aab395e14c96e5354bbc41468b
3,617,727
def text_to_ascii_text(font, text, cols, lines): """Convert text to ASCII art text banner""" image = Image.new('RGB', (cols - 1, lines - 1), (255, 255, 255)) draw = ImageDraw.Draw(image) draw.text((0, 0), text, fill='black', font=font) width, height = image.size pixels = image.load() # conve...
6b63369a588192ed084610d4b65789d909ef57d4
3,617,728
import os def api_role(typ, rawtext, text, lineno, inliner, options={}, content=[]): """ Role `:api:` bridges generated API documentation by epydoc with sphinx. Add `epydoc_ext` to the list of extensions Generate the documentation in build folder:: $ mkdir -p _build/html/api $ e...
bae4b423b81fb4ec0478dd78b34a7211959ee53e
3,617,729
from scipy import integrate def compute_auc(xpts, ypts): """ Calculates the AUC. :param xpts: Points on the X axis - the threshold values :param ypts: Points on the Y axis - the pck value for that threshold :return: The AUC value computed by integrating over pck values for all thresholds """ ...
6790f8183034351fc1d75c6baa10350e55864038
3,617,730
import math def cie76(c1, c2): """ Color comparision using CIE76 algorithm. Returns a float value where 0 is a perfect match and 100 is opposing colors. Note that the range can be larger than 100. http://zschuessler.github.io/DeltaE/learn/ LAB Delta E - version CIE76 https://en.wikipedia....
9470b66231252decd8be7f07af2591ddf1278edc
3,617,731
from typing import Any from typing import Tuple def fill_based_other_col(data: DataFrame, col_to_fill: str, ref_col: str, method: str = 'mode', replace: Any = np.nan) -> Tuple[Series, Any]: """Function to fill nulls on a DataFrame column based on other column. To fill based on multipl...
654c948896c6ad50145d7177fa0f7ce380f9edcc
3,617,732
def sparse_reset_shape(sp_input, new_shape=None): """Resets the shape of a `SparseTensor` with indices and values unchanged. If `new_shape` is None, returns a copy of `sp_input` with its shape reset to the tight bounding box of `sp_input`. This will be a shape consisting of all zeros if sp_input has no values....
77c2f6266fe50a1be77e859f9f876a56c60809a6
3,617,733
def project_new_folder(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /project-xxxx/newFolder API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Folders-and-Deletion#API-method%3A-%2Fclass-xxxx%2FnewFolder """ return DXHTTPRequest('/%s/newF...
3236d824fe5ea8e9698647c16107e3ea1295f4bc
3,617,734
import os from datetime import datetime def get_file_stat(path): """ This is a helper function that given a local path return the size of the file in bytes and time of last modification. """ try: stats = os.stat(path) except IOError as e: raise ValueError('Could not retrieve fi...
ea5f9c35a17b1aa2d2b26541f2940ce30bd2926e
3,617,735
def PolyConvex(poligono): """ Funcion para calcular el poligono con una serie de cordenadas dada """ points = np.array(poligono) hull = ConvexHull(points) ps = set() for x, y in hull.simplices: ps.add(x) ps.add(y) ps = np.array(list(ps)) p = pd.DataFrame(points) ...
5ebf1d031889f3da495f2c5b96fb5c4cae98d271
3,617,736
def recycling_to_no3(vs, plankton, no3): """Recycling to nitrate needs no scaling""" return {no3: recycling(vs, plankton, no3, 1)[no3]}
7dde877ce204dfb97ddd249500bcd7a276293d31
3,617,737
def sharpe_ratio(returns): """Computes Sharpe Ratio from simple returns. Parameters ---------- returns : np.ndarray | pd.Series | pd.DataFrame Returns of the strategy as a percentage, noncumulative. Returns ------- sharpe_ratio : float | np.ndarray | pd.Series Sharpe ratio....
6039738f09c4aa1b016cbf17793ea5a3b6395bea
3,617,738
import copy import numpy def plot_2d(x_data, x_name='x_data', y_data=None, y_name='y_data', yerr=None, groups=None, identifiers=None, graph_type='scatter', line_width_=None, fit=None): """ Min part for plottings a 2d graph. If specified, args groups and identifiers specify the or...
a64910ee4bc9a403df759f31fcee0918362afe04
3,617,739
import typing import collections def serialize_some_embed( instance: some.graph.SomeEmbed, ordered: bool = False ) -> typing.MutableMapping[str, typing.Any]: """ serializes an instance of SomeEmbed to a JSONable representation. :param instance: the instance of SomeEmbed to be serialized ...
5b4f489ffde72b986c84522929e7985d6886080a
3,617,740
def get_current_user(*args): """Return the current user configured in middleware.""" if hasattr(LOGSFORHUMAN_THREAD, 'request'): return getattr(LOGSFORHUMAN_THREAD.request, 'user', None)
d81eed3783d48a29913d3d3daa961c0383e143ba
3,617,741
def get_pair_single(name): """ Given a fastq file name, determines if it's paired-end or single-end and returns the type + name. :param name: The name to check. :return: The combined file type ('single', 'forward', or 'reverse') and the name minus the direction-identifying part of the file name. ...
af2e8dbb459e2e4daa9836638dd885af863963d8
3,617,742
from pathlib import Path def parse_lst(lst_path): """Extract audio names of nnenglish.""" audio_names = [] with open(lst_path) as fd: for line in fd: audio_path, lang = tuple(line.strip().split()) if lang != "nnenglish": continue audio_name = Pa...
82ed0e7a0c13269416e4530157f2a67a68712676
3,617,743
import random def add_angle(r): """ Add angle for each r value to make up a coordinate of a polar coordinate. """ coords = [] for ri in r: theta = random.random() * 360 coords.append((ri, theta)) if len(coords) == 1: return coords[0] else: return coords
0e91e9c7999627885218dde42bc2849e89071eff
3,617,744
import re def Article_Add(request): """ 新增文章 :param request: :return: """ seo_list = get_object_or_404(Seo, name='文章') if request.method == 'GET': category = Category_Article.objects.all() return render(request,'pc/articlesadd.html',{"category":category,'seo_list':seo_list}...
367a20af9d175d8367ddeb2b83b727f5ca588843
3,617,745
def compute_cv_fold_stats(data_df, cv_splits): """ Computes CV fold size and class proportions for a given CV splitting. :param data_df: a DataFrame :param cv_splits: a given cv splitting as e.g. returned by cv_independent_associations() :return: a DataFrame that lists count and fraction of pos...
a39056a821c7527240c3151d11e03517e663c992
3,617,746
def lag_port_stats( data # type: "XDR Data" ): """LAG Port Statistics Counter - Type: Counter, Enterprise: 0, Format: 7""" sample_data = {} # Cache sample_data["dot3adAggPortActorSystemID"] = data.unpack_string() sample_data["dot3adAggPortPartnerOperSystemID"] = data.unpack_string() sample_data["dot3adAggPortAtt...
9c367a1d5aedb123854a77636f3d0cb6f50a839e
3,617,747
def fit(comb): """returns true if combination can be chosen and false otherwise""" if len(comb)>5|len(comb)<1: return False desk=list(filter(lambda x: x>4,comb)) if len(desk)<1: return True desk.sort() handOut = 5 - (len(comb)- len(desk)) deskLast=desk[-1] if handOut>=des...
3512dfb91bf4035c3e817c4bd110b446ef183c2d
3,617,748
import asyncio import inspect async def wait_for_reply(predicate: TYPE_CALLABLE_PREDICATE = None, timeout=30, default=None, raise_on_timeout=False) -> ReplyResult: """ waits for a message matching `predicate` to be received, when its received, it returns a ReplyResult instance with the response. if no me...
da14dd4bbddf7ca2c7cace92cb32eca886c1b2fb
3,617,749
import requests def query(session, qid, args={}): """Query AP system page by qid and args :param session: requests session object, the session must login first. :type session: class requests.sessions.Session :param qid: query id of ap system page :type qid: str :param args: arguments of query...
e5080f2e3d625eff94f442dd1b742f9f926011dd
3,617,750
def get_airflow_operation_client(): """ Get a client to operate airflow dags and tasks. """ global _default_airflow_operation_client ensure_project_registered() if _default_airflow_operation_client: return _default_airflow_operation_client else: return AirflowOperation(_default_proje...
0778e20b9260ce2ba1019bafc5951c16ef4fef6c
3,617,751
def FILTER(*args) -> Function: """ Returns a filtered version of the source range, returning only rows or columns which meet the specified conditions. Learn more: https//support.google.com/docs/answer/3093197 """ return Function("FILTER", args)
97139c2293430d4efcc076bb3e3c4cfcd85d344b
3,617,752
def get_args(): """ Command line arguments """ parser = ArgumentParser(description="Inspect sets of rts contained in hdfs store file(s) as pandas DataFrames.") parser.add_argument("files", help="XML file with RTS", nargs="+", type=str) parser.add_argument("--key", help="DataFrame key in store", default=...
bcbc1a3381a18975d68575742071c5d9151cd70a
3,617,753
from typing import OrderedDict def load_status_info(sfile, fudge=None): """ Parse the output of pb_run_status.py, either from a file or more likely from a BASH <() construct - we don't care. It's quasi-YAML format but I'll not use the YAML parser. Also I want to preserve the order. """...
13e6b546d93847b0321da2cb659150345b6a8b20
3,617,754
def calculateSimilarity(img1, img2, similarityType="l2"): """ This method calculates the similarity of two images given the type of similarity function (such as l2 distance). :param img1: np.array :param img2: np.array :param similarityType: str default: "l2" :return: float - distance between th...
7431f6a15e7d4af649efca55f4a99fb057f5dabb
3,617,755
def _is_false(x): """Evaluates false for bool(False) and str("false")/str("False"). The function is vectorized over numpy arrays or pandas Series. Everything that is NA as defined in `is_na()` evaluates to False. but also works for single values.""" x = np.array(x).astype(object) return _is_f...
d5fec5506da6fca9eeb1736dc6b42e5689a7cd3f
3,617,756
def badDebts(_trader: str = None, _start: int = None, _end: int = None) -> []: """ Get bad debts """ with utils.dbInterface() as client: db = client['perp'] criteria = {} if _trader: criteria['trader'] = _trader if _start or _end: criteria['timestamp'] = {} i...
a9d275770acfc1cb6fdb4c06bcfcda37e5fa3be1
3,617,757
from benchbuild.utils import schema def create_run_group(prj): """ Create a new 'run_group' in the database. This creates a new transaction in the database and creates a new run_group within this transaction. Afterwards we return both the transaction as well as the run_group itself. The user is r...
9112e921038df2544c56daf8aa698511bc509555
3,617,758
def get_tags_from_message(message): """ Given a message string, extracts hashtags and returns a comma-separated list :param message: a Hipchat message body """ tags = {word.strip('#') for word in message.split() if word.startswith('#')} return ','.join(tags)
528f7702f43f8f81adf942c79b292f508773d205
3,617,759
import sys def get_canny_edge_detected(image=None): """the function receives an [image] as an argument The list of things that function performs 1. checks if image is not None 2. turns the color image to Gray Scale 3. blurs the image to reduce the noise 4. detects edges using canny edge detec...
d120b14972103fdc06863bb232b2fd5e106047a9
3,617,760
import shutil import tempfile import subprocess import scipy def test_nwspgr(dimensions: int, level: int, nested: bool) -> None: """Compare with output from the Matlab function nwspgr by Florian Heiss and Viktor Winschel. The weights differ by floating point error because different sorting algorithms are used...
47a504e8c7df2dfb5d50406ffb81b6c7113f86c7
3,617,761
def tf_read_img(tf, filename): """Loads a image file as float32 HxWx3 array; tested to work on png and jpg images.""" string = tf.read_file(filename) image = tf.image.decode_image(string, channels=3) image = tf.cast(image, tf.float32) image /= 255 return image
662fc1c9840e67fb0ff3fae4b12da5179e286e25
3,617,762
def remove_outliers(X): """Function to replace "bad" measurements to zero. Inputs: H: Measurement applied field [float, SI units] Hr: Reversal field [float, SI units] M: Measured magnetization [float, SI units] Fk: Index of measured FORC (int) Fj: Index of given measurement within ...
6e759a35de66655eb93d01da71b80a30316b7f2d
3,617,763
def mumps_eigsh(matrix, k, sigma, **kwargs): """Call sla.eigsh with mumps support. Please see scipy.sparse.linalg.eigsh for documentation. """ class LuInv(sla.LinearOperator): def __init__(self, matrix): instance = kwant.linalg.mumps.MUMPSContext() instance.analyze(matr...
bde217f73ba97510eb8d544ba70fbd13f47f78e8
3,617,764
def collect_server_info(host, port): """ Collect general information of server. """ info = {} with pymongo.MongoClient(host, port, connect=True, serverSelectionTimeoutMS=3000) as mc: info['version'] = mc.server_info()['version'] return info
f8dca0057eb9f358a946b53a93098c39b5c8e799
3,617,765
def mean(array): """Return the mean value of the valid elements of an array. Parameters ---------- array : `numpy.ndarray` array of values Returns ------- `float` mean value """ non_nan = e.isfinite(array) return array[non_nan].mean()
baf91db62bc92887ce8055a1c4401ac874cd2014
3,617,766
def _get_boot_list_for_boot_device(node, device, controller_version): """Get the boot list for a given boot device. The DCIM_BootConfigSetting resource represents each boot list (eg. IPL/BIOS, BCV, UEFI, vFlash Partition, One Time Boot). The DCIM_BootSourceSetting resource represents each of the boot l...
a0713051126a6187e8e4e4c30b2331ff3873dd16
3,617,767
def putseconds(secs): """ Create a datestring for format 'dd HH:MM:SS' """ days = int(secs / SECSPERDAY) secs = int(secs - days * SECSPERDAY) hours = int(secs / SECSPERHOUR) secs = int(secs - hours * SECSPERHOUR) minutes = int(secs / SECSPERMINUTE) secs = int(secs - minutes * SECSPERMINU...
28ed6fe7a6fb00b14e9a89a0609819a5947f2f5f
3,617,768
def get_dataloaders(datasets, batch_size, data_type, preprocessor=None, name=None, label_transformer=None, **kwargs): """ Prepare, define and retrieve appropiate data loaders for the dataset partitions. Args: datasets: dict, {key:partition, val:dict of X, y lists} batch_size: int, batch size data_type: st...
d695a0caf9b86cbfa88ec726374019aa00efb1e0
3,617,769
def Gillespie_FRM4X(generics_func, func_param): """ FUNCTION: Gillespie_FRM4X(a{}, b str) a: dictionary containing function's generic values b: XML string file name - Function generic's handler for "Gillespie_FRM4X". """ # Python's variable...
20b40610607b2923877c65fe5fdbbc846a28adf7
3,617,770
def test_1_subject(sess,MR_image,CT_GT,MR_patch_sz,CT_patch_sz,step): """ receives an MR image and returns an estimated CT image of the same size """ matFA=MR_image matSeg=CT_GT dFA=MR_patch_sz dSeg=CT_patch_sz eps=1e-5 [row,col,leng]=matFA.shape margin1=int((dFA[0]-dSeg[0])/2) margin2=int((dFA[1]-dSeg[...
918877392d3d4a69c626a8cc175739d0750c0d46
3,617,771
def la_uploader(mock_put): """Generate LAUploader for testing.""" response = Response() response.status_code = 200 mock_put.return_value = response la_uploader = LAUploader(workspace="1234", workspace_secret="password", debug=True) return la_uploader
75316dfff8ea118c36e154f410dd8e332b82d48b
3,617,772
def jpeg_cmyk_to_rgb(image_bytes, quality=100): """Converts JPEG CMYK image (bytes) to RGB JPEG (bytes).""" runner = _get_runner() image = runner.run(tf.image.decode_jpeg, image_bytes) fn = lambda img: tf.image.encode_jpeg(img, format="rgb", quality=quality) return runner.run(fn, image)
dc09430d20d09bd44d82672ac779b557ee369346
3,617,773
def indices_for_pixel(pix_x, pix_y, x, y): """ Return the indices of the sources for which the coordinates lie in the x, y pixel """ (indxs,) = np.where( np.logical_and.reduce([pix_x > x, pix_x <= x + 1, pix_y > y, pix_y <= y + 1]) ) return indxs
0f8427927bea388e8bb23e0cc615b02ac1821fda
3,617,774
def is_valid_config_entry(opp, logger, origin, destination, region): """Return whether the config entry data is valid.""" origin = resolve_location(opp, logger, origin) destination = resolve_location(opp, logger, destination) try: WazeRouteCalculator(origin, destination, region).calc_all_routes_...
a052e508931cb1538b042c60ec205e54324d068b
3,617,775
import numpy as np # noqa def is_numpy_array(obj: Any) -> bool: # type: ignore """ Checks if the given object is a numpy array Args: obj (Any): The object to check Returns: bool: True if the object is a numpy array otherwise False """ try: except Exception: retu...
f32644e4dd9dfbb2513dc50a85fa3ee79973dfef
3,617,776
def create_rest_blueprint(app) -> Blueprint: """Create the blueprint for the REST endpoints using the current app extensions.""" # note: using flask.current_app isn't directly possible, because Invenio-MaDMP is # registered as an extension in the API app, not the "normal" app # (which is the...
c6af04da46be8e5ac85cfe3f4c315e9c7fc72f15
3,617,777
from pathlib import Path def construct_storage_path() -> Path: """Construct a Path to draw the standard "storage" flowchart shape.""" # NOTE: After a MOVETO, we need to put the pen down for CLOSEPOLY to # complete a filled shape. _path_data = [ # main shape (Path.MOVETO, [-1.000, -0.80...
5b4c263c9412071b93ef9db395392a8a8db8193d
3,617,778
def create_pb_from_mathtext(text, align='center', weight='heavy', color='b', style='normal'): """ Create a Gdk.Pixbuf from a mathtext string """ global pbmt_cache global dpi if not text in pbmt_cache: parts, fontsize = _handle_customs(text) pbs = [] width = 0 ...
a368e7a2ab1ac543ad511fcea0a7c00a1b70b047
3,617,779
def compare_rrs_types(exp_val, got_val, skip_rrsigs): """sets of RR types in both sections must match""" def rr_ordering_key(rrset): if rrset.covers: return rrset.covers, 1 # RRSIGs go to the end of RRtype list else: return rrset.rdtype, 0 def key_to_text(rrtype, rr...
85bd9f3cffaccaf70ccbb1020ad611fd450dc709
3,617,780
def __do_config_section(parser): """Populate the config section""" # Purge section before adding. parser.remove_section(dtfglobals.CONFIG_SECTION_CONFIG) parser.add_section(dtfglobals.CONFIG_SECTION_CONFIG) # Color is enabled by default parser.set(dtfglobals.CONFIG_SECTION_CONFIG, 'use_color...
90d6d07aefb8057f5c05ab8e8ca61deb0e4febce
3,617,781
def act_gsymbol_reference(context, nodes): """Repetition operators (`*`, `+`, `?`) will create additional productions in the grammar with name generated from original symbol name and suffixes: - `_0` - for `*` - `_1` - for `+` - `_opt` - for `?` Zero or more produces `one or more` productions a...
07ca0e0454b7b6e9b9c127d29afea6faf0f500e5
3,617,782
def is_higher_permission(level1, level2): """ Return True if the level1 is higher than level2 """ return (is_publish_permission(level1) and not is_publish_permission(level2) or (is_edit_permission(level1) and not is_publish_permission(level2) and not is_...
2ec9ee12804c37aeaa64d2fcad9842f05d434760
3,617,783
def vectorize_array(y, steps=1, return_type='df'): """ Take in an array like sequence of values. Vectorize the array and add steps from further in the series to each item. The values in the input array must be of shape [n, 1]. Rows with nan values in the result array will be dropped. If return_...
60be622200aa5000d936d13f3da8a4f7445dfe70
3,617,784
def extract_hist(*input_data, bias): """ Split the SSPFM curve into on and off signal. Function was rewritten to work with m_apply, and to take account a bug into Cypher machine, leading to pulse not all being the same size. Parameters ---------- input_data : array-like data which n...
92599975a911d32e28806308a27ae9b01f2d1c47
3,617,785
from typing import List from typing import Dict from typing import Callable from typing import Tuple import copy def do_upper_envelope_step( policy: List[np.ndarray], value: List[np.ndarray], *, expected_value: np.ndarray, params: pd.DataFrame, options: Dict[str, int], compute_utility: Cal...
9a9051751bb43211421012ca662c7fe8ef6248e2
3,617,786
def normalize_yaml(path): """Normalize a YAML file, and return whether the file changed.""" data = read_yaml(path) changed = write_yaml(data, path) return changed
f74c1b9a5a59bd728ac86c1aa92a70e182be2809
3,617,787
import os from io import StringIO def download(dbx, folder, subfolder, name): """Download a file. Return the bytes of the file, or None if it doesn't exist. """ path = '/%s/%s/%s' % (folder, subfolder.replace(os.path.sep, '/'), name) while '//' in path: path = path.replace('//', '/') t...
7bcff3356510caf5ee496078141f4e27b0b8c49d
3,617,788
def rotateQuaternionByRPYInUnrotatedFrame(roll, pitch, yaw, in_quat): """ Apply RPY rotation in the reference frame of the quaternion. Input: geometry_msgs.msg.Quaternion Output: geometry_msgs.msg.Quaternion rotated by roll, pitch, yaw in its frame """ q_in = [in_quat.x, in_quat.y, in_quat.z, i...
55e2f10e9a2af76c590a5a580c898fcfbdb66422
3,617,789
def log_mat(U): """Matrix logarithm, only use for normal matrices, i.e., square matrices U with U * U^T = U^T * UU""" vals, vecs = la.eig(U) vals = np.log(vals) return np.real(np.einsum('...ij,...j,...kj', vecs, vals, vecs))
e73c610e5584a379e7b4eb40ad8085e943a30511
3,617,790
import sage.plot.all import os import shutil def png(x, filename, density=150, debug=False, do_in_background=False, tiny=False, pdflatex=True, engine='pdflatex'): """ Create a png image representation of ``x`` and save to the given filename. INPUT: - ``x`` -- object to be displayed ...
b54568c5b930ddb8ce76d8fd4d48e83f9ab0e549
3,617,791
from typing import Optional def date_str_to_datetime(date_str: Optional[str]) -> timezone.datetime: """ Converts a date string to a datetime object. :param date_str: Date string (iso8601) :return: A datetime object. """ if date_str is None: return None return parse_datetime(date_...
70e8fa578a7a713d014f9d2e927abf8b3196c912
3,617,792
def add_field(radar_dest, radar_orig): """ adds the fields from orig radar into dest radar. If they are not in the same grid, interpolates them to dest grid Parameters ---------- radar_dest : radar object the destination radar radar_orig : radar object the radar object conta...
df6e62f2e5fb5bbddad77e037f196e0dbc3c5c97
3,617,793
import os def result_folder(*relative_path): """Return the full path to the result/ folder containing experimental result files""" C = _get_config() path = C["experiment"]["expr_results_path"] if relative_path: path = os.path.join(path, *relative_path) return path
6819c67bb70e749a011f1a319f3309e2a335f711
3,617,794
def _convert_str_to_html(string): """Helper function to insert <br> at line endings etc.""" if not string: return "" lines = string.splitlines() for index, line in enumerate(lines): for char in line: if char == '\t': lines[index] = line.replace(char, "&nbsp;&nbsp;&nbs...
b357d04f28a08f6b65d98ee381dcaef8969f6ff0
3,617,795
def build_icd(cp, instruction): """ Build the integer representation of the input channels to dequeue. :param cp: CoreParameters instance for the target architecture :param instruction: Instruction instance :return: integer representation of icd """ # OR in the literal array of bits. i...
99c1a7799a51ec53136cd7fee4104093921e3f61
3,617,796
import os import glob import sys import time import subprocess def processDirectory(inDir, doBgd, doFgd): """Create a layered PDF file from the rasters in `inDir` Temp files are stored in `jbigDir` """ if inDir.endswith("/"): print("%s->%s" % (inDir, inDir[:-1])) inDir = inDir[:-1]...
b80e6b784d4ee459d7d6b911d9fed8cfde3a20eb
3,617,797
def _parseLinks(response, rel): """ Parses an HTTP response's ``Link`` headers of a given relation, according to the Corelight API specification. response (requests.Response): The response to parse the ``Link`` headers out of. rel (str): The link relation type to parse; all other relations are...
73a4f2a7e981b335aa511e5e311ef7290a7695e3
3,617,798
def compute_crop_box(bound_box: dict): """Computes the coordinates to crop an image based on the provided bound_box and the SCALE variable. The input only describes a box around the mask (or area where the mask would be), and the width and height could could be different. The output box will be a square...
66bee6c87b5cb21ed1091f62bab1b9dd940e43d9
3,617,799