code stringlengths 1 199k |
|---|
import importlib
import inspect
import os
import re
import sys
import tempfile
from io import StringIO
from pathlib import Path
from django.conf.urls import url
from django.core import mail
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import DatabaseError, connection
from django.shortcut... |
import os, tempfile, zipfile, tarfile, logging
from django.core.servers.basehttp import FileWrapper
from django.http import HttpResponse
def get_zipfile(file_list):
"""
Create a ZIP file on disk and transmit it in chunks of 8KB,
without loading the whole file into memory.
"""
temp = tempfile.Tempora... |
"""
sphinx.builders.gettext
~~~~~~~~~~~~~~~~~~~~~~~
The MessageCatalogBuilder class.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
from os import path, walk
from codecs import open
from time import... |
import logging as loggers
import numpy as np
import theano.tensor as T
from theano.tensor.nnet import conv
from theano.tensor.signal import downsample
from deepy.utils import build_activation, UniformInitializer
from deepy.layers.layer import NeuralLayer
logging = loggers.getLogger(__name__)
class Convolution(NeuralLay... |
"""
Test rpc_util functions
"""
__author__ = 'Dan Gunter <dkgunter@lbl.gov>'
__date__ = '8/28/15'
import re
from nose.tools import raises
from doekbase.data_api import rpc_util
from thrift.Thrift import TType
class Metadata:
"""SAMPLE object for testing validation, etc.
Default metadata for an object.
Attri... |
from __future__ import print_function
"""
Place in ~/.octoprint/plugins & restart server to test:
* python_checker and python_updater mechanism
* demotion of pip and python setup.py clean output that
gets written to stderr but isn't as severe as that would
look
Plugin will always demand to update itself, mu... |
from __future__ import print_function
import os,FreeCAD,Mesh
__title__="FreeCAD 3DS importer"
__author__ = "Yorik van Havre"
__url__ = "http://www.freecadweb.org"
DEBUG = True
def check3DS():
"checks if collada if available"
global dom3ds
dom3ds = None
try:
from Dice3DS import dom3ds
except ... |
from pilasengine.actores.actor import Actor
class Bala(Actor):
""" Representa una bala que va en línea recta. """
def __init__(self, pilas, x=0, y=0, rotacion=0, velocidad_maxima=9,
angulo_de_movimiento=90):
"""
Construye la Bala.
:param x: Posición x del proyectil.
... |
from lxml import etree
from tempest.common import rest_client
from tempest.common import xml_utils
from tempest import config
from tempest import exceptions
CONF = config.CONF
class AggregatesClientXML(rest_client.RestClient):
TYPE = "xml"
def __init__(self, auth_provider):
super(AggregatesClientXML, se... |
from .stats import TotalStat
from .visitor import SuiteVisitor
class TotalStatistics(object):
"""Container for total statistics."""
def __init__(self):
#: Instance of :class:`~robot.model.stats.TotalStat` for critical tests.
self.critical = TotalStat('Critical Tests')
#: Instance of :cla... |
import sys
from libcloud.utils.py3 import httplib
from io import BytesIO
from mock import Mock
from libcloud.utils.py3 import StringIO
from libcloud.utils.py3 import b
from libcloud.storage.base import StorageDriver
from libcloud.storage.base import DEFAULT_CONTENT_TYPE
from libcloud.test import unittest
from libcloud.... |
"""
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... |
"""Tests for distutils.command.check."""
import os
import textwrap
import unittest
from test.support import run_unittest
from distutils.command.check import check, HAS_DOCUTILS
from distutils.tests import support
from distutils.errors import DistutilsSetupError
try:
import pygments
except ImportError:
pygments ... |
"""Set of utility functions for working with OS commands.
Functions in this module return the command string. These commands are composed but not executed.
"""
import os
from subprocess import call
HADOOP_CONF_DIR = '/etc/hadoop/conf'
def encrypt(key_file):
"""
Encrypt the data from stdin and write output to stdo... |
"""login is not nullable
Revision ID: 105c1c44ff70
Revises: 2003c675a267
Create Date: 2013-12-09 10:52:50.646000
"""
revision = '105c1c44ff70'
down_revision = '2003c675a267'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - p... |
"""
========================
Broadcasting over arrays
========================
The term broadcasting describes how numpy treats arrays with different
shapes during arithmetic operations. Subject to certain constraints,
the smaller array is "broadcast" across the larger array so that they
have compatible shapes. Broadca... |
"""
Custom test runner
If args or options, we run the testsuite as quickly as possible.
If args but no options, we default to using the spec plugin and aborting on
first error/failure.
If options, we ignore defaults and pass options onto Nose.
Examples:
Run all tests (as fast as possible)
$ ./runtests.py
Run all unit t... |
from setuptools import setup
import pybvc
setup(
name='pybvc',
version=pybvc.__version__,
description='A python library for programming your network via the Brocade Vyatta Controller (BVC)',
long_description=open('README.rst').read(),
author='Elbrys Networks',
author_email='jeb@elbrys.com',
... |
"""
Implementation of various trading strategies.
"""
from cointrol.core.models import (
Order, TradingSession,
RelativeStrategyProfile, FixedStrategyProfile
)
class TradeAction:
BUY, SELL = Order.BUY, Order.SELL
def __init__(self, action, price):
self.action = action
self.price = price
... |
from __future__ import absolute_import
import sys
import types
from contextlib import contextmanager
from kombu.utils.encoding import str_to_bytes
from celery import signature
from celery import states
from celery import group
from celery.backends.cache import CacheBackend, DummyClient
from celery.exceptions import Imp... |
import logging
import unittest
import sys
sys.path.insert(0, '..')
sys.path.insert(0, '../pynipap')
sys.path.insert(0, '../nipap')
sys.path.insert(0, '../nipap-cli')
from nipap.backend import Nipap
from nipap.authlib import SqliteAuth
from nipap.nipapconfig import NipapConfig
from pynipap import AuthOptions, VRF, Pool,... |
from __future__ import division, print_function, unicode_literals, \
absolute_import
import os
import unittest
from pymatgen.io.lammps.sets import LammpsInputSet
__author__ = 'Kiran Mathew'
__email__ = 'kmathew@lbl.gov'
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..",
... |
from __future__ import absolute_import
import flask
import auth
import model
import util
from main import app
yahoo_config = dict(
access_token_url='https://api.login.yahoo.com/oauth/v2/get_token',
authorize_url='https://api.login.yahoo.com/oauth/v2/request_auth',
base_url='https://query.yahooapis.com/',
consum... |
from __future__ import unicode_literals
import formatter
import io
import sys
import time
import portage
from portage import os
from portage import _encodings
from portage import _unicode_encode
from portage.output import xtermTitle
from _emerge.getloadavg import getloadavg
if sys.hexversion >= 0x3000000:
basestring =... |
from __future__ import absolute_import
from __future__ import print_function
from future.builtins import range
import re
import sys
from twisted.enterprise import adbapi
from twisted.internet import defer
from twisted.python import log
from buildbot.process.buildstep import LogLineObserver
from buildbot.steps.shell imp... |
import re
from weboob.capabilities.base import UserError
from weboob.capabilities.calendar import CapCalendarEvent, CATEGORIES, BaseCalendarEvent
from weboob.capabilities.video import CapVideo, BaseVideo
from weboob.capabilities.collection import CapCollection, CollectionNotFound, Collection
from weboob.capabilities.ci... |
"""Support for Z-Wave sensors."""
from homeassistant.components.sensor import DEVICE_CLASS_BATTERY, DOMAIN, SensorEntity
from homeassistant.const import DEVICE_CLASS_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
f... |
from pysandesh_example.gen_py.vn.ttypes import VirtualNetwork, VNInfo, VirtualNetworkResp, \
VirtualNetworkAll, VNStats, VirtualNetworkAllResp
def VirtualNetwork_handle_request(self, sandesh):
vn_stats = VNStats(in_pkts=10, out_pkts=20, in_bytes=1024, out_bytes=2048)
vms = ['vm1', 'vm2', 'vm3']
if ... |
import time
import mysql.connector
from pyspider.database.base.projectdb import ProjectDB as BaseProjectDB
from pyspider.database.basedb import BaseDB
from .mysqlbase import MySQLMixin
class ProjectDB(MySQLMixin, BaseProjectDB, BaseDB):
__tablename__ = 'projectdb'
def __init__(self, host='localhost', port=3306,... |
"""Utilities for testing `LinearOperator` and sub-classes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
import numpy as np
import six
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.p... |
"""Define constants for the SimpliSafe component."""
from datetime import timedelta
DOMAIN = "simplisafe"
DATA_CLIENT = "client"
DEFAULT_SCAN_INTERVAL = timedelta(seconds=30)
TOPIC_UPDATE = "update" |
"""Spanning Tree Protocol."""
import dpkt
class STP(dpkt.Packet):
__hdr__ = (
('proto_id', 'H', 0),
('v', 'B', 0),
('type', 'B', 0),
('flags', 'B', 0),
('root_id', '8s', ''),
('root_path', 'I', 0),
('bridge_id', '8s', ''),
('port_id', 'H', 0),
... |
from email import utils
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart |
"""
A classifier model that decides which label to assign to a token on
the basis of a tree structure, where branches correspond to conditions
on feature values, and leaves correspond to label assignments.
"""
from __future__ import print_function, unicode_literals, division
from collections import defaultdict
from nlt... |
import glob
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness
from openmc.statepoint import StatePoint
class SourcepointTestHarness(TestHarness):
def _test_output_created(self):
"""Make sure statepoint.* files have been created."""
statepoint = glob.glob(os.p... |
import logging
from django.core.management.base import BaseCommand
from readthedocs.projects import tasks
from readthedocs.api.client import api
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Build documentation using the API and not hitting a database.
Usage::
./manage.py update_... |
import unittest
from chainer import cuda
from chainer import initializers
from chainer import testing
from chainer.testing import attr
import numpy
@testing.parameterize(*testing.product({
'target': [
initializers.Uniform,
initializers.LeCunUniform,
initializers.HeUniform,
initialize... |
from test import support
from test.support import bigaddrspacetest, MAX_Py_ssize_t
import unittest
import operator
import sys
class StrTest(unittest.TestCase):
@bigaddrspacetest
def test_concat(self):
s1 = 'x' * MAX_Py_ssize_t
self.assertRaises(OverflowError, operator.add, s1, '?')
@bigaddrs... |
from searchv2.tests.test_builders import *
from searchv2.tests.test_models import *
from searchv2.tests.test_utils import *
from searchv2.tests.test_views import * |
from __future__ import print_function
import fixpath
import colorama
from colorama import Fore, Back, Style
from random import randint, choice
from string import printable
FORES = [ Fore.BLACK, Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.CYAN, Fore.WHITE ]
BACKS = [ Back.BLACK, Back.RED, Back.GREEN... |
import json
import unittest
import mock
from django.http import HttpResponseBadRequest
from base import (assert_auth_CREATE, assert_auth_READ, assert_auth_UPDATE, assert_auth_DELETE,
assert_auth_EXECUTE)
from pulp.server.exceptions import InvalidValue, MissingResource, MissingValue, OperationPostponed... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import fnmatch
import os
import re
import itertools
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleParserError
from ansible.inventory.data import InventoryData
from ansible.mo... |
""" IPython extension: new prefilters for output grabbing
Provides
var = %magic blah blah
var = !ls
"""
import IPython.ipapi
from IPython.genutils import *
ip = IPython.ipapi.get()
import re
def hnd_magic(line,mo):
""" Handle a = %mymagic blah blah """
#cmd = genutils.make_quoted_expr(mo.group('syscmd'))
#m... |
import sys
from fs.opener import opener
from fs.commands.runner import Command
from fs.utils import print_fs
class FSTree(Command):
usage = """fstree [OPTION]... [PATH]
Recursively display the contents of PATH in an ascii tree"""
def get_optparse(self):
optparse = super(FSTree, self).get_optparse()
... |
from superdesk.resource import Resource
class FormattersResource(Resource):
"""Formatters schema"""
endpoint_name = 'formatters'
resource_methods = ['GET', 'POST']
item_methods = []
resource_title = endpoint_name
schema = {
'article_id': {
'type': 'string',
'requi... |
"""
Global variables for onedrive_d.
"""
import os
import sys
import logging
import atexit
import json
from calendar import timegm
from datetime import timezone, datetime, timedelta
from pwd import getpwnam
from . import od_ignore_list
config_instance = None
logger_instance = None
update_last_run_timestamp = False
DATE... |
"""
Handle lease database updates from DHCP servers.
"""
from __future__ import print_function
import os
import sys
import traceback
from oslo_config import cfg
from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import importutils
from nova.conductor import rpcapi as conductor_... |
"""Allows to configure a switch using RPi GPIO."""
import logging
import voluptuous as vol
from homeassistant.components.switch import PLATFORM_SCHEMA
from homeassistant.components import rpi_gpio
from homeassistant.const import DEVICE_DEFAULT_NAME
from homeassistant.helpers.entity import ToggleEntity
import homeassist... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.base.payload import Payload
from pants.base.target import Target
class Resources(Target):
"""A set of files accessible as resources from the JVM classpath.... |
"""Base classes and utilities for image datasets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import io
import os
import numpy as np
from tensor2tensor.data_generators import generator_utils
from tensor2tensor.data_generators import problem
from tensor... |
"""Tests for the module module, which contains Module and related classes."""
import os
import unittest
from tvcm import fake_fs
from tvcm import module
from tvcm import resource_loader
from tvcm import project as project_module
class ModuleIntegrationTests(unittest.TestCase):
def test_module(self):
fs = fake_fs.... |
from lxml import etree
import os, sys, logging, subprocess
from os.path import realpath, dirname
import xapian
sys.path.append('/home/liza/threepress')
from threepress import settings
db_dir = 'db/'
main_db = 'threepress'
logging.basicConfig(level=logging.WARNING)
indexer = xapian.TermGenerator()
stemmer = xapian.Stem(... |
from src.platform.jboss.interfaces import WebConsoleInterface
class FPrint(WebConsoleInterface):
def __init__(self):
super(FPrint, self).__init__()
self.version = "5.0" |
"""
requests.models
~~~~~~~~~~~~~~~
This module contains the primary objects that power Requests.
"""
import os
from datetime import datetime
from .hooks import dispatch_hook, HOOKS
from .structures import CaseInsensitiveDict
from .status_codes import codes
from .auth import HTTPBasicAuth, HTTPProxyAuth
from .packages.... |
from test_support import verbose
import strop, sys
def test(name, input, output, *args):
if verbose:
print 'string.%s%s =? %s... ' % (name, (input,) + args, output),
f = getattr(strop, name)
try:
value = apply(f, (input,) + args)
except:
value = sys.exc_type
if value != outp... |
import datetime as dt
from calendar import timegm
import dbus, dbus.mainloop.glib
from gi.repository import GObject as gobject
from hamster.lib import Fact
from hamster.lib import trophies
def from_dbus_fact(fact):
"""unpack the struct into a proper dict"""
return Fact(fact[4],
start_time = dt.... |
""" Handlers for OpenID Connect provider. """
from django.conf import settings
from django.core.cache import cache
from courseware.access import has_access
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.lang_pref import LANGUAGE_KEY
from openedx.core.djan... |
import sys
import os
import subprocess
def runtests():
fail = 0
for test in os.listdir("."):
if test.startswith("tst_") and test.endswith(".py"):
if 0 != subprocess.call(["./" + test]):
fail += 1
print test, "failed!"
if not fail:
return 0
ret... |
from builtins import range
import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from tests import pyunit_utils
from h2o import H2OFrame
import numpy as np
import numpy.random
import scipy.stats
from sklearn import ensemble
from sklearn.metrics import roc_auc_score
from h2o.estimators.gbm import H2... |
from cinder.backup.driver import BackupDriver
from cinder.openstack.common import log as logging
LOG = logging.getLogger(__name__)
class FakeBackupService(BackupDriver):
def __init__(self, context, db_driver=None):
super(FakeBackupService, self).__init__(context, db_driver)
def backup(self, backup, volu... |
import unittest
from cStringIO import StringIO
from pysal.core.util.shapefile import noneMax, noneMin, shp_file, shx_file, NullShape, Point, PolyLine, MultiPoint, PointZ, PolyLineZ, PolygonZ, MultiPointZ, PointM, PolyLineM, PolygonM, MultiPointM, MultiPatch
import os
import pysal
class TestNoneMax(unittest.TestCase):
... |
import numpy as np
from dipy.data import default_sphere
from dipy.tracking.propspeed import ndarray_offset, eudx_both_directions
from numpy.testing import (assert_array_almost_equal, assert_equal,
assert_raises, run_module_suite)
def stepped_1d(arr_1d):
# Make a version of `arr_1d` which ... |
from osv import fields, osv
from tools.translate import _
class event_confirm_registration(osv.osv_memory):
"""
Confirm Event Registration
"""
_name = "event.confirm.registration"
_description = "Confirmation for Event Registration"
_columns = {
'msg': fields.text('Message', readonly=Tru... |
import mms
import unittest
from mooseutils import fuzzyAbsoluteEqual
class TestOutflow(unittest.TestCase):
def test(self):
df1 = mms.run_spatial('advection-outflow.i', 7, y_pp=['L2u', 'L2v'])
fig = mms.ConvergencePlot(xlabel='Element Size ($h$)', ylabel='$L_2$ Error')
fig.plot(df1,
... |
from __future__ import absolute_import
import os
import csv
import json
from io import BytesIO
import tempfile
import shutil
from six.moves.urllib.parse import urlparse
from zope.interface.verify import verifyObject
from twisted.trial import unittest
from twisted.internet import defer
from scrapy.crawler import Crawler... |
import struct
import binascii
import dns.exception
import dns.rdata
from dns._compat import text_type
class NSEC3PARAM(dns.rdata.Rdata):
"""NSEC3PARAM record
@ivar algorithm: the hash algorithm number
@type algorithm: int
@ivar flags: the flags
@type flags: int
@ivar iterations: the number of it... |
from binsearch import BinSearch
from nzbclub import NZBClub
from nzbindex import NZBIndex
from bs4 import BeautifulSoup
from couchpotato.core.helpers.variable import getTitle, splitString, tryInt
from couchpotato.core.helpers.encoding import simplifyString
from couchpotato.environment import Env
from couchpotato.core.l... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: kinesis_stream
short_description: Manage a Kinesis Stream.
desc... |
from gwpy.plot import Plot
plot = Plot(noise, signal, data, separate=True, sharex=True, sharey=True)
plot.gca().set_epoch(0)
plot.show() |
from __future__ import with_statement
import unittest
import pysqlite2.dbapi2 as sqlite
did_rollback = False
class MyConnection(sqlite.Connection):
def rollback(self):
global did_rollback
did_rollback = True
sqlite.Connection.rollback(self)
class ContextTests(unittest.TestCase):
def setU... |
import mxnet as mx
from mxnet.test_utils import *
from data import get_avazu_data
from linear_model import *
import argparse
import os
parser = argparse.ArgumentParser(description="Run sparse linear classification " \
"with distributed kvstore",
... |
from datetime import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
class TestModel(models.Model):
text = models.CharField(max_length=10, default=_('Anything'))
class Company(models.Model):
name = models.CharField(max_length=50)
date_added = models.DateTimeFiel... |
from django.apps import AppConfig
class LibraryConfig(AppConfig):
name = 'library' |
from django.core.exceptions import PermissionDenied
def popup_status(request):
return '_popup' in request.REQUEST or 'pop' in request.REQUEST
def selectfolder_status(request):
return 'select_folder' in request.REQUEST
def popup_param(request):
if popup_status(request):
return "?_popup=1"
else:
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat import unittest, mock
from ansible.errors import AnsibleError
from ansible.plugins.cache import FactCache, CachePluginAdjudicator
from ansible.plugins.cache.base import BaseCacheModule
from ansible.plugins.cache.me... |
import base64
import time
from lxml import etree
from openerp.osv import fields
from openerp.osv import osv
from openerp import tools
from openerp.tools.translate import _
MAX_LEVEL = 15
AVAILABLE_STATES = [
('draft', 'New'),
('cancel', 'Cancelled'),
('open', 'In Progress'),
('pending', 'Pending'),
... |
"""
NL2BR Extension
===============
A Python-Markdown extension to treat newlines as hard breaks; like
GitHub-flavored Markdown does.
Usage:
>>> import markdown
>>> print markdown.markdown('line 1\\nline 2', extensions=['nl2br'])
<p>line 1<br />
line 2</p>
Copyright 2011 [Brian Neal](http://deathofagrem... |
import glob
import sys
sys.path.append('gen-py.twisted')
sys.path.insert(0, glob.glob('../../lib/py/build/lib*')[0])
from tutorial import Calculator
from tutorial.ttypes import InvalidOperation, Operation
from shared.ttypes import SharedStruct
from zope.interface import implements
from twisted.internet import reactor
f... |
"""Class for Roomba devices."""
import logging
from homeassistant.components.vacuum import SUPPORT_FAN_SPEED
from .irobot_base import SUPPORT_IROBOT, IRobotVacuum
_LOGGER = logging.getLogger(__name__)
ATTR_BIN_FULL = "bin_full"
ATTR_BIN_PRESENT = "bin_present"
FAN_SPEED_AUTOMATIC = "Automatic"
FAN_SPEED_ECO = "Eco"
FAN... |
from ....testing import assert_equal
from ..postproc import TrackMerge
def test_TrackMerge_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
output_file=dict(argstr='%s',
posit... |
import sublime, sublime_plugin
import re
def match(rex, str):
m = rex.match(str)
if m:
return m.group(0)
else:
return None
class HtmlCompletions(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
# Only trigger within HTML
if not view.... |
"""
Tests for Discussion API views
"""
from datetime import datetime
import json
from urlparse import urlparse
import ddt
import httpretty
import mock
from pytz import UTC
from django.core.urlresolvers import reverse
from rest_framework.test import APIClient
from discussion_api.tests.utils import (
CommentsServiceM... |
from django.conf.urls import url
from openstack_dashboard.dashboards.project.networks.ports import views
from openstack_dashboard.dashboards.project.networks.ports.extensions. \
allowed_address_pairs import views as addr_pairs_views
PORTS = r'^(?P<port_id>[^/]+)/%s$'
urlpatterns = [
url(PORTS % 'detail', views.... |
"""
Tests For Scheduler weights.
"""
from nova import context
from nova import exception
from nova.openstack.common.fixture import mockpatch
from nova.scheduler import weights
from nova import test
from nova.tests import matchers
from nova.tests.scheduler import fakes
class TestWeighedHost(test.NoDBTestCase):
def t... |
from __future__ import absolute_import
from .formatting import ConditionalFormatting
from .rule import Rule |
from django.conf.urls import url
from wagtail.admin.views import page_privacy, pages
app_name = 'wagtailadmin_pages'
urlpatterns = [
url(r'^add/(\w+)/(\w+)/(\d+)/$', pages.create, name='add'),
url(r'^add/(\w+)/(\w+)/(\d+)/preview/$', pages.PreviewOnCreate.as_view(), name='preview_on_add'),
url(r'^usage/(\w+... |
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from calibre.gui2.convert.azw3_output_ui import Ui_Form
from calibre.gui2.convert import Widget
font_family_model = None
class PluginWidget(Widget, Ui_Form):
... |
import logging
INSTANCES_DIR = '/etc/jormungandr.d'
START_MONITORING_THREAD = False
SQLALCHEMY_DATABASE_URI = 'postgresql://navitia:navitia@localhost/jormun_test'
PUBLIC = True
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0
REDIS_PASSWORD = None
CACHE_DISABLED = False
AUTH_CACHE_TTL = 300
ERROR_HANDLER_FILE = ... |
"""SavedModel simple save functionality."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.saved_model import builder
from tensorflow.python.saved_model import signature_constants
from tensor... |
from . import statement |
from __future__ import unicode_literals
import webnotes
from webnotes.utils import flt, cstr
from webnotes import msgprint
from webnotes.model.controller import DocListController
status_map = {
"Contact": [
["Replied", "communication_sent"],
["Open", "communication_received"]
],
"Job Applicant": [
["Replied", ... |
import httplib
import urllib
import time
import re
from tweepy.error import TweepError
from tweepy.utils import convert_to_utf8_str
from tweepy.models import Model
re_path_template = re.compile('{\w+}')
def bind_api(**config):
class APIMethod(object):
path = config['path']
payload_type = config.get(... |
MODULE_DESCRIPTION = "Web pages" |
"""Unit tests for the urlutils library."""
__revision__ = "$Id$"
from invenio.testutils import InvenioTestCase
from cgi import parse_qs
from invenio.config import CFG_SITE_URL
from invenio.testutils import make_test_suite, run_test_suite
from invenio.urlutils import (create_AWS_request_url,
... |
"""
Tests related to the Microsites feature
"""
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from nose.plugins.attrib import attr
from courseware.tests.helpers import LoginEnrollmentTestCase
from course_modes.models import CourseMode
from ... |
class Output:
'Output interface'
def __init__(self, output):
self._on_blank_line = True
self._output = output
self._flag = False
def write(self, lines):
'Writes lines (a string) '
# assume we are not on a blank line
self._write(lines)
def _write(self, line... |
from . import website |
"""
Solve the unique lowest-cost assignment problem using the
Hungarian algorithm (also known as Munkres algorithm).
"""
import numpy as np
def linear_assignment(X):
"""Solve the linear assignment problem using the Hungarian algorithm.
The problem is also known as maximum weight matching in bipartite graphs.
... |
from abc import ABC, abstractmethod
from calendar import timegm
from enum import Enum
import glob
import re
import time
NO_COL_FAMILY = 'DB_WIDE'
class DataSource(ABC):
class Type(Enum):
LOG = 1
DB_OPTIONS = 2
TIME_SERIES = 3
def __init__(self, type):
self.type = type
@abstra... |
from test import test_support
test_support.requires('audio')
from test.test_support import verbose, findfile, TestFailed, TestSkipped
import errno
import fcntl
import ossaudiodev
import os
import sys
import select
import sunaudio
import time
import audioop
try:
from ossaudiodev import AFMT_S16_NE
except ImportError... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.