content
stringlengths
4
20k
"""Glue code to load http://mlcomp.org data as a scikit.learn dataset""" import os import numbers from sklearn.datasets.base import load_files def _load_document_classification(dataset_path, metadata, set_=None, **kwargs): if set_ is not None: dataset_path = os.path.join(dataset_path, set_) return lo...
#!/usr/bin/env python import logging import datetime import sys PATH_INSTALL = "./" sys.path.append(PATH_INSTALL) from optparse import OptionParser from androguard.core.analysis import auto from androguard.core.androconf import set_debug option_0 = {'name': ('-d', '--directory'), 'help': 'directory input', 'nargs':...
""" Django settings for contagement project. Generated by 'django-admin startproject' using Django 1.10.1. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ from ...
"""Contains the logic for `aq cat --cluster`.""" from aquilon.aqdb.model import Cluster, MetaCluster from aquilon.worker.broker import BrokerCommand # pylint: disable=W0611 from aquilon.worker.dbwrappers.resources import get_resource from aquilon.worker.templates.base import Plenary from aquilon.worker.templates.clu...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os.path from hashlib import sha1 from pants.base.exceptions import TargetDefinitionException from pants.base.fingerprint_strategy import DefaultFingerprintStra...
import argh import os import itertools from functools import partial from cr8 import aio, clients from .insert_json import to_insert from .bench_spec import load_spec from .engine import Runner, Result, run_and_measure, eval_fail_if from .misc import ( as_bulk_queries, as_statements, get_lines, parse_v...
""" Test suite for OS X interpreter environment variables. """ from test.support import EnvironmentVarGuard, run_unittest import subprocess import sys import unittest class OSXEnvironmentVariableTestCase(unittest.TestCase): def _check_sys(self, ev, cond, sv, val = sys.executable + 'dummy'): with Environme...
class ModuleDocFragment(object): # Standard CNOS documentation fragment DOCUMENTATION = ''' options: outputfile: description: - This specifies the file path where the output of each command execution is saved. Each command that is specified in the merged templat...
from apache.thermos.config.schema import * # TODO(wickman) Bind {{mesos.instance}} to %shard_id% class MesosContext(Struct): # The instance id (i.e. replica id, shard id) in the context of a task instance = Required(Integer) hostname = Required(String) class UpdateConfig(Struct): batch_size ...
from spacy.util import align_tokens def test_perfect_align(): ref = ['I', 'align', 'perfectly'] indices = [] i = 0 for token in ref: indices.append((i, i + len(token))) i += len(token) aligned = list(align_tokens(ref, indices)) assert aligned[0] == ('I', [(0, 1)]) assert al...
# -*- coding: utf-8 -*- """ Flexx setup script. Release: * python setup.py register * python setup.py sdist bdist_wheel --universal upload * build conda packages? """ import os from os import path as op try: # use setuptools namespace, allows for "develop" import setuptools # noqa, analysis:ignore except...
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * # Greed is a dice game where you roll up to five dice to accumulate # points. The following "score" function will be used calculate the # score of a single roll of the dice. # # A greed roll is scored as follows: # # * A set of three ones is 10...
""" This module defines the attributes of the PyPI package for the Mbed SDK """ from shutil import copyfileobj from os.path import isfile, join from tempfile import TemporaryFile from setuptools import find_packages from distutils.core import setup LICENSE = open('LICENSE').read() DESCRIPTION = """A set of Python scr...
import mock from nova.scheduler.filters import compute_filter from nova import test from nova.tests.unit.scheduler import fakes @mock.patch('nova.servicegroup.API.service_is_up') class TestComputeFilter(test.NoDBTestCase): def test_compute_filter_manual_disable(self, service_up_mock): filt_cls = compute...
""" Helper functions for writing to terminals and files. """ import sys, os import py py3k = sys.version_info[0] >= 3 from py.builtin import text, bytes win32_and_ctypes = False colorama = None if sys.platform == "win32": try: import colorama except ImportError: try: import ctyp...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} import os_client_config from os_client_config import exceptions def main(): module = AnsibleModule(argument_spec=dict( clouds=dict(required=False, type='list', default=[]), ...
from __future__ import absolute_import, division, print_function from glob import glob import os try: from skimage.io import imread as sk_imread except ImportError: pass from .core import Array from ..base import tokenize def add_leading_dimension(x): return x[None, ...] def imread(filename, imread=N...
""" Signal handler for setting default course mode expiration dates """ from django.core.exceptions import ObjectDoesNotExist from django.dispatch.dispatcher import receiver from xmodule.modulestore.django import SignalHandler, modulestore from .models import CourseMode, CourseModeExpirationConfig @receiver(SignalH...
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.generic.base import TemplateView #from django.contrib.admin.views.decorators import staff_member_required from django.conf.urls import patterns from django.contrib import admin class Screen...
import copy from airflow.contrib.hooks.gcp_dataflow_hook import DataFlowHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class DataFlowJavaOperator(BaseOperator): """ Start a Java Cloud DataFlow batch job. The parameters of the operation will be passed to t...
import os import tempfile import re import sys from pip.util import call_subprocess from pip.util import display_path, rmtree from pip.log import logger from pip.vcs import vcs, VersionControl from pip.download import path_to_url from pip.backwardcompat import ConfigParser class Mercurial(VersionControl): name = ...
from opm._common import eclArrType from opm._common import EclFile from opm._common import ERst from opm._common import ESmry from opm._common import EGrid from opm._common import ERft from opm._common import EclOutput import sys import datetime import numpy as np import datetime # When extracting the strings from CH...
# FIXME: standardize into module_common from traceback import format_exc from re import compile as re_compile # FIXME: standardize into module_common from distutils.spawn import find_executable from os import environ from sys import exc_info import traceback match_key = re_compile("^gpg:.*key ([0-9a-fA-F]+):.*$") REQ...
# Tastypie specific from tastypie.resources import ModelResource # cache specific from api.cache import NoTransformCache from iati.models import AidType from iati.models import Activity from cache.validator import Validator # Direct sql specific import ujson from django.db import connection from django.http import Ht...
""" Counts words in UTF8 encoded, '\n' delimited text received from the network every second. Usage: network_wordcount.py <hostname> <port> <hostname> and <port> describe the TCP server that Spark Streaming would connect to receive data. To run this on your local machine, you need to first run a Netcat server ...
from __future__ import absolute_import, division, unicode_literals from xml.dom import Node from ..constants import namespaces, voidElements, spaceCharacters __all__ = ["DOCUMENT", "DOCTYPE", "TEXT", "ELEMENT", "COMMENT", "ENTITY", "UNKNOWN", "TreeWalker", "NonRecursiveTreeWalker"] DOCUMENT = Node.DOCUMEN...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ibm_sa_utils i...
#!/usr/bin/env python # encoding: utf-8 # Thomas Nagy, 2006-2010 (ita) """ TeX/LaTeX/PDFLaTeX/XeLaTeX support Example:: def configure(conf): conf.load('tex') if not conf.env.LATEX: conf.fatal('The program LaTex is required') def build(bld): bld( features = 'tex', type = 'latex', # pdflatex or x...
"""Image-to-text implementation based on http://arxiv.org/abs/1411.4555. "Show and Tell: A Neural Image Caption Generator" Oriol Vinyals, Alexander Toshev, Samy Bengio, Dumitru Erhan """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # Standard Imports im...
""" ================================= Gaussian Mixture Model Sine Curve ================================= This example highlights the advantages of the Dirichlet Process: complexity control and dealing with sparse data. The dataset is formed by 100 points loosely spaced following a noisy sine curve. The fit by the GMM...
from cloudinit import templater from cloudinit import util from cloudinit.settings import PER_INSTANCE frequency = PER_INSTANCE POST_LIST_ALL = [ 'pub_key_dsa', 'pub_key_rsa', 'pub_key_ecdsa', 'instance_id', 'hostname' ] # phone_home: # url: http://my.foo.bar/$INSTANCE/ # post: all # tries: ...
__all__ = [ 'LXMLTreeBuilderForXML', 'LXMLTreeBuilder', ] from io import BytesIO from io import StringIO import collections from lxml import etree from bs4.element import ( Comment, Doctype, NamespacedAttribute, ProcessingInstruction, ) from bs4.builder import ( FAST, HTML, HTML...
from m5.params import * from m5.objects import * from BaseTopology import SimpleTopology class MeshDirCorners(SimpleTopology): description='MeshDirCorners' def __init__(self, controllers): self.nodes = controllers # This file contains a special network creation function. This # networks is ...
{ 'name': 'Membership Management', 'version': '0.1', 'category': 'Association', 'description': """ This module allows you to manage all operations for managing memberships. ========================================================================= It supports different kind of members: -----------------...
import os from alembic import command as alembic_command from alembic import config as alembic_config from alembic import script as alembic_script from alembic import util as alembic_util from oslo_config import cfg from tacker._i18n import _ from tacker.db.migration.models import head # noqa from tacker.db.migratio...
import logging, os, pwd, grp LOG = logging.getLogger(__name__) def dropPrivileges(): user = pwd.getpwnam('nobody') group = grp.getgrnam('nobody') os.setgroups([group.gr_gid]) os.setgid(group.gr_gid) os.setuid(user.pw_uid) LOG.debug("Dropped root privileges, now running as \'nobody\'")
import collections LINK_TYPE_PHYSICAL = "physical" LINK_TYPE_BOND = "bond" LINK_TYPE_VLAN = "vlan" # Based on: https://www.kernel.org/doc/Documentation/networking/bonding.txts BOND_TYPE_8023AD = "802.3ad" BOND_TYPE_BALANCE_RR = "balance-rr" BOND_TYPE_ACTIVE_BACKUP = "active-backup" BOND_TYPE_BALANCE_XOR = "balance-xo...
class HyObject(object): """ Generic Hy Object model. This is helpful to inject things into all the Hy lexing Objects at once. """ def replace(self, other): if isinstance(other, HyObject): for attr in ["start_line", "end_line", "start_column", "end_column...
import unittest import torch import torch.nn from nupic.research.frameworks.pytorch.models.le_sparse_net import LeSparseNet class LeSparseNetTest(unittest.TestCase): def test_default(self): """ Make sure we get something reasonable with default parameters and that it runs. """ ...
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class KeekIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?keek\.com/keek/(?P<id>\w+)' IE_NAME = 'keek' _TEST = { 'url': 'https://www.keek.com/keek/NODfbab', 'md5': '9b0636f8c0f7614afa4ea5e4c6e57...
from m5.SimObject import SimObject from m5.params import * class VncInput(SimObject): type = 'VncInput' cxx_header = "base/vnc/vncinput.hh" frame_capture = Param.Bool(False, "capture changed frames to files") class VncServer(VncInput): type = 'VncServer' cxx_header = "base/vnc/vncserver.hh" po...
from datetime import datetime from functools import wraps import dateutil.parser from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.contrib.auth.decorators import login_required from django.contrib.sites.requests import RequestSite from django.contrib.contenttypes.mo...
from meresco.core import Transparent, Observable from meresco.core.generatorutils import asyncnoreturnvalue class _Fieldlet(Transparent): def __init__(self, method): Transparent.__init__(self) self._method = method class FilterFieldValue(_Fieldlet): def addField(self, name, value): if ...
import logging import copy try: from zabbix_api import ZabbixAPI, ZabbixAPISubClass HAS_ZABBIX_API = True except ImportError: HAS_ZABBIX_API = False # Extend the ZabbixAPI # Since the zabbix-api python module too old (version 1.0, no higher version so far), # it does not support the 'hostinterface' api ...
""" PureMVC Python Port by Toby de Havilland <<EMAIL>> PureMVC - Copyright(c) 2006-08 Futurescale, Inc., Some rights reserved. Your reuse is governed by the Creative Commons Attribution 3.0 License """ import puremvc.core import puremvc.interfaces import puremvc.patterns.observer class Facade(object,puremvc.int...
import os import stat import time import tempfile import weetest def TestChdirAndGetCwd(): path = os.getcwd() os.chdir('.') assert os.getcwd() == path tempdir = tempfile.mkdtemp() try: os.chdir(tempdir) assert tempdir in os.getcwd() finally: os.chdir(path) os.rmdir(tempdir) assert os....
import pandas as pd from bokeh.models import ColumnDataSource, LabelSet from bokeh.plotting import figure, show, output_file from bokeh.sampledata.periodic_table import elements elements = elements.copy() elements = elements[elements["atomic number"] <= 82] elements = elements[~pd.isnull(elements["melting point"])] m...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import io import os import re import types from datetime import datetime, timedelta from unittest import TestCase from django.core.exceptions import ValidationError from django.core.validators import ( BaseValidator, EmailValidator, MaxLengthValidato...
from blazar import context from blazar.manager.devices import rpcapi as manager_rpcapi from blazar import policy from blazar.utils import trusts class API(object): def __init__(self): self.manager_rpcapi = manager_rpcapi.ManagerRPCAPI() @policy.authorize('devices', 'get') def get_devices(self): ...
''' Tornado-MySQL: A pure-Python MySQL client library for Tornado. Copyright (c) 2010, 2013-2014 PyMySQL contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, includin...
from temboo.core.choreography import Choreography from temboo.core.choreography import InputSet from temboo.core.choreography import ResultSet from temboo.core.choreography import ChoreographyExecution import json class ListAllProducts(Choreography): def __init__(self, temboo_session): """ Create...
from django.shortcuts import render from django.core import serializers from django.http import HttpResponse from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.conf import settings import json impo...
import sys,traceback,types from ctypes import * class lammps: def __init__(self,name="",cmdargs=None,ptr=None): # load liblammps.so by default # if name = "g++", load liblammps_g++.so try: if not name: self.lib = CDLL("liblammps.so",RTLD_GLOBAL) else: self.lib = CDLL("liblammps_%s.so" % nam...
import account_bank_statement import res_partner_bank import report import wizard # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Parse the version from the lostfilm module. with open('extras/__init__.py') as f: for line in f: if line.find("__version__") ...
# -*- coding: utf-8 -*- """ werkzeug.debug ~~~~~~~~~~~~~~ WSGI application traceback debugger. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import os import re import sys import uuid import json import time import getpass...
from __future__ import unicode_literals import json from mock import call from wstore.store_commons.tests import * from wstore.admin.users.tests import * from django.test.client import RequestFactory from wstore import views class ServeMediaTestCase(TestCase): tags = ('media', ) _resource_path = 'media/a...
# # The goal is to finally have a form filler where you pass data for # each form, using the algorithm for "Seeding a form with initial values" # See http://www.whatwg.org/specs/web-forms/current-work/#seeding # import _base from html5lib.constants import spaceCharacters spaceCharacters = u"".join(spaceCharacters) c...
"""FontStyle extensions for OpenGLContext""" from vrml.vrml97 import basenodes from vrml import field, node class FontStyle( basenodes.FontStyle ): """FontStyle with ability to specify geometry format""" PROTO = 'FontStyle' ## #Fields ## style = field.newField( 'style', 'SFString', 0, 'PLAIN') ## topToBottom =...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.tests.mock import patch, MagicMock from units.modules.utils import set_module_args from .junos_module import TestJunosModule jnpr_mock = MagicMock() scp_mock = MagicMock() modules = { 'jnpr': jnpr_mock, ...
import json import mock import os import requests from .. import base from girder import config from girder.api.rest import endpoint from girder.models.user import User def setUpModule(): os.environ['GIRDER_PORT'] = os.environ.get('GIRDER_TEST_PORT', '20200') config.loadConfig() testPluginPath = os.path....
"""Conversion functions between RGB and other color systems. This modules provides two functions for each color system ABC: rgb_to_abc(r, g, b) --> a, b, c abc_to_rgb(a, b, c) --> r, g, b All inputs and outputs are triples of floats in the range [0.0...1.0] (with the exception of I and Q, which covers a slightly...
from django.db import models from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin, Permission from account.validator import validate_name, validate_profession, validate_experience CATEGORIES = ['A', 'A1', 'B', 'B1', 'BE', 'C', 'C1', 'CE', 'C1E', 'D', 'D1', 'DE', 'D1E', 'M', 'Tm', ...
#!/usr/bin/env python """Display clusto objects, recursively, with attributes, and/or in color.""" import sys from itertools import chain import clusto from clusto import script_helper class Colors(object): """ANSI color escape sequences class.""" mapping = {'BRIGHT': '\033[1m', 'GREEN': '\...
"""Unit tests for GS versioning support.""" from xml import sax from boto import handler from boto.gs import acl from tests.integration.gs.testcase import GSTestCase class GSVersioningTest(GSTestCase): def testVersioningToggle(self): b = self._MakeBucket() self.assertFalse(b.get_versioning_stat...
from __future__ import print_function import math #from scipy.special import gamma, gammainc, gammaincc from gamma_functions import * import random def probs(K,M,i): M8 = [0.2148, 0.3672, 0.2305, 0.1875] M128 = [0.1174, 0.2430, 0.2493, 0.1752, 0.1027, 0.1124] M512 = [0.1170, 0.2460, 0.2523, 0....
"""Support for August camera.""" from datetime import timedelta import requests from homeassistant.components.camera import Camera from . import DATA_AUGUST, DEFAULT_TIMEOUT SCAN_INTERVAL = timedelta(seconds=5) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up August cameras.""" ...
# -*- coding: utf-8 -*- ''' 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 dis...
import os import eventlet from oslo_config import cfg from oslo_log import log as logging import webob from neutron._i18n import _, _LI from neutron.agent.linux import keepalived from neutron.agent.linux import utils as agent_utils from neutron.common import utils as common_utils from neutron.notifiers import batch_n...
from spack.main import print_setup_info def test_print_shell_vars_sh(capsys): print_setup_info('sh') out, _ = capsys.readouterr() assert "_sp_sys_type=" in out assert "_sp_tcl_roots=" in out assert "_sp_lmod_roots=" in out assert "_sp_module_prefix" not in out def test_print_shell_vars_csh(...
import base64 import hmac import time from hashlib import sha1 from . import jwt from .compat import izip, urlencode from six import iteritems, PY3 class RequestValidator(object): def __init__(self, token): self.token = token.encode("utf-8") def compute_signature(self, uri, params, utf=PY3): ...
""" tooltips ~~~~~~~~ Simple way to add tooltips to a widget. Idea from https://stackoverflow.com/questions/3221956/what-is-the-simplest-way-to-make-tooltips-in-tkinter """ import datetime import tkinter as tk import tkinter.ttk as ttk class ToolTip(): """Class to display a tooltip over a widget. Works by moni...
import base_report import bilan_report import compute_resultant_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from openerp import tools from openerp.osv import fields, osv class payment_advice_report(osv.osv): _name = "payment.advice.report" _description = "Payment Advice Analysis" _auto = False _columns = { 'name':fields.char('Name', readonly=True), 'date': fields.date('Date', readonly=True,),...
#!/usr/bin/env python import os import shutil import glob import time import sys import subprocess import string from optparse import OptionParser, make_option SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PKG_NAME = os.path.basename(SCRIPT_DIR) PARAMETERS = None #XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=...
import json import os import StringIO import unittest from telemetry import benchmark from telemetry.results import chart_json_output_formatter from telemetry.results import page_test_results from telemetry.page import page_set from telemetry.value import scalar from telemetry.value import list_of_scalar_values def ...
{ 'name': 'Italy - Accounting', 'version': '0.2', 'depends': ['base_vat','account_chart','base_iban'], 'author': 'OpenERP Italian Community', 'description': """ Piano dei conti italiano di un'impresa generica. ================================================ Italian accounting chart and localizatio...
from __future__ import division, absolute_import, print_function import numpy as np from numpy.testing import ( run_module_suite, TestCase, assert_, assert_almost_equal, assert_allclose ) class TestFinancial(TestCase): def test_rate(self): assert_almost_equal(np.rate(10, 0, -3500, 10000), ...
"""WebSubmit Admin Regression Test Suite.""" __revision__ = "$Id$" import unittest from invenio.config import CFG_SITE_URL from invenio.testutils import make_test_suite, run_test_suite, \ test_web_page_content, merge_error_messages class WebSubmitAdminWebPagesAvailabilityTest(unittest....
"""SVD decomposition functions.""" import numpy from numpy import asarray_chkfinite, zeros, r_, diag from scipy.linalg import calc_lwork # Local imports. from misc import LinAlgError, _datacopied from lapack import get_lapack_funcs from funcinfo import get_func_info def svd(a, full_matrices=True, compute_uv=True, o...
"""The tests for the openalpr local platform.""" import homeassistant.components.image_processing as ip from homeassistant.const import ATTR_ENTITY_PICTURE from homeassistant.core import callback from homeassistant.setup import setup_component from tests.async_mock import MagicMock, PropertyMock, patch from tests.comm...
# -*- coding: utf-8 -*- """ This module offers a generic easter computing method for any given year, using Western, Orthodox or Julian algorithms. """ import datetime __all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"] EASTER_JULIAN = 1 EASTER_ORTHODOX = 2 EASTER_WESTERN = 3 def easter(year,...
from abstract_domains.state import State from core.expressions import BinaryArithmeticOperation, BinaryOperation, BinaryComparisonOperation, UnaryOperation, \ UnaryArithmeticOperation, UnaryBooleanOperation, BinaryBooleanOperation, Input, ListDisplay, Slice, Index, Literal from core.statements import Statement, Var...
import webnotes, markdown2 def execute(): webnotes.reload_doc("utilities", "doctype", "note") webnotes.reload_doc("utilities", "doctype", "note_user") for question in webnotes.conn.sql("""select * from tabQuestion""", as_dict=True): if question.question: try: name = question.question[:180] if webnote...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # http://binux.me # Created on 2014-10-07 10:33:38 import os import time import unittest2 as unittest from pyspider.libs import utils from pyspider.libs import rabbitmq @unittest.skipIf(os.environ.get('IGNORE_RA...
""" Tests For Scheduler Host Filters. """ import inspect import sys from nova import filters from nova import loadables from nova import test class Filter1(filters.BaseFilter): """Test Filter class #1.""" pass class Filter2(filters.BaseFilter): """Test Filter class #2.""" pass class FiltersTestC...
""" Fixtures. Fixtures are a way of loading data into the database in bulk. Fixure data can be stored in any serializable format (including JSON and XML). Fixtures are identified by name, and are stored in either a directory named 'fixtures' in the application directory, or in one of the directories named in the ``FIX...
import unittest import nest import numpy as np class PpPscDeltaTestCase(unittest.TestCase): """Tests for pp_psc_delta""" def test_rate_and_fixed_dead_time(self): """ Check for reasonable firing rate and if fixed dead-time is respected """ # test parameters d = 25.0 ...
#!/usr/bin/python import time from copy import copy from Adafruit_I2C import Adafruit_I2C # ============================================================================ # LEDBackpack Class # ============================================================================ class LEDBackpack: i2c = None # Registers ...
from translate.storage.versioncontrol import GenericRevisionControlSystem from translate.storage.versioncontrol import run_command def is_available(): """check if darcs is installed""" exitcode, output, error = run_command(["darcs", "--version"]) return exitcode == 0 class darcs(GenericRevisionControlSy...
from tower import ugettext_lazy as _ class SECTION_ADDONS: short = 'addons' pretty = _(u'Add-ons') twitter = 'twitter-addons' updates = 'updates-addons' class SECTION_MOZILLA: short = 'mozilla' pretty = _(u'Mozilla') twitter = 'twitter-mozilla' updates = 'updates-mozilla' class SEC...
default_app_config = 'providers.org.seafdec.apps.AppConfig' """ Example record: <record xmlns="http://www.openarchives.org/OAI/2.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><header><identifier>oai:repository.seafdec.org.ph:10862/143</identifier><datestamp>2016-10-05T13:04:40Z</datestamp><setSpec>com_1086...
from gnuradio import gr, gr_unittest, blocks class test_interleave (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_int_001 (self): lenx = 64 src0 = blocks.vector_source_f (range (0, lenx, 4)) src1 = ...
#!/usr/bin/env python import argparse from ipalib import api import json def initialize(): ''' This function initializes the FreeIPA/IPA API. This function requires no arguments. A kerberos key must be present in the users keyring in order for this to work. ''' api.bootstrap(context='cli') ...
from gnuradio import gr, gr_unittest, digital, blocks default_access_code = '\xAC\xDD\xA4\xE2\xF2\x8C\x20\xFC' def string_to_1_0_list(s): r = [] for ch in s: x = ord(ch) for i in range(8): t = (x >> i) & 0x1 r.append(t) return r def to_1_0_string(L): return ''...
"""SQL connections, SQL execution and high-level DB-API interface. The engine package defines the basic components used to interface DB-API modules with higher-level statement construction, connection-management, execution and result contexts. The primary "entry point" class into this package is the Engine and it's p...
from .regex import Regex class XMLAnnotator(object): def __init__(self, string): self.regx = Regex(string) def register_tag(self, re_string, open_tag, group=None): ''' Registers an XML tag to be inserted around a matching regular expression. The closing tag is derived from the opening ...
# -*- coding: utf-8 -*- from datetime import timedelta, datetime import pytz from test_ella.cases import RedisTestCase as TestCase from django.conf import settings from django.contrib.sites.models import Site from django.contrib.redirects.models import Redirect from django.contrib.contenttypes.models import ContentTyp...
import testtools from tempest.api.compute import base import tempest.config as config class AuthTokenTestJSON(base.BaseComputeTest): _interface = 'json' @classmethod def setUpClass(cls): super(AuthTokenTestJSON, cls).setUpClass() cls.servers_v2 = cls.os.servers_client cls.server...
import os class MapValidator(): """Base class. Validates user-created map file""" def __init__(self, location): self.map = self.read_file(location) self.player_spawn = False self.npc_spawn = False self.key_present = False self.chest_present = False self.rectan...