content
stringlengths
4
20k
"""Test for google.protobuf.internal.wire_format.""" __author__ = '<EMAIL> (Will Robinson)' import unittest from google.protobuf import message from google.protobuf.internal import wire_format class WireFormatTest(unittest.TestCase): def testPackTag(self): field_number = 0xabc tag_type = 2 self.asser...
import unittest from test import support from test.test_urllib2 import sanepathname2url import os import socket import urllib.error import urllib.request import sys try: import ssl except ImportError: ssl = None support.requires("network") TIMEOUT = 60 # seconds def _retry_thrice(func, exc, *args, **kwarg...
import time, subprocess, optparse, sys, socket, os sys.path.append("../") import rtest as rtest solve = "liquid ".split() null = open("/dev/null", "w") now = (time.asctime(time.localtime(time.time()))).replace(" ","_") logfile = "../tests/logs/regrtest_results_%s_%s" % (socket.gethostn...
from boto.regioninfo import RegionInfo, get_regions class S3RegionInfo(RegionInfo): def connect(self, **kw_params): """ Connect to this Region's endpoint. Returns an connection object pointing to the endpoint associated with this region. You may pass any of the arguments accepted ...
"""Utility functions for reading/writing graphs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import os.path from google.protobuf import text_format from tensorflow.python.framework import ops from tensorflow.python.lib.io import file_io fro...
""" Provides "diff-like" comparison of images. Currently relies on matplotlib for image processing so limited to PNG format. """ from __future__ import (absolute_import, division, print_function) import os.path import shutil import matplotlib.pyplot as plt import matplotlib.image as mimg import matplotlib.widgets ...
"""Steps and utility functions for taking screenshots.""" import uuid from lettuce import ( after, step, world, ) import os.path import json def set_save_directory(base, source): """Sets the root save directory for saving screenshots. Screenshots will be saved in subdirectories under this di...
import frappe from frappe.utils import cstr import re def execute(): item_details = frappe._dict() for d in frappe.db.sql("select name, description from `tabItem`", as_dict=1): description = cstr(d.description).strip() new_desc = extract_description(description) item_details.setdefault(d.name, frappe._dict({ ...
""" byceps.services.ticketing.models.ticket_event ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2019 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from datetime import datetime from typing import Any, Dict from ....database import db, generate_uuid from ....util.instances...
"""Tests for distutils.command.install_data.""" import sys import os import unittest from distutils.command.install_lib import install_lib from distutils.extension import Extension from distutils.tests import support from distutils.errors import DistutilsOptionError from test.support import run_unittest class Install...
"""The ingestion package interface.""" __revision__ = "$Id$" from datetime import datetime try: from hashlib import md5 except: import md5 from .config import CFG_BIBINGEST_VERSIONING, \ CFG_BIBINGEST_ONE_STORAGE_ENGINE_INSTANCE_PER_STORAGE_ENGINE # ******************** # Validation functions # *******...
import os import sys import shutil import subprocess import contextlib from collections import namedtuple import bcbio.bed as bed from bcbio.pipeline import config_utils from bcbio.distributed.transaction import file_transaction, tx_tmpdir from bcbio.utils import (safe_makedir, file_exists, is_gzipped) from bcbio.prov...
import os import warnings from hyperspy.defaults_parser import preferences preferences.General.show_progressbar = False # Check if we should fail on external deprecation messages fail_on_external = os.environ.pop('FAIL_ON_EXTERNAL_DEPRECATION', False) if isinstance(fail_on_external, str): fail_on_external = (fail...
from boto.s3.user import User class ResultSet(list): """ The ResultSet is used to pass results back from the Amazon services to the client. It is light wrapper around Python's :py:class:`list` class, with some additional methods for parsing XML results from AWS. Because I don't really want any dep...
"""Redo the builtin repr() (representation) but with limits on most sizes.""" __all__ = ["Repr","repr"] import __builtin__ from itertools import islice class Repr: def __init__(self): self.maxlevel = 6 self.maxtuple = 6 self.maxlist = 6 self.maxarray = 5 self.maxdict = 4 ...
# -*- coding: utf-8 -*- from trapp.checker import Checker from trapp.competition import Competition class CheckerGames(Checker): def reviewCompetition(self, competition, year): self.log.message('Reviewing competition ' + str(competition)) # Get years this competition was held sql = ("SEL...
# -*- coding: utf-8 -*- """This file contains MRUListEx Windows Registry plugins.""" import abc import logging import construct from plaso.events import windows_events from plaso.lib import binary from plaso.parsers import winreg from plaso.parsers.shared import shell_items from plaso.parsers.winreg_plugins import i...
import datetime import decimal import calendar from django.template import loader from django.http import HttpResponseNotFound from django.core.serializers.json import DjangoJSONEncoder from django.http import HttpResponse from django.utils.encoding import smart_unicode from django.db import models from django.utils.h...
try: from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver from libcloud.common.google import GoogleBaseError, QuotaExceededError, \ ResourceExistsError, ResourceNotFoundError, ResourceInUseError _ = Provider.GCE HAS_LIBCLOUD = True except ImportEr...
# stdlib from hashlib import md5 import time # 3rd party import requests # project from checks import AgentCheck class Mesos(AgentCheck): SERVICE_CHECK_NAME = "mesos.can_connect" def check(self, instance): """ DEPRECATED: This generic Mesosphere check is deprecated not actively deve...
"""Weak reference support for Python. This module is an implementation of PEP 205: http://www.python.org/dev/peps/pep-0205/ """ # Naming convention: Variables named "wr" are weak reference objects; # they are called this instead of "ref" to avoid name collisions with # the module-global ref() function imported from ...
"""SCons.Scanner.Fortran This module implements the dependency scanner for Fortran code. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentati...
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2015-2016 Rapptz 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, including without limitation the rights to u...
from invenio.legacy.dbquery import run_sql depends_on = ['invenio_release_1_1_0'] def info(): return "New bibcheck_rules table" def do_upgrade(): run_sql(""" CREATE TABLE IF NOT EXISTS bibcheck_rules ( name varchar(150) NOT NULL, last_run datetime NOT NULL default '0000-00-00', PRIMARY KEY (name) ) ENG...
# -*- coding: utf-8 -*- ''' #@summary: DbRowFactory is one common factory to convert db row tuple into user-defined class object. It is supported SqlAlchemy, and any database modules conformed to Python Database API Specification v2.0. e.g. cx_Oracle, zxJDBC #@note: Note 1: The DbRowFactory wil...
"""Contains the Tilt mode code""" # tilt.py # Mission Pinball Framework # Written by Brian Madden & Gabe Knuth # Released under the MIT License. (See license info at the end of this file.) # Documentation and more info at http://missionpinball.com/mpf from mpf.system.config import CaseInsensitiveDict from mpf.system...
# -*- coding: utf-8 -*- # # documentation build configuration file, created by # sphinx-quickstart on Sat Sep 27 13:23:22 2008-2009. # # This file is execfile()d with the current directory set to its # containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleab...
from __future__ import unicode_literals import time from django.core.cache import cache class BaseThrottle(object): """ A simplified, swappable base class for throttling. Does nothing save for simulating the throttling API and implementing some common bits for the subclasses. Accepts a number of...
#! /usr/bin/env python """Tool for measuring execution time of small code snippets. This module avoids a number of common traps for measuring execution times. See also Tim Peters' introduction to the Algorithms chapter in the Python Cookbook, published by O'Reilly. Library usage: see the Timer class. Command line ...
import sys as s from parsingMatch import parseAllFact from parsingFasta import parseFasta def sanitizeNode(node): if not node or not (len(node) == 2): #It means this node cannot appear in the taxonomic tree return None else: return node #@allMatches is a dictionary of (key=sa...
import os import sys import warnings import imp import opcode # opcode is not a virtualenv module, so we can use it to find the stdlib # Important! To work on pypy, this must be a module that resides in the # lib-python/modified-x.y.z directory dirname = os.path.dirname distutils_path = o...
# -*- coding: utf-8 -*- from django.contrib.auth.models import User from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Band(models.Model): name = models.CharField(max_length=100) bio = models.TextField() sign_date = models.DateFiel...
import os def main(): import sys #Separate the nose params and the pydev params. pydev_params = [] other_test_framework_params = [] found_other_test_framework_param = None NOSE_PARAMS = '--nose-params' PY_TEST_PARAMS = '--py-test-params' for arg in sys.argv[1:]: if not found_...
""" A splash screen widget with support for positioning of the message text. """ from PyQt4.QtGui import ( QSplashScreen, QWidget, QPixmap, QPainter, QTextDocument, QTextBlockFormat, QTextCursor, QApplication ) from PyQt4.QtCore import Qt from .utils import is_transparency_supported class SplashScreen(QSp...
######################################################################## # File : FC_Scaling_test ######################################################################## """ Test suite for a generic File Catalog scalability tests """ __RCSID__ = "$Id$" from DIRAC.Core.Base import Script from DIRAC import S_OK im...
from openerp.osv import fields, osv from openerp.tools.translate import _ class survey_print_statistics(osv.osv_memory): _name = 'survey.print.statistics' _columns = { 'survey_ids': fields.many2many('survey', string="Survey", required="1"), } def action_next(self, cr, uid, ids, context=None): ...
"""Test correct treatment of hex/oct constants. This is complex because of changes due to PEP 237. """ import unittest class TestHexOctBin(unittest.TestCase): def test_hex_baseline(self): # A few upper/lowercase tests self.assertEqual(0x0, 0X0) self.assertEqual(0x1, 0X1) self.ass...
# -*- coding: utf-8 -*- """ ====================================================================== Structure generators (:mod:`sknano.generators`) ====================================================================== .. currentmodule:: sknano.generators Contents ======== Nanostructure generators -------------------...
from msrest.serialization import Model class NodeFile(Model): """Information about a file or directory on a compute node. :param name: The file path. :type name: str :param url: The URL of the file. :type url: str :param is_directory: Whether the object represents a directory. :type is_di...
"""distutils.spawn Provides the 'spawn()' function, a front-end to various platform- specific functions for launching another program in a sub-process. Also provides the 'find_executable()' to search the path for a given executable name. """ import sys import os from distutils.errors import DistutilsPlatformError, D...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import re from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ne...
import collections import mock from oslo_serialization import jsonutils import testtools from nova import db from nova import objects from nova.objects import pci_device_pool from nova.tests.functional.v3 import api_sample_base from nova.tests.functional.v3 import test_servers skip_msg = "Bug 1426241" fake_db_dev_1...
"""Classes used to represent recipes.""" import env import action import io import os import os.path import sys file_db = { } # file database ext_db = { } # extension database # base classes class File(env.MapEnv): """Representation of files.""" path = None recipe = None is_goal = False is_target = False is_...
import re from django.db import connection from django.test import TestCase, skipUnlessDBFeature from django.utils.functional import cached_property test_srs = ({ 'srid': 4326, 'auth_name': ('EPSG', True), 'auth_srid': 4326, # Only the beginning, because there are differences depending on installed li...
""" This module replicates the miislita vector spaces from "A Linear Algebra Approach to the Vector Space Model -- A Fast Track Tutorial" by Dr. E. Garcia, <EMAIL> See http://www.miislita.com for further details. """ from __future__ import division # always use floats from __future__ import with_statement import l...
from __future__ import unicode_literals import os import frappe from frappe.utils import get_request_site_address, cstr from frappe import _ @frappe.whitelist() def get_dropbox_authorize_url(): sess = get_dropbox_session() request_token = sess.obtain_request_token() return_address = get_request_site_address(True) \...
import pygame import os from random import randint UP = 3 DOWN = 7 RIGHT = 5 LEFT = 9 EXEC_DIR = os.path.dirname(__file__) class Monster(pygame.sprite.Sprite): """ This is our main monster class """ def __init__(self, initial_position, type, direction): pygame.sprite.Sprite.__init__(self) self...
import inspect import rtorrent import re from rtorrent.common import bool_to_int, convert_version_tuple_to_str,\ safe_repr from rtorrent.err import MethodError from rtorrent.compat import xmlrpclib def get_varname(rpc_call): """Transform rpc method into variable name. @newfield example: Example @exam...
""" An implementation of a RequestCache. This cache is reset at the beginning and end of every request. """ import crum import threading class _RequestCache(threading.local): """ A thread-local for storing the per-request cache. """ def __init__(self): super(_RequestCache, self).__init__() ...
""" :class:`.OpenCage` is the Opencagedata geocoder. """ from geopy.compat import urlencode from geopy.geocoders.base import Geocoder, DEFAULT_TIMEOUT, DEFAULT_SCHEME from geopy.exc import ( GeocoderQueryError, GeocoderQuotaExceeded, ) from geopy.location import Location from geopy.util import logger __all__...
from django.db.transaction import non_atomic_requests from django.forms.models import modelformset_factory from django.shortcuts import redirect from olympia import amo from olympia.amo.utils import render from olympia.zadmin.decorators import admin_required from .forms import DiscoveryModuleForm from .models import ...
from django.db import models from .base import BaseModel class TagManager(models.Manager): """Manager that filters out system tags by default. """ def get_queryset(self): return super(TagManager, self).get_queryset().filter(system=False) class Tag(BaseModel): name = models.CharField(db_inde...
from utility import to_seq def difference (b, a): """ Returns the elements of B that are not in A. """ result = [] for element in b: if not element in a: result.append (element) return result def intersection (set1, set2): """ Removes from set1 any items which don't appear...
"""Unit test utilities for Google C++ Testing Framework.""" __author__ = '<EMAIL> (Zhanyong Wan)' import atexit import os import shutil import sys import tempfile import unittest _test_module = unittest # Suppresses the 'Import not at the top of the file' lint complaint. # pylint: disable-msg=C6204 try: import sub...
""" Danish-language mappings for language-dependent features of Docutils. """ __docformat__ = 'reStructuredText' labels = { # fixed: language-dependent 'author': 'Forfatter', 'authors': 'Forfattere', 'organization': 'Organisation', 'address': 'Adresse', 'contact': 'Kontakt', ...
"""Shows file metadata. """ import os from beets.plugins import BeetsPlugin from beets import ui from beets import mediafile from beets import util def info(paths): # Set up fields to output. fields = list(mediafile.MediaFile.fields()) fields.remove('art') fields.remove('images') # Line format....
import unittest import functools import math import numpy from operator import mul import six import chainer from chainer.backends import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr from chainer.testing import condition from chaine...
#!python -u # -*- coding: utf-8 -*- import sys import itertools from svgplotlib import Base class Bar(Base): """ Simple vertical bar plot Example:: graph = Bar( (10,50,100), width = 1000, height = 500, titleColor = 'blue', title = 'Simple b...
# META: timeout=long from tests.support.asserts import assert_error, assert_dialog_handled, assert_success from tests.support.fixtures import create_dialog from tests.support.inline import inline alert_doc = inline("<script>window.alert()</script>") def maximize(session): return session.transport.send("POST", ...
# Debian packaging tools: Configuration defaults. # # Last Change: February 6, 2020 # URL: https://github.com/xolox/python-deb-pkg-tools """Configuration defaults for the `deb-pkg-tools` package.""" # Standard library modules. import os # External dependencies. from humanfriendly import parse_path # Public identifi...
""" Package containing all pip commands """ from pip.commands.bundle import BundleCommand from pip.commands.completion import CompletionCommand from pip.commands.freeze import FreezeCommand from pip.commands.help import HelpCommand from pip.commands.list import ListCommand from pip.commands.search import SearchComman...
import logging from itertools import product from lnst.Common.Parameters import Param, IntParam, StrParam from lnst.Common.IpAddress import ipaddress from lnst.Controller import HostReq, DeviceReq, RecipeParam from lnst.Recipes.ENRT.BaseEnrtRecipe import BaseEnrtRecipe from lnst.Recipes.ENRT.ConfigMixins.OffloadSubConf...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Provides de-serialization and in-stream patch applying capabilities for PE Files """ __author__ = 'A.A.' # Unpack binary data from struct import unpack_from # Holds an single patch part class PePatchPart(object): # Constructor def __init__(self, mem, ...
"""Testing facility for conkit.io.PdbIO""" __author__ = "Felix Simkovic" __date__ = "26 Oct 2016" import os import unittest from conkit.io.pdb import PdbParser from conkit.io.tests.helpers import ParserTestCase class TestPdbIO(ParserTestCase): def test_read_1(self): content = """ATOM 1 N TYR A ...
# -*- coding: utf-8 -*- """ jinja2.testsuite.core_tags ~~~~~~~~~~~~~~~~~~~~~~~~~~ Test the core tags like for and if. :copyright: (c) 2010 by the Jinja Team. :license: BSD, see LICENSE for more details. """ import unittest from jinja2.testsuite import JinjaTestCase from jinja2 import Environment...
# Monitor the system for dropped packets and proudce a report of drop locations and counts import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * drop_log = {} kallsyms = [] def...
class ModuleDocFragment(object): # Standard openstack documentation fragment DOCUMENTATION = ''' options: cloud: description: - Named cloud to operate against. Provides default values for I(auth) and I(auth_type). This parameter is not needed if I(auth) is provided or if OpenStack O...
import os import tempfile import re from pip.backwardcompat import urlparse from pip.log import logger from pip.util import rmtree, display_path, call_subprocess from pip.vcs import vcs, VersionControl from pip.download import path_to_url class Bazaar(VersionControl): name = 'bzr' dirname = '.bzr' repo_na...
import os import subprocess import json import requests from datetime import datetime, timedelta from reportlab.lib import colors from reportlab.platypus import ( SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image ) from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet from r...
import logging import time import random from autotest.client.shared import error @error.context_aware def run(test, params, env): """ Emulate the poweroff under IO workload(dd so far) with signal SIGKILL. 1) Boot a VM 2) Add IO workload for guest OS 3) Sleep for a random time 4) Kill the VM...
""" Verifies that the default STRIP_STYLEs match between different generators. """ import TestGyp import re import subprocess import sys import time if sys.platform == 'darwin': test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode']) CHDIR='strip' test.run_gyp('test-defaults.gyp', chdir=CHDIR) test.buil...
import numpy as np from numpy.testing import assert_allclose import pytest from pytest import raises from astropy import units as u from astropy.wcs import WCS from astropy.tests.helper import assert_quantity_allclose from astropy.wcs.wcsapi.utils import deserialize_class, wcs_info_str def test_construct(): r...
""" The I{service definition} provides a textual representation of a service. """ from logging import getLogger from suds import * import suds.metrics as metrics from suds.sax import Namespace log = getLogger(__name__) class ServiceDefinition: """ A service definition provides an object used to generate a te...
import re from hacking import core # N323: Found use of _() without explicit import of _! UNDERSCORE_IMPORT_FILES = [] string_translation = re.compile(r"[^_]*_\(\s*('|\")") translated_log = re.compile( r"(.)*LOG\.(audit|error|info|warn|warning|critical|exception)" r"\(\s*_\(\s*('|\")") underscore_import_c...
import logging import os import unittest from importlib import import_module from unittest import TestSuite, defaultTestLoader from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.test import SimpleTestCase, TestCase from django.test.utils import setup_test_environment, ...
"""Module storing implementations of PID providers.""" from __future__ import absolute_import, print_function from ..models import PersistentIdentifier, PIDStatus class BaseProvider(object): """Abstract class for persistent identifier provider classes.""" pid_type = None """Default persistent identifie...
import logging import xml.sax.handler import os from select import select from campus_factory.util.ExternalCommands import RunExternal class AvailableGlideins(xml.sax.handler.ContentHandler, object): # Command to query the collector for available glideins command = "condor_status -avail -const '(IsUndef...
from __future__ import unicode_literals import django from django.conf import settings from django.utils.module_loading import import_string from .routing import Router from .utils import name_that_thing class InvalidChannelLayerError(ValueError): pass class ChannelLayerManager(object): """ Takes a se...
"""Tests for Xception application.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.keras._impl import keras from tensorflow.python.platform import test class XceptionTest(test.TestCase): def test_with_top(s...
"""A parser for HTML and XHTML.""" # This file is based on sgmllib.py, but the API is slightly different. # XXX There should be a way to distinguish between PCDATA (parsed # character data -- the normal case), RCDATA (replaceable character # data -- only char and entity references and end tags are special) # and CDAT...
""" Meta Data Extension for Python-Markdown ======================================= This extension adds Meta Data handling to markdown. See <https://pythonhosted.org/Markdown/extensions/meta_data.html> for documentation. Original code Copyright 2007-2008 [Waylan Limberg](http://achinghead.com). All changes Copyrigh...
from __future__ import print_function __author__ = 'Michael Isik' from pybrain.supervised.evolino.gfilter import Filter, SimpleMutation from pybrain.supervised.evolino.variate import CauchyVariate from pybrain.supervised.evolino.population import SimplePopulation from pybrain.tools.validation import Validator from py...
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ PROVINCE_CHOICES = ( ('01', _('Arava')), ('02', _('Albacete')), ('03', _('Alacant')), ('04', _('Almeria')), ('05', _('Avila')), ('06', _('Badajoz')), ('07', _('Illes Balears')), ('08', _('Barcelona')), (...
from __future__ import unicode_literals from django.apps import apps from django.db import models def sql_flush(style, connection, only_django=False, reset_sequences=True, allow_cascade=False): """ Returns a list of the SQL statements used to flush the database. If only_django is True, then only table n...
from __future__ import unicode_literals import datetime import uuid from django.conf import settings from django.core.exceptions import FieldError, ImproperlyConfigured from django.db import utils from django.db.backends import utils as backend_utils from django.db.backends.base.operations import BaseDatabaseOperatio...
from django.template.defaultfilters import urlizetrunc from django.test import SimpleTestCase from django.utils.safestring import mark_safe from ..utils import setup class UrlizetruncTests(SimpleTestCase): @setup({ 'urlizetrunc01': '{% autoescape off %}{{ a|urlizetrunc:"8" }} {{ b|urlizetrunc:"8" }}{% e...
''' This is the chat client wallflower; it connects currently to a server hosted by CaveFox Telecommunications; but that can be changed to any server hosting the Wallflower_Server.py software package. ''' import pickle import requests import time import threading import hashlib message = '' startpoint = 0 endpoint = 0 ...
from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'dvr_host_macs', sa.Column('host', sa.String(length=255), nullable=False), sa.Column('mac_address', sa.String(length=32), nullable=False, unique=True), sa.PrimaryKeyConstraint('host') ...
""" Tests for geography support in PostGIS """ from __future__ import unicode_literals import os from unittest import skipUnless from django.contrib.gis.db.models.functions import Area, Distance from django.contrib.gis.gdal import HAS_GDAL from django.contrib.gis.measure import D from django.test import TestCase, ign...
from django.test.client import RequestFactory from bedrock.base.urlresolvers import reverse from nose.tools import eq_ from bedrock.mozorg.context_processors import funnelcake_param from bedrock.mozorg.tests import TestCase class TestFunnelcakeParam(TestCase): def setUp(self): self.rf = RequestFactory()...
# -*- coding: utf-8 -*- """ *************************************************************************** ScriptUtils.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ***************************...
from os import path from django.conf import settings from openstack_dashboard.test import helpers as test class ErrorPageTests(test.TestCase): """Tests for error pages.""" urls = 'openstack_dashboard.test.error_pages_urls' def test_500_error(self): with self.settings( TEMPLATES=...
# -*- coding: utf-8 -*- """ werkzeug.testsuite.security ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Tests the security helpers. :copyright: (c) 2014 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import os import unittest from werkzeug.testsuite import WerkzeugTestCase from werkzeug.securit...
""" Python 'utf-32' Codec """ import codecs, sys ### Codec APIs encode = codecs.utf_32_encode def decode(input, errors='strict'): return codecs.utf_32_decode(input, errors, True) class IncrementalEncoder(codecs.IncrementalEncoder): def __init__(self, errors='strict'): codecs.IncrementalEncoder.__ini...
# -*- coding: utf-8 -*- """ pythoncompat """ from .packages import chardet import sys # ------- # Pythons # ------- # Syntax sugar. _ver = sys.version_info #: Python 2.x? is_py2 = (_ver[0] == 2) #: Python 3.x? is_py3 = (_ver[0] == 3) #: Python 3.0.x is_py30 = (is_py3 and _ver[1] == 0) #: Python 3.1.x is_py31 =...
""" Functions for creating an Android.mk from already created dictionaries. """ import os def write_group(f, name, items, append): """Helper function to list all names passed to a variable. Args: f: File open for writing (Android.mk) name: Name of the makefile variable (e.g. LOCAL_CFLAGS) items: list...
# -*- coding: utf-8 -*- from pkgutil import get_data from yaml import load as load_yaml """ :mod:`dateparser`'s parsing behavior can be configured like below *``PREFER_DAY_OF_MONTH``* defaults to ``current`` and can have ``first`` and ``last`` as values:: >>> from dateparser.conf import settings >>> from da...
import crm from datetime import datetime from openerp.osv import fields, osv from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT from openerp.tools.translate import _ class crm_phonecall(osv.osv): """ Model for CRM phonecalls """ _name = "crm.phonecall" _description = "Phonecall" _order = "id desc...
""" We deal (mostly) with remote hosts. To avoid special casing each different commands (e.g. using `yum` as opposed to `apt`) we can make a one time call to that remote host and set all the special cases for running commands depending on the type of distribution/version we are dealing with. """ import logging from cep...
# coding=utf-8 """Tests for Django management commands""" import json from nose.plugins.attrib import attr from path import Path as path import shutil from StringIO import StringIO import tarfile from tempfile import mkdtemp import factory from django.conf import settings from django.core.management import call_comm...