content
stringlengths
4
20k
# -*- coding: utf-8 -*- from booktype.tests import TestCase from booktype.utils import permissions from booktype.apps.core.models import Permission class PermissionsUtilsTestCase(TestCase): """ Tests all methods in permissions.py module """ def setUp(self): self.app_name = 'foo_meh' s...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.mysql...
#!/usr/bin/env python from numpy import * parameter_list = [[10,3,15,2.1,1,1e-5,1],[20,4,15,2.2,2,1e-5,2]] def classifier_multiclassocas_modular (num_vec=10,num_class=3,distance=15,width=2.1,C=1,epsilon=1e-5,seed=1): from modshogun import RealFeatures, MulticlassLabels from modshogun import Math_init_random try: ...
import gevent from gevent import monkey monkey.patch_all() from gevent.greenlet import Greenlet from optparse import OptionParser import logging import time import codecs from collections import OrderedDict, defaultdict import json import wapiti from dashboard import LoupeDashboard from inputs import DEFAULT_INPUTS, D...
#!/usr/bin/env python import os import sys import subprocess from optparse import OptionParser SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PARAMETERS = None def doCMD(cmd): print "-->> \"%s\"" % cmd output = [] cmd_return_code = 1 cmd_proc = subprocess.Popen( cmd, stdout=subproce...
import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raise_message from sklearn.exceptions import NotFittedError from sklearn import datasets from sk...
"""Our app specific CEF loggers.""" from django.conf import settings from django.http import HttpRequest from cef import log_cef as _log_cef heka = settings.HEKA class CEFLogger: """Abstract base CEF logger. Class attributes to set in a concrete class: **sig_prefix** Prefix to the CEF signature....
""" Implementation of a function to read NetCDF files from Ocean Observatory Iniciative (OOI) """ import xarray as xr from ..waterframe import WaterFrame def read_nc_ooi(path, clean_data=True): """ Open a NetCDF file from OOI. This function was tested with CTD files. Web - https://oceanobservatori...
""" See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details on the presubmit API built into gcl. """ import re def CheckChange(input_api, output_api): """Checks the heapcheck suppressions files for bad data.""" sup_regex = re.compile('suppressions.*\.txt$') suppressions = {}...
from ctypes import c_void_p, c_uint32, c_buffer, byref from .Win32Structs import * def adjustDebugPrivileges(): privileges = TOKEN_PRIVILEGES() access_token = OpenProcessToken( GetCurrentProcess(), win32con.TOKEN_QUERY | win32con.TOKEN_ADJUST_PRIVILEGES) LookupPrivilegeValue( None, "SeDebugPrivileg...
try: import pyrax HAS_PYRAX = True except ImportError: HAS_PYRAX = False def find_database(instance, name): try: database = instance.get_database(name) except Exception: return False return database def save_database(module, cdb_id, name, character_set, collate): cdb = p...
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsColorScheme. .. note:: 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 2 of the License, or (at your option) any later version. """ __...
''' This module is for enhancing ansible's inventory parsing capability such that it can deal with hostnames specified using a simple pattern in the form of [beg:end], example: [1:5], [a:c], [D:G]. If beg is not specified, it defaults to 0. If beg is given and is left-zero-padded, e.g. '001', it is taken as a formatti...
from __future__ import unicode_literals import collections import json import os import random import re from .common import InfoExtractor from ..compat import ( compat_str, compat_urlparse, ) from ..utils import ( dict_get, ExtractorError, float_or_none, int_or_none, parse_duration, q...
from __future__ import absolute_import import contextlib import logging import logging.handlers import os try: import threading except ImportError: import dummy_threading as threading from pip.compat import WINDOWS from pip.utils import ensure_dir try: from pip._vendor import colorama # Lots of differen...
# coding: utf8 { '!langcode!': 'es', '!langname!': 'Español', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"actualice" es una expresión opcional como "campo1=\'nuevo_valor\'". No se puede actualizar o eliminar resultados de un JOIN', '%s %%{row} de...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import fnmatch import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( check_sdk, create_connection, get_dict_o...
from st2common.exceptions import db from st2common.models.system.common import ResourceReference def get_ref_from_model(model): if model is None: raise ValueError('Model has None value.') model_id = getattr(model, 'id', None) if model_id is None: raise db.StackStormDBObjectMalformedError('...
import logging import sys class ReplicationUtils(object): thisClassName = '(ReplicationUtils)' d = {'name_of_class': thisClassName} logger = logging.getLogger("namedLogger") anonLogger = logging.getLogger("anonymousLogger") def __init__(self, testClassInstance): super(ReplicationUtil...
from __future__ import absolute_import from __future__ import print_function # This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for the Earth and Planetary Sciences # Copyright (C) 2012 - 2015 by the BurnMan team, released under the GNU # GPL v2 or later. import argparse import os.path import s...
from spack import * class Xterm(AutotoolsPackage): """The xterm program is a terminal emulator for the X Window System. It provides DEC VT102 and Tektronix 4014 compatible terminals for programs that can't use the window system directly.""" homepage = "http://invisible-island.net/xterm/" url ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'community'} import uuid from ansible.module_utils.aws.core import AnsibleAWSModule from ansibl...
# encoding: utf-8 from __future__ import unicode_literals import re import json from .common import InfoExtractor from ..utils import remove_start class CBSNewsIE(InfoExtractor): IE_DESC = 'CBS News' _VALID_URL = r'http://(?:www\.)?cbsnews\.com/(?:[^/]+/)+(?P<id>[\da-z_-]+)' _TESTS = [ { ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import os from ansible.module_utils.basic import AnsibleModule class Zfs(object): def...
"""Tests for grudger strategies.""" import random import axelrod from .test_player import TestPlayer C, D = axelrod.Actions.C, axelrod.Actions.D class TestGrudger(TestPlayer): name = "Grudger" player = axelrod.Grudger expected_classifier = { 'memory_depth': float('inf'), # Long memory ...
from setuptools import find_packages, setup import os import re PACKAGE = 'APITaxi_models' DEPENDENCIES = [ 'Flask', 'Flask-Login', 'Flask-Principal', 'Flask-Security', 'Flask-SQLAlchemy', 'parse', 'GeoAlchemy2', 'Shapely', # sqlalchemy 1.4.0 breaks everything. Need to investigate...
from cinderclient.tests import utils from cinderclient.tests.v2 import fakes cs = fakes.FakeClient() class VolumesTest(utils.TestCase): def test_list_volumes_with_marker_limit(self): cs.volumes.list(marker=1234, limit=2) cs.assert_called('GET', '/volumes/detail?limit=2&marker=1234') def te...
import sys from functools import wraps if sys.version_info < (3, 5): raise RuntimeError( 'Python versions prior to 3.5 are not supported for PyFlink [' + str(sys.version_info) + '].') def keyword(func): """ A decorator that forces keyword arguments usage and store actual input keyword...
from PIL import Image import math import os #This script enlarges institions shield imamges so the corners show when they are displayed as circles. INSTITUTIONS_IMG_PATH = '../website/static/img/institutions/' def pythagonreanTheorem(x,y): return math.ceil((x**2 + y**2)**.5) def resize(img): newSize = int(...
from __future__ import print_function import h5py import numpy import os import argparse import sample from molecules.model import MoleculeVAE from molecules.utils import decode_smiles_from_indexes from molecules.utils import one_hot_array, one_hot_index SOURCE = 'Cc1ccnc(c1)NC(=O)Cc2cccc3c2cccc3' DEST = 'c1cc(cc(c1)...
import os import re import sys import datetime import logging from optparse import (make_option, OptionParser, OptionGroup, TitledHelpFormatter) from synnefo import settings from django.core.management.base import (BaseCommand, CommandError as DjangoCommand...
import os from future.utils import viewitems from miasm.core.utils import force_bytes, force_str from miasm.jitter.csts import PAGE_READ, PAGE_WRITE from miasm.core.utils import get_caller_name from miasm.core.utils import pck64, upck64 BASE_SB_PATH = "file_sb" WIN_CODEPAGE = "cp1252" def get_win_str_a(jitter, ad_s...
__author__ = "Felix Brezo, Yaiza Rubio <<EMAIL>>" __version__ = "2.0" from osrframework.utils.platforms import Platform class Kinja(Platform): """A <Platform> object for Kinja""" def __init__(self): self.platformName = "Kinja" self.tags = ["news"] ######################## # ...
import re import sys import traceback from fuzzywuzzy import fuzz import requests import TweetPoster from TweetPoster import rehost from raven.processors import SanitizePasswordsProcessor class SanitizeCredentialsProcessor(SanitizePasswordsProcessor): FIELDS = frozenset([ 'authorization', 'pass...
""" This file is part of ALTcointip. ALTcointip 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. ALTcointip is distr...
"""Add container host operating system info Revision ID: 04ba87af76bb Revises: 8c3d80e18eb5 Create Date: 2017-04-26 17:37:09.544598 """ # revision identifiers, used by Alembic. revision = '04ba87af76bb' down_revision = '8c3d80e18eb5' branch_labels = None depends_on = None from alembic import op import sqlalchemy as...
"""Tests for SavedModelLoader class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from tensorflow.python.client import session from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python...
"""Sublime Text plugin to do a Chromium code search. Select one or more words, and run this command. It will open Chrome to the results page for a search in Chromium code search for those words. """ import platform import sublime_plugin import urllib.parse import webbrowser def OpenInChrome(url): if platform.syst...
""" Helper for parsing Hadoop style configuration. """ import xml.parsers.expat class ConfParse(dict): """ A configuration parser for the "name"/"value" pairs in a file. Does no validating, so if you put garbage in, you get garbage out. """ def __init__(self, conf): """ Create a ConfParse with the c...
from __future__ import unicode_literals import webnotes from webnotes.utils import flt def execute(filters=None): if not filters: filters = {} elif filters.get("to_date"): filters["to_date"] = filters.get("to_date") + "24:00:00" columns = ["Time Log:Link/Time Log:120", "Employee::150", "From Datetime::140", ...
from __future__ import absolute_import, unicode_literals import importlib import os whereami = os.path.realpath(os.path.dirname(__file__)) __version__ = open('%s/VERSION' % whereami, 'r').read().strip() def get_resource(name): """Return an instance of the requested Resource class. Since all of the resource...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ distribute- and pip-enabled setup.py """ import logging import os import re # ----- overrides ----- # set these to anything but None to override the automatic defaults packages = None package_name = None package_data = None scripts = None # --------------------- #...
# -*- coding: utf-8 -*- """ *************************************************************************** r_resamp_filter.py ------------------ Date : February 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot fr **********************...
# -*- coding: utf-8 -*- """ tests.deprecations ~~~~~~~~~~~~~~~~~~ Tests deprecation support. Not used currently. :copyright: (c) 2015 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import pytest import flask class TestRequestDeprecation(object): def test_request_json(...
from __future__ import absolute_import import numpy as np import theano import theano.tensor as T def floatX(X): return np.asarray(X, dtype=theano.config.floatX) def sharedX(X, dtype=theano.config.floatX, name=None): return theano.shared(np.asarray(X, dtype=dtype), name=name) def shared_zeros(shape, dtype...
{ 'name': "multi_attachment_switzerland", 'summary': """ Upload multi-attachment""", 'author': "Michael Sandoz", 'website': "http://www.compassion.ch", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/ # modul...
import unittest try: from unittest import mock except ImportError: try: import mock except ImportError: mock = None from airflow import configuration from airflow.contrib.hooks.sagemaker_hook import SageMakerHook from airflow.contrib.operators.sagemaker_create_training_job_operator \ im...
import os import subprocess from process_handle import ProcessHandle, ProcessHandleParserBase class ProcessHandlersPs(object): @staticmethod def handle_mem(_, value): return value * 1024 @staticmethod def handle_elapsed(_, value): seconds = 0 unpack = value.split('-') if len(unpack) == 2: ...
import mrp_byproduct # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
import pyndn.utils as utils class Test1(utils.Enum): pass VAL1 = Test1.new_flag('VAL1', 1) VAL2 = Test1.new_flag('VAL2', 2) VAL3 = Test1.new_flag('VAL3', 3) print "%r %r %r" % (VAL1, VAL2, VAL3) assert VAL1 == 1 assert repr(VAL1) == '<flags VAL1 of type __main__.Test1>' assert VAL2 == 2 assert repr(VAL2) == '<flags...
""" Purpose Shows how to use the AWS SDK for Python (Boto3) with the Amazon Kinesis API to generate a data stream. This script generates data for the _Detecting Data Anomalies on a Stream_ example in the Amazon Kinesis Data Analytics SQL Developer Guide. """ # snippet-start:[kinesisanalytics.python.datagenerator.anom...
"Afrikaans config with language-specific information." from pynini import * from pynini.lib import byte from config import utils GRAPHEMES = union(byte.LOWER, "'", "'", "-", "à", "á", "ä", "è", "é", "ê", "ë", "í", "ï", "ò", "ó", "ô", "ö", "ú", "ü") INITIAL_PUNCTUATION = utils.DEFA...
# -*- coding: utf-8 -*- """ pygments.lexers.automation ~~~~~~~~~~~~~~~~~~~~~~~~~~ Lexers for automation scripting languages. :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.lexer import RegexLexer, include, bygroups, com...
from openerp.osv import fields, osv import openerp.addons.decimal_precision as dp from openerp.exceptions import Warning from openerp.tools import float_compare, float_round from openerp.tools.translate import _ import product class stock_landed_cost(osv.osv): _name = 'stock.landed.cost' _description = 'Stock...
"""Implements a simple mock gsutil Cloud API for unit testing. gsutil 4 was primarily unit-tested using boto/gsutil 3's mock storage_uri class, since it was possible that changing out the underlying mocks would have had subtly different behavior and increased the risk of breaking back-compat. Most unit and integratio...
import os from gi.repository import Gtk, Pango import gpodder from gpodder import util from gpodder.gtkui.interface.common import BuilderWidget _ = gpodder.gettext N_ = gpodder.ngettext class gPodderExportToLocalFolder(BuilderWidget): """ Export to Local Folder UI: file dialog + checkbox to save all to same fo...
"""Microversion handling.""" # NOTE(cdent): This code is taken from enamel: # https://github.com/jaypipes/enamel and was the original source of # the code now used in microversion_parse library. import collections import inspect import microversion_parse import webob # NOTE(cdent): avoid cyclical import conflict be...
import smartbot.backend from ..formatting import Colour, Style class Backend(smartbot.backend.Backend): def __init__(self): super().__init__() def run(self, name): self.on_connect.trigger() self.on_ready.trigger() while True: line = input("> ").strip() ...
#!/usr/bin/env python3 """ Script to preprocess OCR output for Tesseract Usage: python3 preprocess.py /path/to/input/dir \ /path/to/output/dir """ from glob import glob import os import shutil import sys import cv2 import numpy as np def preprocess(img): """Takes a given image and retu...
from telemetry.page import page as page_module from telemetry import story class ToughTextureUploadCasesPage(page_module.Page): def __init__(self, url, page_set): super( ToughTextureUploadCasesPage, self).__init__( url=url, page_set=page_set) def RunPageInteractions(self, action_...
import pygame, sys, math from Meatball import * class Player(Meatball): def __init__(self, maxSpeed =7 , pos=[-10,-10]): Meatball.__init__(self, "spoonerF.png", [0,-5], pos, None) self.maxSpeed = maxSpeed self.images = [pygame.transform.scale(pygame.image.load("rsc/ball/SpoonerF.png"),...
from datetime import datetime from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse, JsonResponse from django.shortcuts import redirect from django.utils import timezone from django.utils.decorators import met...
import interfaces import decorator import dbus.service import dbus.mainloop.glib import gobject import inspect import threading class DBusExporter(interfaces.ExporterInterface): """ Export method calls through DBus Interface. We take a method to be exported and create a simple wrapper function to call it. This is...
from numpy.testing import assert_, run_module_suite, assert_raises from scipy._lib._version import NumpyVersion def test_main_versions(): assert_(NumpyVersion('1.8.0') == '1.8.0') for ver in ['1.9.0', '2.0.0', '1.8.1']: assert_(NumpyVersion('1.8.0') < ver) for ver in ['1.7.0', '1.7.1', '0.9.9']: ...
"""Debug middleware""" from __future__ import print_function import sys import six import webob.dec from neutron.openstack.common.middleware import base class Debug(base.Middleware): """Helper class that returns debug information. Can be inserted into any WSGI application chain to get information about ...
import sys import xbmc from resources.lib.process import start_info_actions from resources.lib.Utils import * class Main: def __init__(self): xbmc.log("version %s started" % ADDON_VERSION) HOME.setProperty("extendedinfo_running", "true") self._parse_argv() for info in self.infos: ...
""" A test spanning all the capabilities of all the serializers. This class defines sample data and a dynamically generated test case that is capable of testing the capabilities of the serializers. This includes all valid data values, plus forward, backwards and self references. """ from __future__ import unicode_lite...
import collections import datetime import time from _sqlite3 import * paramstyle = "qmark" threadsafety = 1 apilevel = "2.0" Date = datetime.date Time = datetime.time Timestamp = datetime.datetime def DateFromTicks(ticks): return Date(*time.localtime(ticks)[:3]) def TimeFromTicks(ticks): return Time(*t...
# -*- coding: utf-8 -*- """ Student dashboard page. """ from bok_choy.page_object import PageObject from . import BASE_URL class DashboardPage(PageObject): """ Student dashboard, where the student can view courses she/he has registered for. """ def __init__(self, browser): """Initialize th...
''' Author: Hans Erik Heggem Email: <EMAIL> Project: Master's Thesis - Autonomous Inspection Of Wind Blades Repository: Master's Thesis - CV (Computer Vision ''' import cv2, math import numpy as np from Settings.Exceptions import DroneVisionError from src.DroneVision.DroneVision_src.imgProcessing.frameTools.frameT...
from __future__ import absolute_import import os import imp import sys import re import marshal import warnings try: unicode except NameError: unicode = str if sys.version_info[0] == 2: from StringIO import StringIO as BytesIO from StringIO import StringIO else: from io import BytesIO, StringIO...
""" Common utility functions useful throughout the contentstore """ import logging from datetime import datetime from django.conf import settings from django.core.urlresolvers import reverse from django.utils.translation import ugettext as _ from opaque_keys.edx.keys import CourseKey, UsageKey from pytz import UTC f...
# -*- coding: iso-8859-1 -*- """ SUNRISET.C - computes Sun rise/set times, start/end of twilight, and the length of the day at any date and latitude Written as DAYLEN.C, 1989-08-16 Modified to SUNRISET.C, 1992-12-01 (c) Paul Schlyter, 1989, 1992 Released to the public domain by Paul Schlyt...
# encoding: UTF-8 ''' 本文件中实现了风控引擎,用于提供一系列常用的风控功能: 1. 委托流控(单位时间内最大允许发出的委托数量) 2. 总成交限制(每日总成交数量限制) 3. 单笔委托的委托数量控制 ''' import json import os import platform from eventEngine import * from vtConstant import * from vtGateway import VtLogData ######################################################################## class ...
set_get_flavor_extra_specs = { 'status_code': [200], 'response_body': { 'type': 'object', 'properties': { 'extra_specs': { 'type': 'object', 'patternProperties': { '^[a-zA-Z0-9_\-\. :]+$': {'type': 'string'} } ...
""" urllib3 - Thread-safe connection pooling and re-using. """ from __future__ import absolute_import import warnings from .connectionpool import ( HTTPConnectionPool, HTTPSConnectionPool, connection_from_url ) from . import exceptions from .filepost import encode_multipart_formdata from .poolmanager imp...
import random # rules for standard sudoku puzzles MAX_VALUE = 9 BLOCK_SIZE = 3 LINE_SIZE = 9 def main(): print grid_to_string(generate_grid()) def grid_to_string(grid): row_strings = [''.join(map(str, row)) for row in grid] return "\n".join(row_strings) # list of rows, 9 values per r...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} try: from nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey import sslcer...
# -*- coding: utf-8 -*- # $Id: wuiadminsystemlog.py $ """ Test Manager WUI - Admin - System Log. """ __copyright__ = \ """ Copyright (C) 2012-2015 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribut...
# coding=utf-8 from django.core.urlresolvers import reverse from django.db import models from mptt.fields import TreeForeignKey from mptt.models import MPTTModel from core.adminlte import constants from core.adminlte.constants import UsableStatus, DICT_NULL_BLANK_TRUE from core.adminlte.models import BaseModel, User ...
""" urllib3 - Thread-safe connection pooling and re-using. """ __author__ = 'Andrey Petrov (<EMAIL>)' __license__ = 'MIT' __version__ = '1.3' from .connectionpool import ( HTTPConnectionPool, HTTPSConnectionPool, connection_from_url ) from . import exceptions from .filepost import encode_multipart_formd...
from nova.api.openstack import volume from nova.api.openstack.volume import snapshots from nova.api.openstack.volume import versions from nova.api.openstack.volume import volumes from nova.api.openstack import wsgi from nova import flags from nova.openstack.common import log as logging from nova import test from nova.t...
from openerp import models, api from openerp.osv import orm class IrUIView(models.Model): _inherit = 'ir.ui.view' @api.model def _add_readonly_attr(self, node): orm.transfer_modifiers_to_node({'readonly': True}, node) return True @api.model def postprocess(self, model, node, view...
"""This script is used by chrome_tests.gypi's js2webui action to maintain the argument lists and to generate inlinable tests. Usage: python tools/gypv8sh.py v8_shell mock.js test_api.js js2webui.js \ inputfile inputrelfile cxxoutfile jsoutfile """ import json import optparse import os import subprocess imp...
#-*- coding:utf-8 -*- import csv import os.path from . import basededatos def eliminar_tabla(): """ Eliminar tabla """ with basededatos.inegi() as bd: bd.cursor.execute("DROP TABLE IF EXISTS den_denue") print(" Eliminada la tabla den_denue si existía.") def crear_tabla(): """ Crear tabla; la...
from urlparse import urlparse import etcd import json import sys class BaseOperations(object): def __init__(self, url='http://localhost:4001'): self.get_client(url) def get_client(self, url, ca_cert=None, cert=None): parsed = urlparse(url) (h, p) = parsed.netloc.split(':') s...
""" Wrapper for dog_stats_api, ensuring tags are valid. See: http://help.datadoghq.com/customer/portal/questions/908720-api-guidelines """ from dogapi import dog_stats_api def _clean_tags(tags): """ Helper method that does the actual cleaning of tags for sending to statsd. 1. Handles any type of tag - a p...
""" JobManagerHandler is the implementation of the JobManager service in the DISET framework The following methods are available in the Service interface submitJob() rescheduleJob() deleteJob() killJob() """ __RCSID__ = "$Id$" from types import StringType, IntType, ListType from DIRAC.Core....
import mock from neutron import manager from neutron.plugins.ryu.db import models_v2 as ryu_models_v2 # noqa from neutron.tests.unit.ryu import fake_ryu from neutron.tests.unit import test_db_plugin as test_plugin class RyuPluginV2TestCase(test_plugin.NeutronDbPluginV2TestCase): _plugin_name = 'neutron.plugins...
import unittest class ByteRangeTests(unittest.TestCase): def testEmptyRange(self): try: server.byterange.parse_byteranges("") self.fail() except server.byterange.InvalidByteRangeException: # Expected result pass def testNoRangeGroups(self): ...
"""Self-test suite for Cryptodome.Cipher.Blowfish""" import unittest from Cryptodome.Util.py3compat import bchr from Cryptodome.Cipher import Blowfish # This is a list of (plaintext, ciphertext, key) tuples. test_data = [ # Test vectors from http://www.schneier.com/code/vectors.txt ('000000000000...
import mock from oslo_utils import timeutils from nova import context from nova import db from nova import exception from nova import objects from nova.objects import migration from nova.tests.unit import fake_instance from nova.tests.unit.objects import test_objects NOW = timeutils.utcnow().replace(microsecond=0) ...
from __future__ import division, print_function, unicode_literals import unittest from mwel.decompiler.xmlparser import XMLParser from . import ElementCheckMixin from .. import ErrorLoggerMixin class TestXMLParser(ElementCheckMixin, ErrorLoggerMixin, unittest.TestCase): def setUp(self): super(TestXMLPa...
""" Precompute coefficients of Temme's asymptotic expansion for gammainc. This takes about 8 hours to run on a 2.3 GHz Macbook Pro with 4GB ram. Sources: [1] NIST, "Digital Library of Mathematical Functions", http://dlmf.nist.gov/ """ from __future__ import division, print_function, absolute_import import os fr...
import sys from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import SJISDistributionAnalysis from .jpcntx import SJISContextAnalysis from .mbcssm import SJISSMModel from . import constants class SJISProber(MultiByteCharSetProber): ...
import report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
import collections import calendar import datetime import re import urllib from lxml.html import fromstring, tostring import requests import slugify from publish.lib.helpers import to_markdown, anchor_to_resource, get_dom, hd ROOT = "http://www.england.nhs.uk/statistics/statistical-work-areas/integrated-performance-...
from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import login_required from django.contrib.sites.shortcuts import get_current_site from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models...
# -*- coding: utf-8 -*- from os import path from gluon import current from gluon.html import * from s3 import s3_represent_facilities, s3_register_validation # ============================================================================= class index(): """ Custom Home Page """ def __call__(self): ...
__doc__ = """hashlib module - A common interface to many hash functions. new(name, string='') - returns a new hash object implementing the given hash function; initializing the hash using the given string data. Named constructor functions are also available, these are muc...