content string |
|---|
#! /usr/bin/env python
from __future__ import print_function
from openturns import *
TESTPREAMBLE()
RandomGenerator.SetSeed(0)
try:
# We create a numerical math function
myFunction = NumericalMathFunction(
('E', 'F', 'L', 'I'), ('y',), ('-F*L^3/(3.*E*I)',))
dim = myFunction.getInputDimension()
... |
from skin import app_theme
from dtk.ui.progressbar import ProgressBar
class NewProgressBar(ProgressBar):
def __init__(self):
ProgressBar.__init__(self)
def set_text(self, text):
pass
def set_fraction(self, value):
if 0.0 <= value <= 1.0:
print ":value:", va... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class account_open_closed_fiscalyear(osv.osv_memory):
_name = "account.open.closed.fiscalyear"
_description = "Choose Fiscal Year"
_columns = {
'fyear_id': fields.many2one('account.fiscalyear', \
... |
import os
import sys
from distutils.sysconfig import get_python_lib
from setuptools import find_packages, setup
# Warn if we are installing over top of an existing installation. This can
# cause issues where files that were deleted from a more recent Django are
# still present in site-packages. See #18115.
overlay_wa... |
from __future__ import unicode_literals
import frappe
from frappe import _, throw
import frappe.utils.user
from frappe.permissions import check_admin_or_system_manager
from frappe.model.db_schema import type_map
def execute(filters=None):
user, doctype = filters.get("user"), filters.get("doctype")
validate(user, doc... |
"""Unit tests for MockDRT."""
import io
import sys
import unittest
from webkitpy.common.system.systemhost_mock import MockSystemHost
from webkitpy.layout_tests.port import mock_drt
from webkitpy.layout_tests.port import port_testcase
from webkitpy.layout_tests.port import test
from webkitpy.layout_tests.port.factory ... |
"""SCons.Tool.suncc
Tool-specific initialization for Sun Solaris (Forte) CC and cc.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010... |
#!/usr/bin/python
#
# Sched-credit tests modified from SEDF tests
#
import re
from XmTestLib import *
paramsRE = re.compile(r'^[^ ]* *[^ ]* *([^ ]*) *([^ ]*)$')
def get_sched_credit_params(domain):
status, output = traceCommand("xm sched-credit -d %s | tail -1" %
domain.getName... |
"""Tests for utils.py."""
import unittest
from protorpc import messages
from . import utils
class UtilsTests(unittest.TestCase):
"""Comprehensive test for the endpoints_proto_datastore.utils module."""
def testIsSubclass(self):
"""Tests the utils.IsSubclass method."""
self.assertTrue(utils.IsSubclass... |
"""Ce fichier contient la classe Message, définie plus bas."""
class Message:
"""Cette classe représente un message de log stockée par la fil
d'attente du Logger.
"""
def __init__(self, niveau, message, formate):
"""Un message de log contient :
- un niveau d'erreur (int)
... |
"""
Exception definitions.
"""
class UnsupportedVersion(Exception):
"""Indicates that the user is trying to use an unsupported
version of the API.
"""
pass
class InvalidAPIVersion(Exception):
pass
class CommandError(Exception):
pass
class AuthorizationFailure(Exception):
pass
class... |
import copy
import os
import tempfile
from oslo_log import log as logging
from oslo_utils import excutils
from pypowervm import const as pvm_const
from pypowervm.tasks import scsi_mapper as tsk_map
from pypowervm.tasks import storage as tsk_stg
from pypowervm.tasks import vopt as tsk_vopt
from pypowervm import util as... |
"""Implementations of unittest features from the future."""
# Use unittest2 if it's available, otherwise unittest. This gives us
# back-ported features for 2.6.
try:
import unittest2 as unittest
except ImportError:
import unittest
def unittest_has(method):
"""Does `unittest.TestCase` have `method` defin... |
"""text and font classes, helps everyone to text"""
import pygame, pygame.font, gfx
#old versions of SysFont were buggy
if pygame.ver <= '1.6.1':
from mysysfont import SysFont
else:
SysFont = pygame.font.SysFont
FontPool = {}
def initialize():
pygame.font.init()
return 1
class Font:
def __i... |
{
'name': 'Customer References',
'category': 'Website',
'summary': 'Publish Your Customer References',
'version': '1.0',
'description': """
OpenERP Customer References
===========================
""",
'author': 'OpenERP SA',
'depends': [
'crm_partner_assign',
'website_partner... |
"""
We're using snmpsim to simulate various target devices for our tests.
Before we do anything, we should probably make sure it's actually running
"""
import pytest
from subprocess import run, PIPE
SNMP_TEST_SRV_HOST = '127.0.0.1:10000'
SYSDESCR_OID = '.1.3.6.1.2.1.1.1.0'
@pytest.fixture(scope="session", autouse=... |
import errno
import os
import tempfile
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.exceptions import SuspiciousOperation, ImproperlyConfigured
class SessionStore(SessionBase):
"""
Implements a file based session store.
"""
... |
from __future__ import print_function
import time, sys, signal, atexit
from upm import pyupm_grovewater as upmGrovewater
def main():
# Instantiate a Grove Water sensor on digital pin D2
myWaterSensor = upmGrovewater.GroveWater(2)
## Exit handlers ##
# This function stops python from printing a stacktr... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec
from ansible.module_utils.basic import A... |
from warnings import warn
from pyimzml.ontology.ontology import lookup_and_convert_cv_param, convert_xml_value, convert_term_name
XMLNS_PREFIX = "{http://psi.hupo.org/ms/mzml}"
def _deep_pretty(obj):
if isinstance(obj, list):
return [_deep_pretty(item) for item in obj]
if isinstance(obj, dict):
... |
"""
Management command `manage_group` is used to idempotently create Django groups
and set their permissions by name.
"""
from django.apps import apps
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
f... |
import re
class Link:
"""
This class represents a file link from within a string given by the
output of some software tool. A link contains a reference to a file, the
line number within the file and the boundaries within the given output
string that should be marked as a link.
"""
def __in... |
import os
import csv
class Reader(object):
"""
This is an abstract class and not to be used as is.
Expects the text files start with a header
"""
INPUT_DELIMITER='\t'
OUTPUT_DELIMITER='\t'
def __init__(self, filename=None):
self._filename=filename
self._filehandle=None... |
import pandas_vectors as pv
import pandas as pd
import numpy as np
import unittest
class PvTest(unittest.TestCase):
def test_indexer(self):
self.assertListEqual(pv.indexer('a'), ['a_x', 'a_y', 'a_z'])
self.assertListEqual(pv.indexer(['a']), ['a_x', 'a_y', 'a_z'])
self.assertListEqual(pv.in... |
""" Common tools used by plugins implementing search plugin api """
from __future__ import unicode_literals, division, absolute_import
import re
from unicodedata import normalize
from flexget.utils.titles.parser import TitleParser
def clean_symbols(text):
"""Replaces common symbols with spaces. Also normalize un... |
"""Store global configuration information"""
import os
import sys
import socket
# The current version of duplicity
version = "0.7.17"
# Prefix for all files (appended before type-specific prefixes)
file_prefix = ""
# Prefix for manifest files only
file_prefix_manifest = ""
# Prefix for archive files only
file_pre... |
""" Testing mio5_utils Cython module
"""
from __future__ import division, print_function, absolute_import
import sys
from io import BytesIO
cStringIO = BytesIO
import numpy as np
from nose.tools import (assert_true, assert_equal, assert_raises)
from numpy.testing import (assert_array_equal, run_module_suite)
fro... |
import unittest
from ...compatibility import StringIO
from ..helperfunctions import _xml_to_list
from ...workbook import Workbook
class TestAssembleWorkbook(unittest.TestCase):
"""
Test assembling a complete Workbook file.
"""
def test_assemble_xml_file(self):
"""Test writing a workbook with ... |
"""Test script for the binhex C module
Uses the mechanism of the python binhex module
Based on an original test by Roger E. Masse.
"""
import binhex
import os
import unittest
from test import support
class BinHexTestCase(unittest.TestCase):
def setUp(self):
self.fname1 = support.TESTFN + "1"
... |
from shinken_test import *
class TestConfig(ShinkenTest):
# setUp is inherited from ShinkenTest
def test_satellite_failed_check(self):
print "Create a Scheduler dummy"
r = self.conf.realms.find_by_name('Default')
creation_tab = {'scheduler_name': 'scheduler-1', 'address': '0.0.0.0', ... |
'''
Float Layout
============
:class:`FloatLayout` honors the :attr:`~kivy.uix.widget.Widget.pos_hint`
and the :attr:`~kivy.uix.widget.Widget.size_hint` properties of its children.
.. only:: html
.. image:: images/floatlayout.gif
:align: right
.. only:: latex
.. image:: images/floatlayout.png
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import distutils.spawn
import os
import os.path
import subprocess
import traceback
from ansible import constants as C
from ansible.errors import AnsibleError
from ansible.module_utils.six.moves import shlex_quote
from ansible.modu... |
"""
This module defines export functions for decision trees.
"""
# Authors: Gilles Louppe <<EMAIL>>
# Peter Prettenhofer <<EMAIL>>
# Brian Holt <<EMAIL>>
# Noel Dawe <<EMAIL>>
# Satrajit Gosh <<EMAIL>>
# Trevor Stephens <<EMAIL>>
# License: BSD 3 clause
import numpy as np
... |
import os
import shutil
from copyrighter.CRCopyright import CRCopyright
class CRFile:
def __init__(self, context, file):
self.dirty = False
self.context = context
self.abs_path = context.get_path_of_file(file)
self.file_ext = os.path.splitext(self.ab... |
from boto.ec2.ec2object import EC2Object
class InstanceType(EC2Object):
"""
Represents an EC2 VM Type
:ivar name: The name of the vm type
:ivar cores: The number of cpu cores for this vm type
:ivar memory: The amount of memory in megabytes for this vm type
:ivar disk: The amount of disk space... |
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_blobs
from sklearn.utils.class_weight import compute_class_weight
from sklearn.utils.class_weight import compute_sample_weight
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testin... |
import time
import datetime
try:
import boto.ec2
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# Find the most recent snapshot
def _get_snapshot_starttime(snap):
return datetime.datetime.strptime(snap.start_time, '%Y-%m-%dT%H:%M:%S.000Z')
def _get_most_recent_snapshot(snapshots, max_snapshot... |
from gobject import timeout_add_seconds
from datetime import datetime, timedelta
from os import listdir, remove
from os.path import join
from tempfile import mkstemp
from time import time
from ossupport import xclose
from plugins import Plugin, get_plugin_by_type
from support import die, warning
from proximateprotocol... |
"""Module implementing RNN Cells."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.util import nest
def _state_size_with_prefix(state... |
import json, errno
from twisted.web.resource import Resource, NoResource, ErrorPage
class SlydJsonResource(Resource):
"""Base Resource for Slyd Resources
This sets the content type to JSON and handles errors
"""
def render(self, request):
request.setResponseCode(200)
request.setHeade... |
# -*- coding: utf-8 -*-
"""
pygments.styles.manni
~~~~~~~~~~~~~~~~~~~~~
A colorful style, inspired by the terminal highlighting style.
This is a port of the style used in the `php port`_ of pygments
by Manni. The style is called 'default' there.
:copyright: Copyright 2006-2013 by the Pygments... |
"""
PLN Simple Deduction Agent Example
Demonstrates the simplest possible forward inference agent that implements
a chainer with one inference rule and one link type
For instructions, refer to the README for PLN.
"""
from opencog.cogserver import MindAgent
from opencog.atomspace import types
from pln.chainers import... |
from textwrap import dedent
from pants.backend.codegen.thrift.java.java_thrift_library import JavaThriftLibrary
from pants.backend.graph_info.tasks.dependees import ReverseDepmap
from pants.backend.jvm.targets.jar_library import JarLibrary
from pants.backend.jvm.targets.java_library import JavaLibrary
from pants.backe... |
"""
Acceptance tests for Studio related to edit/save peer grading interface.
"""
from ...fixtures.course import XBlockFixtureDesc
from ...pages.studio.import_export import ExportCoursePage
from ...pages.studio.component_editor import ComponentEditorView
from ...pages.studio.overview import CourseOutlinePage
from base_... |
class HostedZone(object):
def __init__(self, id=None, name=None, owner=None, version=None,
caller_reference=None):
self.id = id
self.name = name
self.owner = owner
self.version = version
self.caller_reference = caller_reference
def startElement(self, na... |
"""Utilities for working with pretty-printers."""
import gdb
import gdb.types
import re
import sys
if sys.version_info[0] > 2:
# Python 3 removed basestring and long
basestring = str
long = int
class PrettyPrinter(object):
"""A basic pretty-printer.
Attributes:
name: A unique string amon... |
from __future__ import print_function
#########################################################################################################################################################################
# 24/11/2017
#
# Reproduce the experimental comparison of Maurin et al (2015), considering the experiments of Fr... |
"""
The :mod:`sklearn.decomposition` module includes matrix decomposition
algorithms, including among others PCA, NMF or ICA. Most of the algorithms of
this module can be regarded as dimensionality reduction techniques.
"""
from .nmf import NMF, ProjectedGradientNMF
from .pca import PCA, RandomizedPCA
from .incrementa... |
import struct
import random
from packet_utils import *
from packet_base import packet_base
TYPE_ECHO_REPLY = 0
TYPE_DEST_UNREACH = 3
TYPE_SRC_QUENCH = 4
TYPE_REDIRECT = 5
TYPE_ECHO_REQUEST = 8
TYPE_TIME_EXCEED = 11
CODE_UNREACH_NET = 0
CODE_UNREACH_HOST = 1
CODE_UNREACH_PROTO = 2
CODE_UNREACH... |
import sys
from datetime import datetime
from indico.core.db import DBMgr
from MaKaC.common.indexes import IndexesHolder, CategoryDayIndex
def switchIndex():
if IndexesHolder()._getIdx().has_key("backupCategoryDate") and IndexesHolder()._getIdx().has_key("categoryDate"):
tmp = IndexesHolder()._getIdx()["b... |
from oslo.utils import timeutils
from ceilometer.network.services import base
from ceilometer.openstack.common.gettextutils import _
from ceilometer.openstack.common import log
from ceilometer import sample
LOG = log.getLogger(__name__)
class FirewallPollster(base.BaseServicesPollster):
"""Pollster to capture f... |
from openerp import models, fields, api, _
class AccountInvoice(models.Model):
"""Check on cancelling of an invoice"""
_inherit = 'account.invoice'
credit_policy_id = fields.Many2one(
'credit.control.policy',
string='Credit Control Policy',
help="The Credit Control Policy used for... |
import json
from .. import constants
ROUND = constants.DEFAULT_PRECISION
## THREE override function
def _json_floatstr(o):
if ROUND is not None:
o = round(o, ROUND)
return '%g' % o
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
_key_separator, _item_separator,... |
try:
from operator import methodcaller
except ImportError:
methodcaller = lambda name: lambda o: getattr(o, name)()
from django.forms.forms import NON_FIELD_ERRORS, Form
from django.forms.formsets import formset_factory
from django.forms.models import modelform_factory, _get_foreign_key, BaseInlineFormSet, Bas... |
"""Self-test suite for Crypto.PublicKey.ElGamal"""
__revision__ = "$Id$"
import unittest
from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex
from Crypto import Random
from Crypto.PublicKey import ElGamal
from Crypto.Util.number import *
from Crypto.Util.py3compat import *
class ElGamalTest(unitte... |
"""Middleware for course_wiki"""
from urlparse import urlparse
from django.conf import settings
from django.http import Http404
from django.shortcuts import redirect
from django.core.exceptions import PermissionDenied
from wiki.models import reverse
from courseware.courses import get_course_with_access
from courseware... |
"Módulo para manejo de archivos JSON"
__author__ = "Mariano Reingart (<EMAIL>)"
__copyright__ = "Copyright (C) 2011 Mariano Reingart"
__license__ = "GPL 3.0"
from decimal import Decimal
try:
import json
except ImportError:
try:
import simplejson as json
except:
print "para soporte de JSO... |
"""Bignum routines"""
import struct
# generic big endian MPI format
def bn_bytes(v, have_ext=False):
ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
def bn2bin(v):
s = bytearray()
i = bn_bytes(v)
while i > 0:
s.append((v >> ((i-1) * 8)) & 0xff)
i -... |
#!/usr/bin/python
# Most of these names are only available via PluginLoader so pylint doesn't
# know they exist
# pylint: disable=no-name-in-module
results = {}
# Test import with no from
import ansible.module_utils.foo0
results['foo0'] = ansible.module_utils.foo0.data
# Test depthful import with no from
import ansib... |
""" test the label propagation module """
import nose
import numpy as np
from sklearn.semi_supervised import label_propagation
from numpy.testing import assert_array_almost_equal
from numpy.testing import assert_array_equal
ESTIMATORS = [
(label_propagation.LabelPropagation, {'kernel': 'rbf'}),
(label_propa... |
"""
This config file runs the simplest dev environment using sqlite, and db-based
sessions. Assumes structure:
/envroot/
/db # This is where it'll write the database file
/edx-platform # The location of this repo
/log # Where we're going to write log files
"""
# We intentionally define lot... |
import traceback
import logger
#Incorporadas las funciones loads() y dumps() para json y simplejson
def loads(*args, **kwargs):
try:
#logger.info("tvalacarta.core.jsontools loads Probando json incluido en el interprete")
import json
return to_utf8(json.loads(*args, **kwargs))
except Im... |
from openerp.report.render.rml2pdf import utils
import copy
import base64
import cStringIO
import re
from reportlab.lib.utils import ImageReader
_regex = re.compile('\[\[(.+?)\]\]')
utils._regex = re.compile('\[\[\s*(.+?)\s*\]\]',re.DOTALL)
class html2html(object):
def __init__(self, html, localcontext):
s... |
"""
Provides a sensor to track various status aspects of a UPS.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.nut/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_S... |
"""
Tests for the command-line scripts in the top-level I{bin/} directory.
Tests for actual functionality belong elsewhere, written in a way that doesn't
involve launching child processes.
"""
from os import devnull, getcwd, chdir
from sys import executable
from subprocess import PIPE, Popen
from twisted.trial.unitt... |
import unittest, threading
import zookeeper, zktestbase
class ClientidTest(zktestbase.TestBase):
"""Test whether clientids work"""
def setUp(self):
pass
def testclientid(self):
cv = threading.Condition()
self.connected = False
def connection_watcher(handle, typ... |
# coding=utf-8
import time
import math
import multiprocessing
import os
import random
import sys
import signal
try:
from setproctitle import getproctitle, setproctitle
except ImportError:
setproctitle = None
from diamond.utils.signals import signal_to_exception
from diamond.utils.signals import SIGALRMExcept... |
import unittest
import os
import fudge
from fudge.inspector import arg
from fabric.contrib import project
class UploadProjectTestCase(unittest.TestCase):
"""Test case for :func: `fabric.contrib.project.upload_project`."""
fake_tmp = "testtempfolder"
def setUp(self):
fudge.clear_expectations()... |
# conding: utf-8
import datetime
from datetime import timedelta
from django.core.urlresolvers import reverse
from . import TestBase, CashForm, Cash, make_validated_form, create_cash
class HomeViewTest(TestBase):
def setUp(self):
self.login()
self.url = reverse('statement:home')
self.res... |
from argparse import ArgumentParser
def build_opts(transformers=None):
opts = ArgumentParser()
opts.add_argument(dest='filename', help='Filename or release name to guess', nargs='*')
naming_opts = opts.add_argument_group("Naming")
naming_opts.add_argument('-t', '--type', dest='type', default=None,
... |
try:
import gitlab
HAS_GITLAB_PACKAGE = True
except:
HAS_GITLAB_PACKAGE = False
class GitLabUser(object):
def __init__(self, module, git):
self._module = module
self._gitlab = git
def addToGroup(self, group_id, user_id, access_level):
if access_level == "guest":
... |
from pyasn1.error import PyAsn1Error
from pysnmp.error import PySnmpError
class SmiError(PySnmpError, PyAsn1Error): pass
class MibLoadError(SmiError): pass
class MibNotFoundError(MibLoadError): pass
class MibOperationError(SmiError):
def __init__(self, **kwargs): self.__outArgs = kwargs
def __str__(self): ret... |
"""
WSGI config for dj project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setti... |
"""Fichier contenant l'ordre Feu."""
from secondaires.navigation.equipage.signaux import *
from ..ordre import *
class Feu(Ordre):
"""Ordre feu.
Cet ordre demande au matelot de faire feu avec le canon précisé. Le
canon est supposé chargé en poudre et boulet.
"""
cle = "feu"
def __init__(s... |
from gnuradio import gr, gr_unittest
from gnuradio import blocks
import pmt
class qa_tag_share(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_001_t(self):
# Constants
tag_key = 'in1_tag'
tag_value = 0
... |
'''
GCE external inventory script
=================================
Generates inventory that Ansible can understand by making API requests
Google Compute Engine via the libcloud library. Full install/configuration
instructions for the gce* modules can be found in the comments of
ansible/test/gce_tests.py.
When run a... |
from __future__ import absolute_import, division, print_function, with_statement
from hashlib import md5
from tornado.escape import utf8
from tornado.httpclient import HTTPRequest
from tornado.stack_context import ExceptionStackContext
from tornado.testing import AsyncHTTPTestCase
from tornado.test import httpclient_... |
from .charsetprober import CharSetProber
from .codingstatemachine import CodingStateMachine
from .enums import LanguageFilter, ProbingState, MachineState
from .escsm import (HZ_SM_MODEL, ISO2022CN_SM_MODEL, ISO2022JP_SM_MODEL,
ISO2022KR_SM_MODEL)
class EscCharSetProber(CharSetProber):
"""
... |
"""
Many-to-many relationships between the same two tables
In this example, a ``Person`` can have many friends, who are also ``Person``
objects. Friendship is a symmetrical relationship - if I am your friend, you
are my friend. Here, ``friends`` is an example of a symmetrical
``ManyToManyField``.
A ``Person`` can als... |
from openerp.osv import fields, osv
class product_category(osv.osv):
_inherit = "product.category"
_columns = {
'property_account_creditor_price_difference_categ': fields.property(
'account.account',
type='many2one',
relation='account.account',
string="Pr... |
from __future__ import unicode_literals
from .cbs import CBSBaseIE
class CBSSportsIE(CBSBaseIE):
_VALID_URL = r'https?://(?:www\.)?cbssports\.com/[^/]+/(?:video|news)/(?P<id>[^/?#&]+)'
_TESTS = [{
'url': 'https://www.cbssports.com/nba/video/donovan-mitchell-flashes-star-potential-in-game-2-victory-o... |
# -*- coding: utf-8 -*-
'''
Local settings
- Run in Debug mode
- Use console backend for emails
- Add Django Debug Toolbar
- Add django-extensions as app
'''
from .common import * # noqa
# DEBUG
# ------------------------------------------------------------------------------
DEBUG = env.bool('DJANGO_DEBUG', default... |
from heat.common.i18n import _
from heat.engine import properties
from heat.engine import resource
from heat.engine import support
class KeystoneService(resource.Resource):
"""Heat Template Resource for Keystone Service."""
support_status = support.SupportStatus(
version='2015.2',
message=_('... |
"""
Verifies that targets have independent INTERMEDIATE_DIRs.
"""
import TestGyp
test = TestGyp.TestGyp()
test.run_gyp('test.gyp', chdir='src')
test.build('test.gyp', 'target1', chdir='src')
# Check stuff exists.
intermediate_file1 = test.read('src/outfile.txt')
test.must_contain(intermediate_file1, 'target1')
shar... |
"""The io module provides the Python interfaces to stream handling. The
builtin open function is defined in this module.
At the top of the I/O hierarchy is the abstract base class IOBase. It
defines the basic interface to a stream. Note, however, that there is no
separation between reading and writing to streams; impl... |
import mock
from neutronclient.common import exceptions
from heat.common import template_format
from heat.engine.resources.openstack.neutron.lbaas import health_monitor
from heat.tests import common
from heat.tests.openstack.neutron import inline_templates
from heat.tests import utils
class HealthMonitorTest(common... |
#!/usr/bin/env python3
import logging
from logging import StreamHandler
from docopt import docopt
from riot_graphs.rg import RiotGraph
from riot_graphs import server
def fetch(args, graphs):
days = None
if args['--days']:
try:
days = int(args['--days'])
except:
raise ... |
import encrypt_bot
def test():
for cmd, expected_response in sample_conversation():
message = {'content': cmd, 'subject': 'foo',
'display_recipient': 'bar'}
class ClientDummy(object):
def __init__(self):
self.output = ''
def send_message(... |
from django.test import TestCase
from models import A, B, C, D, DataPoint, RelatedPoint
class SimpleTest(TestCase):
def setUp(self):
self.a1 = A.objects.create()
self.a2 = A.objects.create()
for x in range(20):
B.objects.create(a=self.a1)
D.objects.create(a=self.a1... |
from airflow import configuration
from airflow.exceptions import AirflowException
# Constants for resources (megabytes are the base unit)
MB = 1
GB = 1024 * MB
TB = 1024 * GB
PB = 1024 * TB
EB = 1024 * PB
class Resource(object):
"""
Represents a resource requirement in an execution environment for an operato... |
import numpy as np
import os.path as op
from nose.tools import assert_equal, assert_raises, assert_true
from numpy.testing import assert_array_equal, assert_array_almost_equal
from mne import Epochs, read_events, pick_types, compute_raw_covariance
from mne.io import read_raw_fif
from mne.utils import requires_sklearn, ... |
from difflib import unified_diff
import os
import sys
from conf import hook
from exc.test_failed import TestFailed
""" Post-Test Hook: ExpectedFiles
This is a Post-Test hook that checks the test directory for the files it
contains. A dictionary object is passed to it, which contains a mapping of
filenames and contents... |
from boto.s3.key import Key
from mock import Mock
from moto import mock_s3
from pyproctor import MonkeyPatcher
from shelf.app import app
from shelf.error_code import ErrorCode
from shelf.metadata.initializer import Initializer
from shelf.resource_identity import ResourceIdentity
from shelf.search.container import Conta... |
# Django settings for wictrl project.
import sys
import os.path
reload(sys)
sys.setdefaultencoding('utf-8')
gettext = lambda s: s
PROJECT_ROOT = os.path.join(
os.path.realpath(os.path.dirname(__file__)), os.pardir)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '<EMAIL>'),
)
MANAGERS = ADM... |
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
# PYTHON 3 and PYGAME DEPENDENCIES
if module_exists('pygame'):
import pygame
class _body(object):
def __init__(self):
self.events = {}
def appe... |
"""Twilio Call platform for notify component."""
import logging
import urllib
from twilio.base.exceptions import TwilioRestException
import voluptuous as vol
from homeassistant.components.notify import (
ATTR_TARGET,
PLATFORM_SCHEMA,
BaseNotificationService,
)
from homeassistant.components.twilio import D... |
"""
EasyBuild support for building and installing Qt, implemented as an easyblock
@author: Kenneth Hoste (Ghent University)
"""
import os
import easybuild.tools.toolchain as toolchain
from easybuild.easyblocks.generic.configuremake import ConfigureMake
from easybuild.tools.filetools import run_cmd_qa
class EB_Qt(Co... |
"""Component targets XML test (MEDIUM test)."""
import sys
import TestFramework
def TestSConstruct(scons_globals):
"""Test SConstruct file.
Args:
scons_globals: Global variables dict from the SConscript file.
"""
# Get globals from SCons
Environment = scons_globals['Environment']
base_env = Enviro... |
import ldap
import logging
from ldap.filter import filter_format
import openerp.exceptions
from openerp import tools
from openerp.osv import fields, osv
from openerp import SUPERUSER_ID
from openerp.modules.registry import RegistryManager
_logger = logging.getLogger(__name__)
class CompanyLDAP(osv.osv):
_name = '... |
"""
Support for Dark Sky weather service.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.darksky/
"""
import logging
from datetime import timedelta
import voluptuous as vol
from requests.exceptions import ConnectionError as ConnectError, \
HT... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.