content stringlengths 4 20k |
|---|
"""
Contains common test fixtures used to run unit tests.
"""
import random
import sys
# This is needed so Python can find test_tools on the path.
sys.path.append('../..')
from test_tools.fixtures.common import *
@pytest.fixture()
def make_faces():
def _make_faces(count, has_details=False, is_celebrity=False, is... |
__author__ = 'e0d'
"""
Retrieves AWS Auto-scaling lifecycle messages from and SQS queue and processes them. For
the LifeCycleTransition type of autoscaling:EC2_INSTANCE_TERMINATING, ec2 instances are inspected
for an ok_to_retire tag. If that tag exists, the termination state transition is continued, if not, the
lif... |
#!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
# create planes
# Create the RenderWindow, Renderer
#
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer( ren )
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# create pipeline
#
pl3d = vtk.vtkPLOT3... |
import time
from functools import wraps
TEST_LOG_BOOL = True
def test_logger(msg):
print 'test-' + msg
def comprehensive_logger(logger=None, logging=True, maxlength=250, nowait=False):
'''
Decorator to log the inputs and outputs of functions, as well as the time taken
to run the function.
Requires: time, fu... |
"""Tests for EncodeBase64 and DecodeBase64."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import base64
import numpy as np
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework ... |
"""Imported from the recipes section of the itertools documentation.
All functions taken from the recipes section of the itertools library docs
[1]_.
Some backward-compatible usability improvements have been made.
.. [1] http://docs.python.org/library/itertools.html#recipes
"""
from collections import deque
from ite... |
"""common library code for socorro modules"""
class DatabaseError(Exception):
"""When querying a storage system failed. """
pass
class MissingArgumentError(Exception):
"""When a mandatory argument is missing or empty. """
def __init__(self, arg):
self.arg = arg
def __str__(self):
... |
from telemetry import benchmark
from telemetry.page import page
from telemetry.page import page_set
from telemetry.page import page_test
from webgl_conformance import WebglConformanceValidator
from webgl_conformance import conformance_harness_script
from webgl_conformance import conformance_path
robustness_harness_s... |
import urllib
from paste.httpheaders import CONTENT_LENGTH
from paste.httpheaders import CONTENT_TYPE
from paste.httpheaders import LOCATION
from paste.httpexceptions import HTTPFound
from paste.request import parse_dict_querystring
from paste.request import parse_formvars
from paste.request import construct_url
fro... |
#! /usr/bin/env python
from __future__ import absolute_import
import json
import re
import os
import logging
from validator import Validator
from validator.utils import find_file
PAT = re.compile('\s+-->\s(?P<fname>.*?):(?P<lnum>\d+):(?P<col>\d+)')
logger = logging.getLogger('validator')
class Cargo(Validator):
... |
"""Fake ConsoleProxy driver for tests."""
class FakeConsoleProxy(object):
"""Fake ConsoleProxy driver."""
@property
def console_type(self):
return 'fake'
def setup_console(self, context, console):
"""Sets up actual proxies."""
pass
def teardown_console(self, context, con... |
"""
================================
SVM Exercise
================================
A tutorial exercise for using different SVM kernels.
This exercise is used in the :ref:`using_kernels_tut` part of the
:ref:`supervised_learning_tut` section of the :ref:`stat_learn_tut_index`.
"""
print(__doc__)
import numpy as np
i... |
import unittest
from mock import Mock
from mock import patch
from airflow import DAG, configuration
from airflow.contrib.operators.jira_operator import JiraOperator
from airflow.models.connection import Connection
from airflow.utils import db
from airflow.utils import timezone
DEFAULT_DATE = timezone.datetime(2017, ... |
__version__ = "2.0.1"
def detect(aBuf):
import universaldetector
u = universaldetector.UniversalDetector()
u.reset()
u.feed(aBuf)
u.close()
return u.result |
import os
import unittest
import tempfile
import shutil
import Namcap.package
import Namcap.ruleclass
class PkgbuildTest(unittest.TestCase):
"""
This class is the template for unit tests concerning PKGBUILD rules.
The setUp() method should set self.rule to a class derived from
PkgbuildRule.
The usual way to do ... |
import sqlalchemy
def downgrade_trust_table_with_column_drop(meta, migrate_engine):
trust_table = sqlalchemy.Table('trust', meta, autoload=True)
# delete trusts with a limited use count, we are downgrading so uses
# will not be tracked anymore.
d = trust_table.delete(trust_table.c.remaining_uses >= 0)... |
# encoding: utf-8
"""
System command aliases.
Authors:
* Fernando Perez
* Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License.
#
# The full license is in the file... |
import unittest
from apache_beam.metrics.cells import DistributionData
from apache_beam.metrics.execution import MetricKey
from apache_beam.metrics.execution import MetricsContainer
from apache_beam.metrics.execution import MetricsEnvironment
from apache_beam.metrics.metric import Metrics
from apache_beam.metrics.metr... |
from mojo.events import addObserver, removeObserver
class each(object):
def __init__(self, countable):
self.countable = countable
def __call__(self, fn):
try:
ticks = fn.ticks
except:
ticks = 0
def wrapped(ui, *args, **kwargs):
count = le... |
import os
import sys
def main(args):
if '--dev' in args:
use_devel_version = True
ape_devel_arg = '--dev'
args.remove('--dev')
djpl_install = 'pip install -e git+https://github.com/henzk/django-productline#egg=django-productline'
else:
use_devel_version = False
... |
"""Test Access Control Role"""
from ggrc.access_control.role import AccessControlRole
from integration.ggrc import TestCase
from integration.ggrc.api_helper import Api
from integration.ggrc.models.factories import random_str
from integration.ggrc.generator import ObjectGenerator
class TestAccessControlRole(TestCase)... |
"""
Group Configuration Tests.
"""
import json
from unittest import skipUnless
from django.conf import settings
from contentstore.utils import reverse_course_url
from contentstore.views.component import SPLIT_TEST_COMPONENT_TYPE
from contentstore.views.course import GroupConfiguration
from contentstore.tests.utils impo... |
"""Defines `AdditiveExternalRegretOptimizer`.
This optimizer minimizes a `ConstrainedMinimizationProblem` by introducing
Lagrange multipliers, and using `tf.train.Optimizer`s to jointly optimize over
the model parameters and Lagrange multipliers.
For the purposes of constrained optimization, at least in theory,
exter... |
# -*- coding: utf-8 -*-
# A secured Python sandbox for tempson
import re, ast, copy
import RestrictedPython
class vm (object):
def _evalExp(self, exp, context):
# protect context
_context = copy.deepcopy(context)
_context['_getattr_'] = self._hook_getattr
_context['_getitem_'] = se... |
import ConfigParser
import StringIO
import unittest
from test import test_support
class TestCaseBase(unittest.TestCase):
def newconfig(self, defaults=None):
if defaults is None:
self.cf = self.config_class()
else:
self.cf = self.config_class(defaults)
return self.c... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.galaxy.token import GalaxyToken
from ansible.module_utils.six import string_types
from ansible.module_utils.six.moves.urllib.error impo... |
from security_monkey.exceptions import AccountNameExists
from security_monkey.views import AuthenticatedService
from security_monkey.views import ACCOUNT_FIELDS
from security_monkey.datastore import Account, AccountType
from security_monkey.datastore import User
from security_monkey.account_manager import get_account_b... |
import os, sys
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__)))
from distutils.core import setup
import wtforms
setup(
name='WTForms',
version=wtforms.__version__,
url='http://wtforms.simplecodes.com/',
license='BSD',
author='Thomas Johansson, James Crasta',
author_email='<EMAIL>... |
"""Tests for the CSS TALES formatter."""
__metaclass__ = type
from testtools.matchers import Equals
from lp.testing import (
test_tales,
TestCase,
)
from lp.testing.layers import DatabaseFunctionalLayer
class TestCSSFormatter(TestCase):
layer = DatabaseFunctionalLayer
def test_select(self):
... |
import logging
from collections import namedtuple
from timeit import default_timer as timer
from typing import Callable, List, Tuple
import dill
import mlflow
import numpy as np
import tempfile
from lcs.metrics import basic_metrics
TrialMetrics = namedtuple('TrialMetrics', ['steps', 'reward'])
logger = logging.get... |
from boto.resultset import ResultSet
from boto.cloudformation.stack import Capability
class Template(object):
def __init__(self, connection=None):
self.connection = connection
self.description = None
self.template_parameters = None
self.capabilities_reason = None
self.capabi... |
#!/usr/bin/env python
import sys
import simplejson as json
from docker_registry.core import exceptions
import docker_registry.storage as storage
store = storage.load()
def walk_all_tags():
for namespace_path in store.list_directory(store.repositories):
for repos_path in store.list_directory(namespace_... |
from . import grammar, token, tokenize
class PgenGrammar(grammar.Grammar):
pass
class ParserGenerator(object):
def __init__(self, filename, stream=None):
close_stream = None
if stream is None:
stream = open(filename)
close_stream = stream.close
self.filename = ... |
#!/usr/bin/env python
#
# Generated Thu Jun 11 18:43:54 2009 by generateDS.py.
#
import sys
import getopt
from string import lower as str_lower
from xml.dom import minidom
from xml.dom import Node
#
# User methods
#
# Calls to the methods in these classes are generated by generateDS.py.
# You can replace these metho... |
from __future__ import absolute_import
from django.contrib import admin
from django.core.paginator import Paginator
from .models import (Child, Parent, Genre, Band, Musician, Group, Quartet,
Membership, ChordsMusician, ChordsBand, Invitation, Swallow)
site = admin.AdminSite(name="admin")
class CustomPaginator(... |
from robot.utils import Matcher, NormalizedDict, setter
class Tags(object):
def __init__(self, tags=None):
self._tags = tags
@setter
def _tags(self, tags):
if not tags:
return ()
if isinstance(tags, basestring):
tags = (tags,)
return self._normaliz... |
from .device import VirtualDevice
from .xmlbuilder import XMLProperty
class VirtualInputDevice(VirtualDevice):
virtual_device_type = VirtualDevice.VIRTUAL_DEV_INPUT
TYPE_MOUSE = "mouse"
TYPE_TABLET = "tablet"
TYPE_KEYBOARD = "keyboard"
TYPE_DEFAULT = "default"
TYPES = [TYPE_MOUSE, TYPE_TABLET... |
import time
from openerp.osv import fields, osv
class account_partner_reconcile_process(osv.osv_memory):
_name = 'account.partner.reconcile.process'
_description = 'Reconcilation Process partner by partner'
def _get_to_reconcile(self, cr, uid, context=None):
cr.execute("""
SELEC... |
import os
import re
import sys
from distutils import log
import xml.dom.pulldom
import shlex
import locale
import codecs
import unicodedata
import warnings
from setuptools.compat import unicode
from xml.sax.saxutils import unescape
try:
import urlparse
except ImportError:
import urllib.parse as... |
from scipy import stats
import numpy as np
from numpy.testing import assert_almost_equal, assert_
def test_kde_1d():
#some basic tests comparing to normal distribution
np.random.seed(8765678)
n_basesample = 500
xn = np.random.randn(n_basesample)
xnmean = xn.mean()
xnstd = xn.std(ddof=1)
# ... |
import os, sys
from xml.dom import minidom
scriptDir = os.path.abspath(sys.path[0])
wkroot = os.path.abspath(os.path.join(scriptDir, "../.."))
def getWebCoreFilesDict():
"""
This method parses the WebCoreSources.bkl file, which has a list of all sources not specific
to any port, and returns the result as ... |
from nose.tools import *
from snowclient.querybuilder import *
import unittest
import tests.test_helpers as test_helpers
class TestSnowClientQuery(unittest.TestCase):
def test_date_range(self):
qb = QueryBuilder()
# snow api sucks balls https://community.servicenow.com/thread/181519
e = "sys_create... |
"""Unit tests for python.py."""
import os
import unittest
from python import PythonChecker
class PythonCheckerTest(unittest.TestCase):
"""Tests the PythonChecker class."""
def test_init(self):
"""Test __init__() method."""
def _mock_handle_style_error(self):
pass
check... |
from itools.core import proto_lazy_property
from itools.datatypes import DateTime, Date, Time
from itools.gettext import MSG
from itools.html import stream_is_empty
from itools.web import STLView
# Import from ikaaro
from autoedit import AutoEdit
from autoform import AutoForm
from config import Configuration
from conf... |
import copy
import inspect
from importlib import import_module
from django.db import router
from django.db.models.query import QuerySet
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class BaseManager(object):
# Tracks each time a Manager i... |
from __future__ import absolute_import
from django.core.exceptions import FieldError
from django.test import TestCase
from .models import Author, Article
def pks(objects):
""" Return pks to be able to compare lists"""
return [o.pk for o in objects]
class CustomColumnRegression(TestCase):
def setUp(sel... |
#!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt4 stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess import Popen, PIPE
import glob
import operator
import os
OUT_CPP="src/qt/SaveCoinstrings.cpp"
EMPTY=['""']
def parse_po(text):
"""
Parse 'po' format pr... |
"""Webster is a self validating dict object for python.
It expands upon dict's capability by allowing you
to pass in a validation dict object with either types or
regular expression values.
Then you can use it for validation by using it as a condition or get
back a detailed error response.
import Webster
# create a... |
from __future__ import absolute_import
import sys
import pip
from pip.compat import stdlib_pkgs
from pip.basecommand import Command
from pip.operations.freeze import freeze
from pip.wheel import WheelCache
DEV_PKGS = ('pip', 'setuptools', 'distribute', 'wheel')
class FreezeCommand(Command):
"""
Output ins... |
import re
import pep8
UNDERSCORE_IMPORT_FILES = []
mutable_default_argument_check = re.compile(
r"^\s*def .+\((.+=\{\}|.+=\[\])")
string_translation = re.compile(r"[^_]*_\(\s*('|\")")
log_translation = re.compile(
r"(.)*LOG\.(audit|error|info|warn|warning|critical|exception)\(\s*('|\")")
translated_log = r... |
import pytest
from tests.common.impala_test_suite import ImpalaTestSuite
from tests.common.test_dimensions import create_single_exec_option_dimension
class TestLocalFileSystem(ImpalaTestSuite):
@classmethod
def get_workload(self):
return 'functional-query'
@classmethod
def add_test_dimensions(cls):
su... |
from tempest_lib.common.utils import data_utils as utils
from tempest.api.volume import base
from tempest import test
class QosSpecsV2TestJSON(base.BaseVolumeAdminTest):
"""Test the Cinder QoS-specs.
Tests for create, list, delete, show, associate,
disassociate, set/unset key V2 APIs.
"""
@cla... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class TelewebionIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?telewebion\.com/#!/episode/(?P<id>\d+)'
_TEST = {
'url': 'http://www.telewebion.com/#!/episode/1263668/',
'info_dict': {
... |
"""TensorFlow Ops for Sequence to Sequence models (deprecated).
This module and all its submodules are deprecated. See
[contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md)
for migration instructions.
"""
from __future__ import absolute_import
from __future__ import division
fr... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.constants import TREE_DIR
from ansible.module_utils._text import to_bytes
from ansible.plugins.callback import CallbackBase
from ansible.utils.path import makedirs_safe
class CallbackModule(CallbackBase):
... |
"""Get basic information about gensim & dependencies (useful for bug-reporting).
Examples
--------
You can use it through python
.. sourcecode:: pycon
>>> from gensim.scripts.package_info import package_info
>>>
>>> info = package_info()
or using CLI interface
::
python -m gensim.scripts.package_i... |
"""Assorted backends for interfacing with your particular hardware.
"""
def _import_by_name(modname):
"""
>>> mod = _import_by_name('pypid.backend.melcor')
>>> 'MelcorBackend' in dir(mod)
True
>>> _import_by_name('pypid.backend.highly_unlikely')
Traceback (most recent call last):
...
... |
from __future__ import absolute_import
import mock
import unittest
import google.auth
import google.datalab
import google.datalab.stackdriver.monitoring as gcm
class TestCases(unittest.TestCase):
def test_make_client(self):
context = self._create_context()
client = gcm._utils.make_client(context)
sel... |
#!/usr/bin/env python
# vim: expandtab:tabstop=4:shiftwidth=4
"""
This is a script that gathers tags from instances and reports the status of the tags to zabbix
Usage:
ops-ec2-check-tags.py --aws-creds-profile profile1 --clusterid=testcluster --region=us-east-1
"""
# Ignoring module name
# pylint: disable=inval... |
"""urllib2 style build opener integrates with HTTPSConnection class from this
package.
"""
__author__ = "P J Kershaw"
__date__ = "21/12/10"
__copyright__ = "(C) 2011 Science and Technology Facilities Council"
__license__ = "BSD - see LICENSE file in top-level directory"
__contact__ = "<EMAIL>"
__revision__ = '$Id$'
imp... |
# -*- coding: utf-8 -*-
"""
werkzeug.local
~~~~~~~~~~~~~~
This module implements context-local objects.
:copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from functools import update_wrapper
from werkzeug.wsgi import ClosingIt... |
"""
Contains XML text for documents to be distributed
with the suds lib. Also, contains classes for accessing
these documents.
"""
from StringIO import StringIO
from logging import getLogger
log = getLogger(__name__)
#
# Soap section 5 encoding schema.
#
encoding = \
"""<?xml version="1.0" encoding="UTF-8"?>
<xs:s... |
from logging.config import fileConfig
from alembic import context
from sqlalchemy import create_engine, pool
from quantum.db import model_base
from quantum.openstack.common import importutils
DATABASE_QUOTA_DRIVER = 'quantum.extensions._quotav2_driver.DbQuotaDriver'
# this is the Alembic Config object, which provi... |
from __future__ import absolute_import
from . decompiler_common import TestDecompiler
##class TestDiscardDecompile(TestDecompiler):
## s = """
##def f(o, v, f):
## f(o, v)
## return o.x
##"""
## inputs = [[Dummy(), 1, dummySet], [Dummy(), 1.0, dummySet], [Dummy(), True, dummySet], [Dummy(), 'foo', dummySet]]
##
def... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import numpy as np
import ast
import re
import os
import logging
logger = logging.getLogger("logger")
def tvars_num():
logger.info("model variables:")
nvars = 0
for var in ... |
# Define critical settings and/or override defaults specified in
# settings.py. Copy this file to settings_local.py in the same
# directory as settings.py and edit. Any settings defined here
# will override those defined in settings.py
# Set this to point to your compiled checkout of caffe
caffevis_caffe_root =... |
#!/usr/bin/env python
import dpkt
import sys
import socket
from collections import defaultdict
from operator import itemgetter
def parse_ip4_udp(buf):
eth = dpkt.ethernet.Ethernet(buf)
if eth.type != dpkt.ethernet.ETH_TYPE_IP:
raise Exception('unhandled type: %s' % eth.type)
ip = eth.data
... |
"""
MultiGPU model similar to the one used in model tutorials. The model keeps
one copy of the weights on each device and handles syncing the parameters
across devices.
"""
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
i... |
"""Example of how to implement a low battery alarm in weewx.
*******************************************************************************
To use this alarm, add the following somewhere in your configuration file
weewx.conf:
[Alarm]
time_wait = 3600
count_threshold = 10
smtp_host = smtp.example.com
... |
import unittest
import logging
import struct
from struct import *
from nose.tools import *
from nose.plugins.skip import Skip, SkipTest
from ryu.ofproto import ether
from ryu.lib.packet.ethernet import ethernet
from ryu.lib.packet.packet import Packet
from ryu.lib.packet.arp import arp
from ryu.lib.packet.vlan import v... |
# coding: utf-8
'''
Created on 17 avr. 2010
a module to calculate different statistics on coranic text
@author: assem
'''
import re
import araby
__all__ = ['letters', 'diacritics', 'letter_count', 'hamza_count', 'words',
'gwords', 'sunletters', 'moonletters']
gword_pattern = re.compile( u"لله" )
GWORDS_FORMS = ... |
#!/data/home/gpadmin/greenplum-db-devel/ext/python/bin/python
import httplib
import optparse
import string
import sys
import time
class HTTPCli:
@staticmethod
def send_http_request(url_path, data, **headers):
parts = url_path.strip().split('/')
if len(parts) < 2 or parts[0] == '':
r... |
from django.contrib.gis.db import models
from django.contrib.postgres.fields import ArrayField, JSONField
from opencivicdata.core.models.base import (
OCDBase,
LinkBase,
OCDIDField,
RelatedBase,
RelatedEntityBase,
MimetypeLinkBase,
)
from opencivicdata.core.models import Jurisdiction
from .bill ... |
#
# shift_jis.py: Python Unicode Codec for SHIFT_JIS
#
# Written by Hye-Shik Chang <<EMAIL>>
#
import _codecs_jp, codecs
import _multibytecodec as mbc
codec = _codecs_jp.getcodec('shift_jis')
class Codec(codecs.Codec):
encode = codec.encode
decode = codec.decode
class IncrementalEncoder(mbc.M... |
from __future__ import division
__author__ = "Dan Knights"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Dan Knights", "Greg Caporaso", "Jai Ram Rideout"]
__license__ = "GPL"
__version__ = "1.8.0-dev"
__maintainer__ = "Dan Knights"
__email__ = "<EMAIL>"
import numpy as np
import matplotlib
matpl... |
from openerp import models, fields
class clv_lab_test(models.Model):
_inherit = 'clv_lab_test'
tag_ids = fields.Many2many('clv_tag',
'clv_lab_test_tag_rel',
'lab_test_id',
'tag_id',
'Ta... |
# django imports
from django.contrib import admin
# lfs imports
from lfs.catalog.models import Category
from lfs.catalog.models import FilterStep
from lfs.catalog.models import Image
from lfs.catalog.models import Product
from lfs.catalog.models import ProductAccessories
from lfs.catalog.models import Property
from lf... |
import ddt
from oslo_config import cfg
from oslo_serialization import jsonutils
import six
import webob
from manila.api.openstack import wsgi
from manila.common import constants
from manila import context
from manila import db
from manila import exception
from manila.share import api as share_api
from manila import te... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class MakersChannelIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?makerschannel\.com/.*(?P<id_type>video|production)_id=(?P<id>[0-9]+)'
_TEST = {
'url': 'http://makerschannel.com/en/zoomin/commu... |
"""Amazon SQS Transport.
Amazon SQS transport module for Kombu. This package implements an AMQP-like
interface on top of Amazons SQS service, with the goal of being optimized for
high performance and reliability.
The default settings for this module are focused now on high performance in
task queue situations where ... |
import copy
import unittest
from collections import Mapping, MutableMapping
from scrapy.utils.datatypes import CaselessDict, SequenceExclude
__doctests__ = ['scrapy.utils.datatypes']
class CaselessDictTest(unittest.TestCase):
def test_init_dict(self):
seq = {'red': 1, 'black': 3}
d = CaselessDic... |
""" Key factory for info keys. """
from collections import defaultdict
class Key(object):
""" A key object. """
def __init__(self, name, owner):
""" Initializer.
:param str name: name of key
:param class owner: key owner
"""
self._name = name
self._own... |
from nova import exception
from nova import test
from nova.virt import diagnostics
class DiagnosticsTests(test.NoDBTestCase):
def test_cpu_diagnostics_default(self):
cpu = diagnostics.CpuDiagnostics()
self.assertEqual(0, cpu.time)
def test_cpu_diagnostics(self):
cpu = diagnostics.Cpu... |
"""
Reference implementation server for Glance Registry
"""
import eventlet
import os
import sys
# Monkey patch socket and time
eventlet.patcher.monkey_patch(all=False, socket=True, time=True)
# If ../glance/__init__.py exists, add ../ to Python search path, so that
# it will override what happens to be installed in... |
"""
Get line authorship attribution from git.
Here's why this is somewhat challenging: ``git blame`` is designed to work on
one file at a time, with the implication that you know what file it's talking
about, since you gave it the filename. However, when you run together the
output from ``git ls-files | xargs -L1 git... |
# -*- coding: utf-8 -*-
import logging
import mock
import webtest_plus
import unittest
from nose.tools import * # noqa
from tests.base import DbTestCase
from flask import make_response
from pymongo.errors import CollectionInvalid, OperationFailure
from framework.flask import add_handlers
from framework.mongo impor... |
from __future__ import absolute_import
from __future__ import print_function
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolutio... |
"""
This module is for the miscellaneous GEOS routines, particularly the
ones that return the area, distance, and length.
"""
from ctypes import POINTER, c_double, c_int
from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory
from django.contrib.gis.geos.prototypes.errcheck import check_dbl, check_stri... |
import colorsys
import yaml
from bokeh.layouts import column, row, widgetbox
from bokeh.models import ColumnDataSource, HoverTool, CustomJS, Slider
from bokeh.plotting import figure, output_file, show, curdoc
from bokeh.themes import Theme
# for plot 2: create colour spectrum of resolution N and brightness I, return ... |
from AlgorithmImports import *
### <summary>
### This example demonstrates how to get access to futures history for a given root symbol.
### It also shows how you can prefilter contracts easily based on expirations, and inspect the futures
### chain to pick a specific contract to trade.
### </summary>
### <meta name="... |
"""
This module provides a large set of colormaps, functions for
registering new colormaps and for getting a colormap by name,
and a mixin class for adding color mapping functionality.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import o... |
from __future__ import unicode_literals
import webnotes
from webnotes import _, msgprint
def execute(filters=None):
if not filters: filters = {}
columns = get_columns()
data = get_entries(filters)
return columns, data
def get_columns():
return ["Journal Voucher:Link/Journal Voucher:140", "Account:Link/Accou... |
from __future__ import print_function
from bokeh.browserlib import view
from bokeh.document import Document
from bokeh.embed import file_html
from bokeh.models.glyphs import Patches
from bokeh.models import (
Plot, DataRange1d, ColumnDataSource, ResizeTool
)
from bokeh.resources import INLINE
from bokeh.sampledata... |
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Web Site"),
"icon": "fa fa-star",
"items": [
{
"type": "doctype",
"name": "Web Page",
"description": _("Content web page."),
},
{
"type": "doctype",
"name": "Web Form",
... |
import logging
import os
import re
import shlex
import subprocess
import sys
from time import sleep
from streamlink_cli.compat import is_win32, stdout
from streamlink_cli.constants import PLAYER_ARGS_INPUT_DEFAULT, PLAYER_ARGS_INPUT_FALLBACK, SUPPORTED_PLAYERS
from streamlink_cli.utils import ignored
if is_win32:
... |
"""
Solution to Project Euler problem by Joseph Jude
Webpage: http://tech.jjude.com/euler
Git Repo: https://github.com/jjude/euler
Problem 003: What is the largest prime factor of the number 600851475143?
WIL: Prime factorization
Ref: https://www.mathsisfun.com/prime-factorization.html
"Prime Factorization" is find... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.smv
~~~~~~~~~~~~~~~~~~~
Lexers for the SMV languages.
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, words
from pygments.token import Comment, Keyword... |
"""Provides TestStream for verifying streaming runner semantics."""
from abc import ABCMeta
from abc import abstractmethod
from apache_beam import coders
from apache_beam import pvalue
from apache_beam.transforms import PTransform
from apache_beam.transforms.window import TimestampedValue
from apache_beam.utils impor... |
import Image, ImageFilter
class _Enhance:
##
# Returns an enhanced image. The enhancement factor is a floating
# point value controlling the enhancement. Factor 1.0 always
# returns a copy of the original image, lower factors mean less
# colour (brightness, contrast, etc), and higher values more.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.