code
stringlengths
1
199k
""" Find the closest DMC colors for a hex color. Usage: python closest_colors.py <hexcolor> """ import sys from .. import color from .. import dmc_colors def main(): if len(sys.argv) < 2: sys.exit(__doc__) hex_color = sys.argv[1] rgb_color = color.RGBColorFromHexString(hex_color) print 'Given RGB color', rg...
""" """ from .register import get_registered_layers import axpy import flatten import argmax import reshape import roipooling import priorbox import permute import detection_out import normalize import select import crop import reduction custom_layers = get_registered_layers() def set_args(f, params, node=None): ""...
from nltk.book import * fdist1 = FreqDist(text1) fdist1.plot(50, cumulative=True)
def command(): return "edit-instance-vmware" def init_argument(parser): parser.add_argument("--instance-no", required=True) parser.add_argument("--instance-type", required=True) parser.add_argument("--key-name", required=True) parser.add_argument("--compute-resource", required=True) parser.add_a...
import os import time import ujson from django.conf import settings from django.http import HttpResponse from django.test import TestCase from mock import patch from typing import Any, Callable, Dict, List, Mapping, Tuple from zerver.lib.test_helpers import simulated_queue_client from zerver.lib.test_classes import Zul...
import datetime import json import re from six.moves import urllib import httmock import requests import six from girder.constants import SettingKey from tests import base def setUpModule(): base.enabledPlugins.append('oauth') base.startServer() def tearDownModule(): base.stopServer() class OauthTest(base.T...
import functools import os from perfkitbenchmarker import flags from perfkitbenchmarker import vm_util from perfkitbenchmarker.vm_util import POLL_INTERVAL FLAGS = flags.FLAGS flags.DEFINE_string('openstack_auth_url', os.environ.get('OS_AUTH_URL', 'http://localhost:5000'), ('Url ...
from linkedin import linkedin import easygui import sys reload(sys) sys.setdefaultencoding("utf-8") import requests def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) Mode = enum('PREVIEW', 'EDIT', 'REFRESH') mode = 0 paramslist = [] key...
"""Support for Lutron Caseta scenes.""" from typing import Any from homeassistant.components.scene import Scene from .const import BRIDGE_LEAP, DOMAIN as CASETA_DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Lutron Caseta scene platform. Adds scenes from the Caseta bri...
from __future__ import with_statement import logging import os import pipes import random import shutil import subprocess import sys import tempfile import time import commands import urllib2 from optparse import OptionParser from sys import stderr import shlex import getpass import threading import json identity_file ...
"""Tests for classification of real numbers.""" __author__ = 'Sean Lip' from core.tests import test_utils from extensions.rules import real class RealRuleUnitTests(test_utils.GenericTestBase): """Tests for rules operating on Real objects.""" def test_equals_rule(self): self.assertTrue(real.Equals(3).eva...
from __future__ import absolute_import, division, print_function, unicode_literals import os from builtins import str from textwrap import dedent from pants.backend.jvm.targets.jvm_app import JvmApp from pants.backend.jvm.targets.jvm_binary import JvmBinary from pants.base.exceptions import TargetDefinitionException fr...
import sys import ray import pytest from ray.test_utils import ( generate_system_config_map, wait_for_condition, wait_for_pid_to_exit, ) @ray.remote class Increase: def method(self, x): return x + 2 @ray.remote def increase(x): return x + 1 @pytest.mark.parametrize( "ray_start_regular", ...
""" Middleware that will provide Static Large Object (SLO) support. This feature is very similar to Dynamic Large Object (DLO) support in that it allows the user to upload many objects concurrently and afterwards download them as a single object. It is different in that it does not rely on eventually consistent contain...
from turnstile.checks import get_checks from turnstile.manager import get_commands CORE_COMMIT_MSG_CHECKS = ['branch_pattern', 'branch_release', 'branch_type', 'protect_master', 'specification'] CORE_SUBCOMMANDS = ['config', 'install', 'remove', 'specification', 'upgrade', 'version'] def test_checks(): checks = dic...
import gevent import socket from vnc_api.vnc_api import * from cfgm_common.vnc_kombu import VncKombuClient from config_db import * from cfgm_common.dependency_tracker import DependencyTracker from reaction_map import REACTION_MAP import svc_monitor class RabbitConnection(object): _REACTION_MAP = REACTION_MAP de...
from oslo_config import cfg from mistral.db.v2 import api as db_api from mistral.lang import parser as spec_parser from mistral.services import workbooks as wb_service from mistral.tests.unit import base cfg.CONF.set_default('auth_enable', False, group='pecan') WORKBOOK = """ --- version: '2.0' name: my_wb tags: [test]...
from neutron.plugins.ml2.drivers.l2pop import rpc as l2pop_rpc from neutron.plugins.ml2 import managers from neutron.plugins.ml2 import rpc as rpc from neutron_lib.agent import topics class Tunnel_Calls(object): """Common tunnel calls for L2 agent.""" def __init__(self): self._construct_rpc_stuff() ...
import proto # type: ignore __protobuf__ = proto.module( package="google.ads.googleads.v10.enums", marshal="google.ads.googleads.v10", manifest={"WebpageConditionOperatorEnum",}, ) class WebpageConditionOperatorEnum(proto.Message): r"""Container for enum describing webpage condition operator in web...
"""Big tensor games.""" from absl import logging # pylint:disable=unused-import import numpy as np from open_spiel.python.algorithms.adidas_utils.helpers import misc class TensorGame(object): """Tensor Game.""" def __init__(self, pt, seed=None): """Ctor. Inits payoff tensor (players x actions x ... np.array). ...
""" environ settings """ import environ BASE_DIR = environ.Path(__file__) - 4 ENV_VAR = environ.Env()
import os from library.connecter.ansible.yaml import Yaml_Base class Data_DB(Yaml_Base): def router(self, content, name, yaml_tpye='main', file_type='tasks', preserve=True, together=False, describe=''): ''' 检测yaml数据的语法是否正确,如果含有include或/和roles,将把这些存储在后端数据库中 :参数 content:内容 ...
import io from devstack import cfg from devstack import component as comp from devstack import log as logging from devstack import shell as sh from devstack import utils from devstack.components import db LOG = logging.getLogger("devstack.components.quantum") VSWITCH_PLUGIN = 'openvswitch' V_PROVIDER = "quantum.plugins...
import socket import sys import time import eventlet eventlet.monkey_patch() from oslo_config import cfg from oslo_log import log as logging import oslo_messaging from oslo_service import loopingcall from neutron.agent.l2.extensions import manager as ext_manager from neutron.agent import rpc as agent_rpc from neutron.a...
"""This API defines FeatureColumn abstraction. FeatureColumns provide a high level abstraction for ingesting and representing features in tf.learn Estimator models. FeatureColumns are the primary way of encoding features for pre-canned tf.learn Estimators. When using FeatureColumns with tf.learn models, the type of fea...
""" Most s2n integration tests are run against a variety of arguments. A "scenario" represents a specific set of inputs, such as address, cipher, version, etc. """ import itertools import multiprocessing import os from enum import Enum as BaseEnum from multiprocessing.pool import ThreadPool class Enum(BaseEnum): de...
import heapq, logging, os, re, socket, time, types from proton import dispatch, generate_uuid, PN_ACCEPTED, SASL, symbol, ulong, Url from proton import Collector, Connection, Delivery, Described, Endpoint, Event, Link, Terminus, Timeout from proton import Message, Handler, ProtonException, Transport, TransportException...
from pyspark_cassandra.util import as_java_object, as_java_array from pyspark.streaming.dstream import DStream from pyspark_cassandra.conf import WriteConf from pyspark_cassandra.util import helper from pyspark.serializers import AutoBatchedSerializer, PickleSerializer def saveToCassandra(dstream, keyspace, table, colu...
import errno import os import socketserver import threading from oslo_config import cfg from oslo_log import log as logging from oslo_serialization import jsonutils from octavia.api.drivers.driver_agent import driver_get from octavia.api.drivers.driver_agent import driver_updater CONF = cfg.CONF LOG = logging.getLogger...
"""Hyperparameter sweeps and configs for stage 1 of "abstract_reasoning_study". Are Disentangled Representations Helpful for Abstract Visual Reasoning? Sjoerd van Steenkiste, Francesco Locatello, Juergen Schmidhuber, Olivier Bachem. NeurIPS, 2019. """ from __future__ import absolute_import from __future__ import divisi...
"hey iam there yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyy"
from __future__ import unicode_literals import pyxb import pyxb.binding import pyxb.binding.saxer import io import pyxb.utils.utility import pyxb.utils.domutils import sys import pyxb.utils.six as _six _GenerationUID = pyxb.utils.utility.UniqueIdentifier('urn:uuid:773ffeee-c70b-11e6-9daf-00e1020040ea') _PyXBVersion = '...
from gbpservice.nfp.configurator.drivers.loadbalancer.v2.haproxy.octavia_lib.\ common import data_models class Interface(data_models.BaseDataModel): def __init__(self, id=None, compute_id=None, network_id=None, fixed_ips=None, port_id=None): self.id = id self.compute_id = comput...
from django.shortcuts import render from django.http import HttpResponse from django.utils import simplejson as json import ner def index(request): params = {'current': 'home'} return render(request, 'index.html', params) def name_entity_recognition(request): if request.method == 'GET': #Get the ar...
import os import shutil import tempfile import pytest import redact GCLOUD_PROJECT = os.getenv("GOOGLE_CLOUD_PROJECT") RESOURCE_DIRECTORY = os.path.join(os.path.dirname(__file__), "resources") @pytest.fixture(scope="module") def tempdir(): tempdir = tempfile.mkdtemp() yield tempdir shutil.rmtree(tempdir) de...
class RegisterPair: def __init__(self, name, register_high, register_low): self.name = name self.register_high = register_high self.register_low = register_low
""" flowlabels are abbreviations that can be used to identify a flow. Flows do not have a single unique attribute, which makes them difficult to identify. flows solve that problem. flowlabels have 2 parts: origin node index destination node index Example: flowlabel 1_2 means the ...
""" Ecks plugin to collect system memory usage information Copyright 2011 Chris Read (chris.read@gmail.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('organization', '0004_teacher_image'), ('courses', '0006_auto_20170914_2345'), ] operations = [ migrations.AddFie...
from touchdown.core import argument, resource, serializers from .provisioner import Provisioner class Output(resource.Resource): resource_name = "output" name = argument.String() provisioner = argument.Resource(Provisioner) class OutputAsString(serializers.Serializer): def __init__(self, resource): ...
from webfs import WebDirParser testDoc = """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> <title>Index of /ubuntu</title> </head> <body> <h1>Index of /ubuntu</h1> <pre><img src="/icons/blank.gif" alt="Icon "> <a href="?C=N;O=D">Name</a> <a href="?C=M;O=A">Last modified</...
from bacnet import BACNetTransform from cwmp import CWMPTransform from dns import DNSTransform from ftp import FTPTransform from http import HTTPTransform from http import HTTPWWWTransform from https import HTTPSTransform from https import HTTPSGetTransform from https import HTTPSWWWTransform from https import Heartble...
""" @author: ArcGIS for Intelligence @contact: defensesolutions@esri.com @company: Esri @version: 1.0 @description: Used to stage the apps for Movement Analysis @requirements: Python 2.7.x, ArcGIS 10.3.1 @copyright: Esri, 2015 """ import arcresthelper from arcresthelper import portalautomati...
from __future__ import absolute_import from traitsui.api import View, Item, VGroup, InstanceEditor, UItem, EnumEditor, \ RangeEditor, spring, HGroup, Group, ButtonEditor from pychron.core.ui.custom_label_editor import CustomLabel from pychron.core.ui.led_editor import LEDEditor from pychron.envisage.icon_button_edi...
__author__ = 'eveliotc' __license__ = 'See LICENSE' import alfred from alfred import Item import sys from subprocess import Popen, PIPE def json_to_obj(x): if isinstance(x, dict): return type('X', (), {k: json_to_obj(v) for k, v in x.iteritems()}) else: return x def join_query(dic): return '...
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2013 ARM Limited Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law...
from nativedroid.protobuf.java_signatures_pb2 import * __author__ = "Fengguo Wei" __copyright__ = "Copyright 2018, The Argus-SAF Project" __license__ = "Apache v2.0" def java_package_str(java_package_pb, delimiter): """ Return full string of a java package proto. :param JavaPackage java_package_pb: java_sig...
class Solution: def uniquePathsIII(self, grid: 'List[List[int]]') -> 'int': self.res = 0 R, C, E = len(grid), len(grid[0]), 1 for i in range(R): for j in range(C): if grid[i][j] == 1: x,y = (i, j) elif grid[i][j] == 2: end = (i, j) ...
from setuptools import setup, find_packages version = "__VERSION__" setup( name="swift_undelete", version=version, description='Undelete middleware for OpenStack Swift', license='Apache License (2.0)', author='Samuel N. Merritt', author_email='sam@swiftstack.com', url='https://github.com/swi...
import os import time import logging import math from parsl.channels import LocalChannel from parsl.launchers import SingleNodeLauncher from parsl.providers.cluster_provider import ClusterProvider from parsl.providers.lsf.template import template_string from parsl.providers.provider_base import JobState, JobStatus from...
''' fantastic Add-on This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the ...
All Terrain Life Vest- IEA Raspverry Pi Competition Entry import RPi.GPIO as GPIO import time import os GPIO.setmode (GPIO.BCM) GPIO.cleanup() GPIO.setwarnings(False) GPIO.setup(17,GPIO.OUT) GPIO.setup(04,GPIO.OUT) GPIO.setup(22, GPIO.IN) print("---------------") print("Button+GPIO") print("---------------") print GPIO...
import urllib from flask import Flask, Response, abort, request, send_file from flask_restful import Resource, Api from flask_cors import CORS, cross_origin import datetime import json import vacker.file_factory app = Flask(__name__) api = Api(app) file_factory = vacker.file_factory.FileFactory() CORS(app, resources={"...
"""Model defination for the RetinaNet Model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np from absl import logging import tensorflow.compat.v2 as tf from tensorflow.python.keras import backend from official.vision.d...
import logging from boto3.resources.factory import ResourceFactory from boto3.resources.model import ResourceModel from boto3.resources.base import ResourceMeta from boto3.docs import docstring from boto3.exceptions import ResourceLoadException from boto3.resources.factory import build_identifiers from functools import...
from PyCA.Core import * import PyCA.Common as common import numpy as np import matplotlib.pyplot as plt def SplatSafe(outMass, g, mass): mType = mass.memType() if mType == MEM_DEVICE: minmaxl = MinMax(mass) maxval = max([abs(x) for x in minmaxl]) if maxval > 2000.00: ...
import shutil import tempfile import numpy as np import os from os.path import getsize import pytest import yaml from util import PATH_TO_TESTS, seed, dummy_predict_with_threshold PATH_TO_ASSETS = os.path.join(PATH_TO_TESTS, 'assets') PATH_TO_RETINA_DIR = os.path.join(PATH_TO_ASSETS, 'recordings', 'retina') PATH_TO_RE...
def index_power(array, n): if n>=len(array): return -1 else: return array[n]**n if __name__ == '__main__': # These "asserts" using only for self-checking and not necessary for auto-testing assert index_power([1, 2, 3, 4], 2) == 9, "Square" assert index_power([1, 3, 10, 100], 3) == 1000000,...
import argparse from unittest.mock import patch, call import pytest from runners.nrfjprog import NrfJprogBinaryRunner from conftest import RC_KERNEL_HEX TEST_DEF_SNR = 'test-default-serial-number' # for mocking user input TEST_OVR_SNR = 'test-override-serial-number' EXPECTED_COMMANDS = { # NRF51: '1NNN': (...
"""Utilities for managing distrubtion strategies.""" from absl import flags from absl import logging import tensorflow.compat.v2 as tf flags.DEFINE_string('tpu', None, 'BNS address for the TPU') flags.DEFINE_bool('use_gpu', False, 'If True a MirroredStrategy will be used.') def get_strategy(tpu, use_gpu): """Utility ...
"""Tests for PrometheusStatsCollector.""" from absl import app from grr_response_core.stats import stats_test_utils from grr_response_server import prometheus_stats_collector from grr.test_lib import test_lib class PrometheusStatsCollectorTest(stats_test_utils.StatsCollectorTest): def _CreateStatsCollector(self): ...
from __future__ import absolute_import from collections import namedtuple import mock import pytest from kazoo.exceptions import NoNodeError from kafka_utils.util.config import ClusterConfig from kafka_utils.util.serialization import dump_json from kafka_utils.util.zookeeper import ZK MockGetTopics = namedtuple('MockGe...
import csv, sys mapping = {} totalTruth, totalTesting, hit, miss, errors = (0, 0, 0, 0, 0) with open(sys.argv[1], 'rb') as groundtruth: reader = csv.reader(groundtruth) for row in reader: totalTruth += 1 mapping[(row[1], row[2])] = row[0] with open(sys.argv[2], 'rb') as testing: reader = csv...
from sqlalchemy import MetaData from sqlalchemy import orm from sqlalchemy.orm import exc as orm_exc from sqlalchemy import Table def map(engine, models): meta = MetaData() meta.bind = engine if mapping_exists(models['instance']): return orm.mapper(models['instance'], Table('instances', meta, au...
from molotov.api import pick_scenario, scenario, get_scenarios, setup from molotov.tests.support import TestLoop, async_test class TestUtil(TestLoop): def test_pick_scenario(self): @scenario(weight=10) async def _one(self): pass @scenario(weight=90) async def _two(self): ...
""" IOStore class originated here https://github.com/BD2KGenomics/hgvm-graph-bakeoff-evaluations/blob/master/scripts/toillib.py and was then here: https://github.com/cmarkello/toil-lib/blob/master/src/toil_lib/toillib.py In a perfect world, this would be deprecated and replaced with Toil's stores. Actually did this her...
from conveyor.conveyorheat.common import exception from conveyor.conveyorheat.engine import attributes from conveyor.conveyorheat.engine import constraints from conveyor.conveyorheat.engine import properties from conveyor.conveyorheat.engine.resources.huawei.elb import elb_res_base from conveyor.i18n import _ class Lis...
import logging from constance import config from dateutil.relativedelta import relativedelta from rest_framework.authentication import SessionAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from rest_framework im...
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ibms', '0006_auto_20180813_1603'), ] operations = [ migrations.RenameField( model_name='serviceprioritymappings', old_name='costcentreName', new_name='costCentreName...
""" Python wrapper for functionality exposed in the TemcaGraph dll. @author: jayb """ from ctypes import * import logging import threading import time import os import sys import numpy as np from pytemca.image.imageproc import fit_sin from numpy.ctypeslib import ndpointer if sys.flags.debug: rel = "../x64/Debug/Te...
import numpy as np import mxnet as mx import random import math from mxnet.executor_manager import _split_input_slice from utils.image import tensor_vstack from segmentation.segmentation import get_segmentation_train_batch, get_segmentation_test_batch from PIL import Image from multiprocessing import Pool class TestDat...
import json from django.utils.translation import ugettext_lazy as _ from django.http import HttpResponse import django.views from django.template import defaultfilters as template_filters from horizon import tables from horizon import exceptions from cloudkittydashboard.api import cloudkitty as api from openstack_dashb...
from __future__ import absolute_import from __future__ import print_function from __future__ import division import tensorflow as tf from tensorforce import util, TensorForceError from tensorforce.core.optimizers import MetaOptimizer class SubsamplingStep(MetaOptimizer): """ The subsampling-step meta optimizer ...
from twisted.internet import defer from synapse.api.errors import AuthError, StoreError, SynapseError from synapse.http.servlet import RestServlet from ._base import client_v2_pattern, parse_json_dict_from_request class TokenRefreshRestServlet(RestServlet): """ Exchanges refresh tokens for a pair of an access t...
from unittest import mock from heat.common import exception from heat.common import template_format from heat.engine.resources.openstack.sahara import data_source from heat.engine import scheduler from heat.tests import common from heat.tests import utils data_source_template = """ heat_template_version: 2015-10-15 res...
""" Typically called by Cloud Scheduler with recipe JSON payload. Sample JSON POST payload: { "setup":{ "id":"", #string - Cloud Project ID for billing. "auth":{ "service":{}, #dict - Optional Cloud Service JSON credentials when task uses service. "user":{} #dict - Option...
from .linkstate import LinkState # noqa from .node.local_router_id import LocalRouterID # noqa from .node.name import NodeName # noqa from .node.isisarea import ISISArea # noqa from .node.sr_capabilities import SRCapabilities # noqa from .node.sr_algorithm import SRAlgorithm # noqa from .node.node_msd import N...
"""Support for the Italian train system using ViaggiaTreno API.""" import asyncio import logging import time import aiohttp import async_timeout import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity from homeassistant.const import ATTR_ATTRIBUTION, HTTP_OK, TIME_MINUTES impo...
import urllib, urllib2, sys, httplib url = "/MELA/REST_WS" HOST_IP="109.231.126.217:8180" if __name__=='__main__': connection = httplib.HTTPConnection(HOST_IP) description_file = open("./costTest.xml", "r") body_content = description_file.read() headers={ 'Content-Type':'application/...
""" @Author: yyg @Create: 2016MMDD @LastUpdate: 2016-12-15 HH:MM:SS @Version: 0.0 """ from json import load from logging import (Formatter, _defaultFormatter, exception, getLogger, FileHandler, basicConfig, StreamHandler) from cloghandler import ConcurrentRota...
from prob1 import hexToRaw, rawToHexLUT from prob2 import hex_xor import string letterFrequency = {} letterFrequency['A'] = .082; letterFrequency['B'] = .015; letterFrequency['C'] = .028; letterFrequency['D'] = .043; letterFrequency['E'] = .127; letterFrequency['F'] = .022; letterFrequency['G'] = .020; letterFrequency[...
""" ./e09asynctwostage.py http://camlistore.org 1 6 Found 10 urls http://camlistore.org/ frequencies: [('camlistore', 13), ...] ... First integer arg is depth, second is minimum word count. """ import re from sys import argv import asyncio from e01extract import canonicalize from e04twostage import print_popular_words ...
import json import random import requests import string import sys import time MOLD = {"name": "name1", "timestamp": '2014-12-01', "value": 100 } MOLD_DIMENSIONS = {"key1": None} def setup_metrics(argv): for a in range(100): MOLD_DIMENSIONS['key1'] = ( ''.join(random.samp...
import json import numbers import shutil from tempfile import mkdtemp import mock import operator import time import unittest import socket import os import errno import itertools import random import eventlet from collections import defaultdict from datetime import datetime import six from six.moves import urllib from...
"""Test suite for abdt_rbranchnaming.""" from __future__ import absolute_import import unittest import abdt_namingtester import abdt_rbranchnaming class Test(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def make_naming(self): return abdt_rbranchnaming.Naming() ...
import difflib import inflect import itertools import logging import netaddr import os import re import toposort import yaml import hotcidr.state def inflect_a(s, p=inflect.engine()): x = p.plural(s) if p.compare(s, x) == 'p:s': return s return p.a(s) logging.basicConfig(format='%(levelname)s %(mess...
"""Base abstract class for metadata builders.""" import abc _ABC = abc.ABCMeta("ABC", (object,), {"__slots__": ()}) class MetadataBuilder(_ABC): """Abstract base class for metadata builders.""" @abc.abstractmethod def get_metadata(self): """Returns the current metadata as a dictionary.""" @abc.a...
""" Demonstrate use of pysnmp walks """ import sys import re from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() devip = sys.argv.pop(1) errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('server', 'galileo', 1), cmdgen.UdpTransportTarg...
""" Copyright 2015 Akamai Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law ...
"""## Functions for working with arbitrarily nested sequences of elements. This module can perform operations on nested structures. A nested structure is a Python sequence, tuple (including `namedtuple`), or dict that can contain further sequences, tuples, and dicts. The utilities here assume (and do not check) that th...
"""Tests for the Tensorboard debugger data plugin.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import json from tensorflow.python.platform import test from tensorflow.tensorboard.plugins.debugger import plugin as debugger_plugin clas...
from neutron import context as n_ctx from sqlalchemy.orm import exc as orm_exc from gbpservice.neutron.db.grouppolicy.extensions import group_proxy_db from gbpservice.neutron.tests.unit.services.grouppolicy import ( test_extension_driver_api as test_ext_base) class ExtensionDriverTestCaseMixin(object): def test...
from charms_openstack.plugins.adapters import ( CephRelationAdapter, ) from charms_openstack.plugins.classes import ( BaseOpenStackCephCharm, CephCharm, PolicydOverridePlugin, ) from charms_openstack.plugins.trilio import ( TrilioVaultCharm, TrilioVaultSubordinateCharm, TrilioVaultCharmGhost...
from oslo_log import log as logging from pypowervm import exceptions as pvm_exc from pypowervm.tasks import scsi_mapper as pvm_smap from taskflow import task from taskflow.types import failure as task_fail from nova import exception from nova.virt.powervm import media from nova.virt.powervm import mgmt LOG = logging.ge...
""" Class representing an exponential distribution, allowing us to sample from it. """ from numpy.random import exponential def exponential_draw(lambdax): scale = 1.0 / lambdax return exponential(scale=scale,size=None) ''' import matplotlib.pyplot as plt import numpy as np scale = 2. s = [exponential_draw(1./sc...
"""Model for an Oppia exploration.""" import datetime from constants import constants import core.storage.base_model.gae_models as base_models import core.storage.user.gae_models as user_models import feconf from google.appengine.ext import ndb class ExplorationSnapshotMetadataModel(base_models.BaseSnapshotMetadataMode...
''' The function cache system allows for data to be stored on the master so it can be easily read by other minions ''' import copy import logging import salt.crypt import salt.payload log = logging.getLogger(__name__) def _auth(): ''' Return the auth object ''' if 'auth' not in __context__: __co...
from setuptools import find_packages from os import path, environ import io import os import re from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import numpy as np def read(*names, **kwargs): with io.open( os.path.join(os.path.dirname(__file__), *...
from __future__ import absolute_import, division, print_function, unicode_literals import os import unittest from mock import patch from nose.tools import assert_equals, assert_raises import pygenie from ..utils import FakeRunningJob assert_equals.__self__.maxDiff = None @pygenie.adapter.genie_3.set_jobname def set_job...
"""Unit tests for annotations.""" import tvm from tvm import relay import pytest def test_on_device_via_string(): x = relay.Var("x") call = relay.annotation.on_device(x, "cuda") assert isinstance(call, relay.Call) assert len(call.args) == 1 assert call.args[0] == x assert call.attrs.virtual_devi...