content
string
""" Views for serving static textbooks. """ from django.contrib.auth.decorators import login_required from django.http import Http404 from edxmako.shortcuts import render_to_response from opaque_keys.edx.locations import SlashSeparatedCourseKey from xmodule.annotator_token import retrieve_token from courseware.acces...
#! /usr/bin/env python sources = """ @SOURCES@""" import os import sys import base64 import zlib import tempfile import shutil def unpack(sources): temp_dir = tempfile.mkdtemp('-scratchdir', 'unpacker-') for package, content in sources.items(): filepath = package.split(".") dirpath = os.sep....
# Scan an Apple header file, generating a Python file of generator calls. import sys from bgenlocations import TOOLBOXDIR, BGENDIR sys.path.append(BGENDIR) from scantools import Scanner_OSX LONG = "CoreFoundation" SHORT = "cf" OBJECTS = ("CFTypeRef", "CFArrayRef", "CFMutableArrayRef", ...
from openerp import netsvc from openerp.osv import osv, fields from openerp.tools.translate import _ from openerp.addons.point_of_sale.point_of_sale import pos_session class pos_session_opening(osv.osv_memory): _name = 'pos.session.opening' _columns = { 'pos_config_id' : fields.many2one('pos.config'...
""" Contains transport interface (classes). """ class TransportError(Exception): def __init__(self, reason, httpcode, fp=None): Exception.__init__(self, reason) self.httpcode = httpcode self.fp = fp class Request: """ A transport request @ivar url: The url for the request. ...
"""Response classes used by urllib. The base class, addbase, defines a minimal file-like interface, including read() and readline(). The typical response object is an addinfourl instance, which defines an info() method that returns headers and a geturl() method that returns the url. """ from __future__ import absolut...
import numpy as np import matplotlib.pyplot as plt from scipy import stats npoints = 20 # number of integer support points of the distribution minus 1 npointsh = npoints / 2 npointsf = float(npoints) nbound = 4 #bounds for the truncated normal normbound = (1 + 1 / npointsf) * nbound #actual bounds of truncated normal ...
"""Musepack audio streams with APEv2 tags. Musepack is an audio format originally based on the MPEG-1 Layer-2 algorithms. Stream versions 4 through 7 are supported. For more information, see http://www.musepack.net/. """ __all__ = ["Musepack", "Open", "delete"] import struct from mutagen.apev2 import APEv2File, er...
# -*- coding: utf-8 -*- import cStringIO import datetime from itertools import islice import json import logging import re from sys import maxint import werkzeug.utils import werkzeug.wrappers from PIL import Image import openerp from openerp.addons.web import http from openerp.http import request, Response logger ...
""" ========================== Model Complexity Influence ========================== Demonstrate how model complexity influences both prediction accuracy and computational performance. The dataset is the Boston Housing dataset (resp. 20 Newsgroups) for regression (resp. classification). For each class of models we m...
# -*- coding: utf-8 -*- """ *************************************************************************** aspect.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com ******************...
"""Provide kiskadee queues and operations on them.""" import time from multiprocessing import Queue import kiskadee analysis = Queue() results = Queue() packages = Queue() class Queues(): """Provide kiskadee queues objects.""" @staticmethod def enqueue_analysis(package_to_analysis): """Put a ana...
import json import optparse from webkitpy.layout_tests.port import Port def main(host, argv): parser = optparse.OptionParser(usage='%prog [times_ms.json]') parser.add_option('-f', '--forward', action='store', type='int', help='group times by first N directories of test') parser.add_...
""" test one to many relationships """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import six from elixir import * from sqlalchemy import and_ from sqlalchemy.ext.orderinglist import ordering_list def setup(): ...
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext as _ from model_utils import Choices import aristotle_mdr as aristotle """ These models are based on the DDI3.2 and the SQBL XML formats. """ class AdministrationMode(aristotle.models.unmanagedObject...
from jingo import get_env from mock import Mock from pyquery import PyQuery as pq from olympia import amo from olympia.addons.models import Addon def render(s, context=None): """Taken from jingo.tests.utils, previously jingo.tests.test_helpers.""" if context is None: context = {} t = get_env().fr...
"""TLS Lite + smtplib.""" from smtplib import SMTP from tlslite.TLSConnection import TLSConnection from tlslite.integration.ClientHelper import ClientHelper class SMTP_TLS(SMTP): """This class extends L{smtplib.SMTP} with TLS support.""" def starttls(self, username=None, password=None, share...
from Plugin import Plugin import dbus class MateMediaKeysPlugin(Plugin): def __init__(self): super(MateMediaKeysPlugin, self).__init__() def initialize(self, name, eventManagerWrapper, eventSubscriber, provider, cfgProvider, mediator, tooltip): self.name = name self.eventManager...
from modules.OsmoseTranslation import T_ from .Analyser_Merge import Analyser_Merge, SourceOpenDataSoft, CSV, Load, Conflate, Select, Mapping class Analyser_Merge_Public_Equipment_FR_Rennes_Toilets(Analyser_Merge): def __init__(self, config, logger = None): Analyser_Merge.__init__(self, config, logger) ...
from setuptools import setup import os readme = open(os.path.join(os.path.dirname(__file__), 'README'), 'r').read() license = open(os.path.join(os.path.dirname(__file__), 'LICENSE'), 'r').read() setup( name = "data_packager", version = "0.0.1", author = "Ethan Rowe", author_email = "<EMAIL>", desc...
"""Tests for browser.network.schemehandler.""" import pytest from qutebrowser.browser.network import schemehandler def test_init(): handler = schemehandler.SchemeHandler(0) assert handler._win_id == 0 def test_create_request(): handler = schemehandler.SchemeHandler(0) with pytest.raises(NotImpleme...
# coding=utf-8 """ The GridEngineCollector parses qstat statistics from Sun Grid Engine, Univa Grid Engine and Open Grid Scheduler. #### Dependencies * Grid Engine qstat """ import os import re import subprocess import sys import xml.dom.minidom import diamond.collector class GridEngineCollector(diamond.collec...
from openerp import api, fields, models from openerp import SUPERUSER_ID # TODO remove in v10 class BaseImportMatch(models.Model): _name = "base_import.match" _description = "Deduplicate settings prior to CSV imports." _order = "sequence, name" name = fields.Char( compute="_compute_name", ...
#!/usr/bin/env python ''' Run this script every time you change one of the png files. Using pngcrush, it will optimize the png files, remove various color profiles, remove ancillary chunks (alla) and text chunks (text). #pngcrush -brute -ow -rem gAMA -rem cHRM -rem iCCP -rem sRGB -rem alla -rem text ''' import os impor...
""" Test variable expansion of '<!()' syntax commands. """ import os import TestGyp test = TestGyp.TestGyp(format='gypd') expect = test.read('commands.gyp.stdout').replace('\r', '') test.run_gyp('commands.gyp', '--debug', 'variables', stdout=expect, ignore_line_numbers=True) # Verify the...
"""Provides an API for generating Event protocol buffers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os.path import time from tensorflow.core.framework import graph_pb2 from tensorflow.core.framework import summary_pb2 from tensorflow.core.p...
import unittest from mantid.geometry import CrystalStructure class CrystalStructureTest(unittest.TestCase): def test_creation(self): # Some valid constructions self.assertTrue(self.createCrystalStructureOrRaise("5.43 5.43 5.43", "F d -3 m", "Al 1/3 0.454 1/12 1.0 0.01")) self.assertTrue(se...
__author__ = "Cyril Jaquier" __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" import os, shlex from .configreader import DefinitionInitConfigReader from ..server.action import CommandAction from ..helpers import getLogger # Gets the instance of the logger. logSys = getLogger(__name__) class Fi...
import stem.response import stem.socket class MapAddressResponse(stem.response.ControlMessage): """ Reply for a MAPADDRESS query. Doesn't raise an exception unless no addresses were mapped successfully. :var dict entries: mapping between the original and replacement addresses :raises: * :class:`stem.O...
#!/usr/bin/env python '''Testing flat map allow_oob enforcement. Press 0-9 to set the size of the view in the window (1=10%, 0=100%) Press arrow keys to move view focal point (little ball) around map. Press "o" to turn allow_oob on and off. You should see no black border with allow_oob=False. Press escape or close...
import sys import unittest from test import test_support from UserList import UserList # We do a bit of trickery here to be able to test both the C implementation # and the Python implementation of the module. # Make it impossible to import the C implementation anymore. sys.modules['_bisect'] = 0 # We must also handl...
r""" ***************************************************** **espressopp.storage.DomainDecompositionNonBlocking** ***************************************************** .. function:: espressopp.storage.DomainDecompositionNonBlocking(system, nodeGrid, cellGrid) :param system: :param nodeGrid: :param cellGrid: ...
from gnuradio import gr from gnuradio import audio from gnuradio import blocks from gnuradio import vocoder def build_graph(): tb = gr.top_block() src = audio.source(8000) src_scale = blocks.multiply_const_ff(32767) f2s = blocks.float_to_short() enc = vocoder.g723_40_encode_sb() dec = vocoder.g...
import json from mock import MagicMock, patch, call from path import Path import pytest import sys d = Path('__file__').parent.abspath() / 'hooks' sys.path.insert(0, d.abspath()) from lib.registrator import Registrator class TestRegistrator(): def setup_method(self, method): self.r = Registrator() ...
import platform import shlex def _load_dist_subclass(cls, *args, **kwargs): ''' Used for derivative implementations ''' subclass = None distro = kwargs['module'].params['distro'] # get the most specific superclass for this platform if distro is not None: for sc in cls.__subclasses...
"""Tests for the experimental input pipeline ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from os import path import shutil import tempfile from tensorflow.contrib.data.python.ops import dataset_ops from tensorflow.python.framework import dtypes...
"""\ Augment the "bgen" package with definitions that are useful on the Apple Macintosh. Intended usage is "from macsupport import *" -- this implies all bgen's goodies. """ # Import everything from bgen (for ourselves as well as for re-export) from bgen import * # Simple types Boolean = Type("Boolean"...
import kdb, unittest TEST_NS = "user/tests/swig_py3" class Constants(unittest.TestCase): def setUp(self): pass def test_kdbconfig_h(self): self.assertIsInstance(kdb.DB_SYSTEM, str) self.assertIsInstance(kdb.DB_USER, str) self.assertIsInstance(kdb.DB_HOME, str) self.assertIsInstance(kdb.DEBUG, int...
"""Inline bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.ops.distributions import bijector from tensorflow.python.util import deprecation __all__ = [ "Inline", ] class Inline(bijector.Bijector): """Bijector con...
data = ( 'dwaen', # 0x00 'dwaenj', # 0x01 'dwaenh', # 0x02 'dwaed', # 0x03 'dwael', # 0x04 'dwaelg', # 0x05 'dwaelm', # 0x06 'dwaelb', # 0x07 'dwaels', # 0x08 'dwaelt', # 0x09 'dwaelp', # 0x0a 'dwaelh', # 0x0b 'dwaem', # 0x0c 'dwaeb', # 0x0d 'dwaebs', # 0x0e 'dwaes', # 0x...
"""Common code for working with images """ from __future__ import absolute_import import itertools import glanceclient from oslo.config import cfg from ceilometer.openstack.common import timeutils from ceilometer import plugin from ceilometer import sample class _Base(plugin.PollsterBase): @staticmethod d...
# -*- coding: utf8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from unittest2 import TestCase from pylijm.list import List class TestDict(TestCase): @property def fixture(self): return List(int) def test_init_good(self): Fix = self.fixture ...
import pytest def test_audit_biosample_characterization_review_lane_not_required( testapp, biosample_characterization, review, ): testapp.patch_json( biosample_characterization['@id'], { 'review': review, 'characterization_method': 'immunoprecipitati...
import crossovered_budget_report import analytic_account_budget_report import budget_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
from cinder.i18n import _ from cinder.volume.drivers.coprhd.helpers import commoncoprhdapi as common class VirtualPool(common.CoprHDResource): URI_VPOOL = "/{0}/vpools" URI_VPOOL_SHOW = URI_VPOOL + "/{1}" URI_VPOOL_SEARCH = URI_VPOOL + "/search?name={1}" def vpool_show_uri(self, vpooltype, uri): ...
#!/usr/bin/python -u import libxml2 import sys # Memory debug specific libxml2.debugMemory(1) doc = libxml2.newDoc("1.0") comment = doc.newDocComment("This is a generated document") doc.addChild(comment) pi = libxml2.newPI("test", "PI content") doc.addChild(pi) root = doc.newChild(None, "doc", None) ns = root.newNs("...
import uuid from django import http from django.contrib.syndication.views import Feed from django.shortcuts import get_object_or_404 from django.utils.feedgenerator import Rss201rev2Feed as RSS from django.utils.translation import ugettext from olympia import amo from olympia.activity.models import ActivityLog from o...
from weboob.tools.test import BackendTest from weboob.capabilities.base import NotLoaded class ParolesmaniaTest(BackendTest): BACKEND = 'parolesmania' def test_search_song_n_get(self): l_lyrics = list(self.backend.iter_lyrics('song', 'chien')) for songlyrics in l_lyrics: assert so...
# coding: utf-8 # # Talks markdown generator for academicpages # # Takes a TSV of talks with metadata and converts them for use with [academicpages.github.io](academicpages.github.io). This is an interactive Jupyter notebook ([see more info here](http://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is...
""" Support for bounce message generation. """ import StringIO import rfc822 import time import os from twisted.mail import smtp BOUNCE_FORMAT = """\ From: postmaster@%(failedDomain)s To: %(failedFrom)s Subject: Returned Mail: see transcript for details Message-ID: %(messageID)s Content-Type: multipart/report; repo...
from .core import Filter from c7n.exceptions import PolicyValidationError from c7n.utils import type_schema from c7n.policy import Policy class Missing(Filter): """Assert the absence of a particular resource. Intended for use at a logical account/subscription/project level This works as an effectively ...
#!/usr/bin/env python # Convert calls from Canvas, cn.MOPS, CNVnator, ERDS, Genome STRiP, or RDXplorer to a common format # Usage example: # convert_CNV_calls_to_common_format.py input_filename name_of_caller # name_of_caller must be one of "Canvas", "cn.MOPS", "CNVnator", "ERDS", "Genome_STRiP" (note underscore), or ...
"""Build a sentiment analysis / polarity model Sentiment analysis can be casted as a binary text classification problem, that is fitting a linear classifier on features extracted from the text of the user messages so as to guess wether the opinion of the author is positive or negative. In this examples we will use a ...
# vim: ts=4 sw=4 expandtab import HTMLParser import unittest class _Parser(HTMLParser.HTMLParser): def __init__(self): HTMLParser.HTMLParser.__init__(self) self._tags = [] def handle_starttag(self, tag, attributes): if tag.lower() == 'script': attr = dict(attributes) ...
import numpy import scipy.integrate.odepack from scipy.sparse.linalg import LinearOperator from scipy.ndimage.filters import convolve from scipy.sparse.linalg import gmres import pyopencl as cl import pyopencl.array as cl_array from pyopencl.array import vec import math class CrankNicIntegrator: def __init__(self,...
import os from config.utils import DotDict, namedtuple_with_defaults, zip_namedtuple, config_as_dict RandCropper = namedtuple_with_defaults('RandCropper', 'min_crop_scales, max_crop_scales, \ min_crop_aspect_ratios, max_crop_aspect_ratios, \ min_crop_overlaps, max_crop_overlaps, \ min_crop_sample_cover...
from ctypes import c_void_p from django.contrib.gis.gdal.error import GDALException from django.utils import six class GDALBase(object): """ Base object for GDAL objects that has a pointer access property that controls access to the underlying C pointer. """ # Initially the pointer is NULL. _...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils._text import to_native from ansible.module_utils.ec2 import HAS_BOTO3, boto3_tag_list_to_ansible_dict from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase try: from __...
from __future__ import absolute_import, division, unicode_literals from pip._vendor.six import text_type from lxml import etree from ..treebuilders.etree import tag_regexp from . import _base from .. import ihatexml def ensure_str(s): if s is None: return None elif isinstance(s, text_type): ...
# -*- coding: utf-8 -*- r""" werkzeug.contrib.securecookie ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module implements a cookie that is not alterable from the client because it adds a checksum the server checks for. You can use it as session replacement if all you have is a user id or something to mark ...
from setuptools import find_packages from setuptools import setup package_name = 'demo_nodes_py' setup( name=package_name, version='0.15.0', packages=find_packages(exclude=['test']), data_files=[ ('share/ament_index/resource_index/packages', ['resource/' + package_name]), (...
import time from lxml import etree from datetime import datetime from openerp.osv import fields, orm from openerp.tools.translate import _ def previous_year_date(date, nb_prev=1): if not date: return False parsed_date = datetime.strptime(date, '%Y-%m-%d') previous_date = datetime(year=parsed_date...
"""Parent classes for quantum chemistry program input and output file formats. """ import re class InputFormat(object): def __init__(self, mem, mtd, bas, mol, sys, cast): # total job memory in MB self.memory = mem # computational method self.method = mtd.lower() # qcdb.Mo...
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # 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 Lic...
import command_common import logging import manifest_util def Info(manifest, bundle_names): valid_bundles, invalid_bundles = command_common.GetValidBundles(manifest, bundle_names) if invalid_bundles: logging.warn('Unknown bundle(s): %s\n' % (', ...
"""Starts a local HTTP server which displays layout test failures (given a test results directory), provides comparisons of expected and actual results (both images and text) and allows one-click rebaselining of tests.""" from webkitpy.common import system from webkitpy.common.net.resultsjsonparser import for_each_tes...
from __future__ import unicode_literals import sys from pre_commit import color from pre_commit import five def get_hook_message( start, postfix='', end_msg=None, end_len=0, end_color=None, use_color=None, cols=80, ): """Prints a message for running a hook...
__author__ = 'Thomas Rueckstiess, <EMAIL>' from scipy import reshape, dot, outer, eye from pybrain.structure.connections import FullConnection class FullNotSelfConnection(FullConnection): """Connection which connects every element from the first module's output buffer to the second module's input buffer in a...
""" Helper for looping over sequences, particular in templates. Often in a loop in a template it's handy to know what's next up, previously up, if this is the first or last item in the sequence, etc. These can be awkward to manage in a normal Python loop, but using the looper you can get a better sense of the context....
{ 'name': 'Sale Team', 'version': '1.0', 'author': 'OpenERP SA', 'category': 'Sales Management', 'summary': 'Sales Team', 'description': """ Using this application you can manage Sales Team with CRM and/or Sales ======================================================================= """, ...
import pytest import tvm from tvm import te import pickle as pkl def test_schedule_create(): m = te.size_var("m") n = te.size_var("n") l = te.size_var("l") A = te.placeholder((m, l), name="A") B = te.placeholder((n, l), name="B") AA = te.compute((m, l), lambda i, j: A[i, j]) T = te.compute...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleError, AnsibleFilterError try: import jmespath HAS_LIB = True except ImportError: HAS_LIB = False def json_query(data, expr): '''Query data using jmespath query language ( http:/...
# -*- coding: utf-8 -*- """ Module defining unit prefixe class and some constants. Constant dict for SI and binary prefixes are defined as PREFIXES and BIN_PREFIXES. """ from sympy import sympify class Prefix(object): """ This class represent prefixes, with their name, symbol and factor. Prefixes are ...
""" XML serializer. """ from __future__ import unicode_literals from collections import OrderedDict from xml.dom import pulldom from xml.sax import handler from xml.sax.expatreader import ExpatParser as _ExpatParser from django.apps import apps from django.conf import settings from django.core.serializers import bas...
"""Statistics analyzer for HotShot.""" import profile import pstats import hotshot.log from hotshot.log import ENTER, EXIT def load(filename): return StatsLoader(filename).load() class StatsLoader: def __init__(self, logfn): self._logfn = logfn self._code = {} self._stack = [] ...
"""Tests for Uniform distribution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import importlib import numpy as np from tensorflow.python.eager import backprop from tensorflow.python.framework import constant_op from tensorflow.python.framework imp...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pants.backend.android.tasks.zipalign import Zipalign from pants_test.android.test_android_base import TestAndroidBase, distribution class TestZipalig...
"""Tests for letsencrypt.plugins.disco.""" import pkg_resources import unittest import mock import zope.interface from letsencrypt import errors from letsencrypt import interfaces from letsencrypt.plugins import standalone EP_SA = pkg_resources.EntryPoint( "sa", "letsencrypt.plugins.standalone", attrs=("Aut...
#!/usr/bin/env python ######################################################################## # File : dirac-admin-get-pilot-output ######################################################################## """ Retrieve output of a Grid pilot Usage: dirac-admin-get-pilot-output [options] ... PilotID ... Arguments...
"""Support for deCONZ sensors.""" from pydeconz.sensor import ( Battery, Consumption, Daylight, Humidity, LightLevel, Power, Pressure, Switch, Temperature, Thermostat, ) from homeassistant.components.sensor import DOMAIN from homeassistant.const import ( ATTR_TEMPERATURE, ...
"""add task fails journal table Revision ID: 64de9cddf6c9 Revises: 211e584da130 Create Date: 2016-08-03 14:02:59.203021 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '64de9cddf6c9' down_revision = '211e584da130' branch_labels = None depends_on = None def upg...
import os import sys from time import time from trace import IsTrace _NOT_TTY = not os.isatty(2) class Progress(object): def __init__(self, title, total=0, units=''): self._title = title self._total = total self._done = 0 self._lastp = -1 self._start = time() self._show = False self._uni...
microcode = ''' def macroop FLDZ { lfpimm ufp1, 0.0 movfp st(-1), ufp1, spm=-1 }; def macroop FLD1 { lfpimm ufp1, 1.0 movfp st(-1), ufp1, spm=-1 }; def macroop FLDPI { lfpimm ufp1, 3.14159265359 movfp st(-1), ufp1, spm=-1 }; '''
#!/usr/bin/env python import argparse import gzip import os from collections import OrderedDict import yaml from Bio.SeqIO.QualityIO import FastqGeneralIterator OUTPUT_DBKEY_DIR = 'output_dbkey' OUTPUT_METRICS_DIR = 'output_metrics' def get_sample_name(file_path): base_file_name = os.path.basename(file_path) ...
############################################# # This is a basic script to emulate the hardware of # an Arduino microcontroller. The VirtualDevice # service will execute this script when # createVirtualArduino(port) is called import time import math import threading from random import randint from org.myrobotlab.codec ...
from subprocess import check_output, check_call, CalledProcessError from os import unlink, devnull from os.path import isfile from tempfile import NamedTemporaryFile from fractions import Fraction from six.moves import zip from . import cglpk from .wrappers import * # detect paths to system calls for esolver and gzip...
from django.conf.urls import patterns, url from .views import ( LoginView, LogoutView, RecoverPasswordCompleteView, RecoverPasswordConfirmView, RecoverPasswordSentView, RecoverPasswordView ) urlpatterns = patterns( '', url(r'^login/$', LoginView.as_view(), name='login'), url(r'^log...
import time import json import pprint import hashlib import struct import re import base64 import httplib import sys from multiprocessing import Process ERR_SLEEP = 15 MAX_NONCE = 1000000L settings = {} pp = pprint.PrettyPrinter(indent=4) class BitcoinRPC: OBJID = 1 def __init__(self, host, port, username, passwo...
import sys from twisted.trial import unittest try: import cPickle as pickle except ImportError: import pickle try: import cStringIO as StringIO except ImportError: import StringIO # Twisted Imports from twisted.persisted import styles, aot, crefutil class VersionTestCase(unittest.TestCase): de...
import wx import wx.lib.newevent from atom.api import Int, Typed from enaml.widgets.spin_box import ProxySpinBox from .wx_control import WxControl #: The changed event for the custom spin box wxSpinBoxEvent, EVT_SPIN_BOX = wx.lib.newevent.NewEvent() class wxProperSpinBox(wx.SpinCtrl): """ A custom wx spin co...
from django import template from django.core.urlresolvers import reverse from ..models import LegalPage register = template.Library() class LegalPageNode(template.Node): def __init__(self, context_name): self.context_name = context_name def render(self, context): lps = LegalPage.objects.l...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.nxos import nxos_argument_spec, run_commands from ansible.module_utils.basic import AnsibleModule def checkpoint(filename, module): commands = ['te...
import time from openerp.report import report_sxw class request_quotation(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(request_quotation, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'user': self.pool.get...
from __future__ import unicode_literals import frappe from frappe.utils import cstr, flt from frappe import _, msgprint from frappe.model.document import Document class AuthorizationRule(Document): def check_duplicate_entry(self): exists = frappe.db.sql("""select name, docstatus from `tabAuthorization Rule` wh...
import logging from rx.internal import PriorityQueue, ArgumentOutOfRangeException from .schedulerbase import SchedulerBase from .scheduleditem import ScheduledItem from .scheduleperiodic import SchedulePeriodic log = logging.getLogger("Rx") class VirtualTimeScheduler(SchedulerBase): """Virtual Scheduler. This ...
"""TLS Lite + poplib.""" import socket from poplib import POP3 from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper # POP TLS PORT POP3_TLS_PORT = 995 class POP3_TLS(POP3, ClientHelper): """This class extends L{poplib.POP3} with TLS support.""" ...
""" Settings Model A very rudimentary settings implementation which is intended to store our non-mission-critical options which can be edited via the admin UI. .. todo: Rather than fetch one option at a time, load all settings into an object with attribute-style access. """ from sqlalchemy import Table, For...
import os import unittest from unittest import mock from dmoj.config import InvalidInitException from dmoj.problem import Problem, ProblemDataManager class ProblemTest(unittest.TestCase): def setUp(self): self.data_patch = mock.patch('dmoj.problem.ProblemDataManager') data_mock = self.data_patch....
""" Tests of student.roles """ import ddt from django.test import TestCase from courseware.tests.factories import UserFactory, StaffFactory, InstructorFactory from student.tests.factories import AnonymousUserFactory from student.roles import ( GlobalStaff, CourseRole, CourseStaffRole, CourseInstructorRole, Or...
from PyQt4 import QtGui, QtCore import sys, os import models from pluginmgr import ShelfView # This plugin lists the books by tag EBOOK_EXTENSIONS=['epub','mobi','pdf'] class Catalog(ShelfView): title = "Books By Tag" itemText = "Tags" items = {} def showList(self, search = None): """Ge...