content string |
|---|
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.api
~~~~~~~~~~~~~~~~~~~~
Tests the public API and related stuff.
: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, Undefi... |
"""
USA-specific Form helpers
"""
from __future__ import absolute_import
import re
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select, CharField
from django.utils.encoding import smart_unicode
from django.utils.translatio... |
"""Tests for learn.utils.gc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.contrib.learn.python.learn.utils import gc
from tensorflow.python.framewo... |
from telemetry.page import shared_page_state
from telemetry import story
from page_sets import top_pages
def _Reload(action_runner):
# Numbers below are chosen arbitrarily. For the V8DetachedContextAgeInGC
# the number of reloads should be high enough so that V8 could do few
# incremental GCs.
NUMBER_OF_RELO... |
#-*- conding: utf-8 -*-
'''
Creole Reader
-------------
This plugins allows you to write your posts using the wikicreole syntax. Give to
these files the creole extension.
For the syntax, look at: http://www.wikicreole.org/
'''
from pelican import readers
from pelican import signals
from pelican import settings
from... |
import sys
from argparse import ArgumentParser
from threading import Timer
from time import time
from confluent_kafka import avro
from confluent_kafka.avro import AvroProducer
from random import randint, random
from sample_source_props import random_movie, random_series, random_user, random_tags, random_sentence
clas... |
from django.conf import settings
from django.core.cache import cache
from django.contrib.sites.models import Site
from ragendja.dbutils import db_create
from ragendja.pyutils import make_tls_property
_default_site_id = getattr(settings, 'SITE_ID', None)
SITE_ID = settings.__class__.SITE_ID = make_tls_property()
class... |
# -*- coding: utf-8 -*-
"""
Nearest Centroid Classification
"""
# Olivier Grisel <<EMAIL>>
#
# License: BSD 3 clause
import warnings
import numpy as np
from scipy import sparse as sp
from ..base import BaseEstimator, ClassifierMixin
from ..metrics.pairwise import pairwise_distances
from ..preprocessing impor... |
"""Test cases for traceback module"""
import unittest
from test_support import run_unittest
import traceback
class TracebackCases(unittest.TestCase):
# For now, a very minimal set of tests. I want to be sure that
# formatting of SyntaxErrors works based on changes for 2.1.
def get_exception_format(self... |
# -*- coding: utf-8 -*-
import datetime
import json
import functools
from Queue import Queue
import six
from twisted.application.service import Service
from twisted.internet import defer
from bouser.excs import SerializableBaseException, ExceptionWrapper
from twisted.web.http import Request
from bouser.web.cors import... |
from __future__ import print_function, division
from sympy.core import Basic
from sympy.core.compatibility import iterable, as_int, range
from sympy.utilities.iterables import flatten
from collections import defaultdict
class Prufer(Basic):
"""
The Prufer correspondence is an algorithm that describes the
... |
import collections
import sys
import mock
from six import moves
from cinderclient import exceptions
from cinderclient import utils
from cinderclient import base
from cinderclient.tests.unit import utils as test_utils
UUID = '8e8ec658-c7b0-4243-bdf8-6f7f2952c0d0'
class FakeResource(object):
NAME_ATTR = 'name'
... |
"""
Slapcomp Unit Tests
~~~~~~~~~~~~~~~~~~~~
Testing DAG functions.
:Version 0.1 Written by Daniel Hayes (<EMAIL>) June 2012
"""
#import os
import sys
sys.path.append("/Users/d/Dropbox/work/")
sys.path.append("/home/d/Dropbox/work/")
import unittest
from slapcomp.core.dag import Dag
from slapcomp.nod... |
from tempest.api.volume import api_microversion_fixture
from tempest.common import compute
from tempest.common import waiters
from tempest import config
from tempest.lib.common import api_version_utils
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
import tempest.test
C... |
import nest
import unittest
from math import exp
@nest.check_stack
class VogelsSprekelerConnectionTestCase(unittest.TestCase):
"""Check vogels_sprekeler_synapse model properties."""
def setUp(self):
"""Set up the test."""
nest.set_verbosity('M_WARNING')
nest.ResetKernel()
# ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import re
from ansible.errors import AnsibleConnectionFailure
from ansible.module_utils._text import to_text, to_bytes
from ansible.plugins.terminal import TerminalBase
class TerminalModule(TerminalBase):
termin... |
"""
A generic comment-moderation system which allows configuration of
moderation options on a per-model basis.
To use, do two things:
1. Create or import a subclass of ``CommentModerator`` defining the
options you want.
2. Import ``moderator`` from this module and register one or more
models, passing the model... |
"""
GCode M562
Example: M562 P0
Reset temperature fault
Author: Elias Bakken
License: CC BY-SA: http://creativecommons.org/licenses/by-sa/2.0/
"""
from GCodeCommand import GCodeCommand
import numpy as np
import logging
class M562(GCodeCommand):
def execute(self, g):
if g.has_letter("P"):
... |
from nova.api.openstack.compute.contrib import admin_actions as \
suspend_server_v2
from nova.api.openstack.compute.plugins.v3 import suspend_server as \
suspend_server_v21
from nova.tests.unit.api.openstack.compute import admin_only_action_common
from nova.tests.unit.api.openstack import fakes
class SuspendS... |
"""Utilities for CVS administration."""
import string
import os
import time
import md5
import fnmatch
if not hasattr(time, 'timezone'):
time.timezone = 0
class File:
"""Represent a file's status.
Instance variables:
file -- the filename (no slashes), None if uninitialized
lseen -- true if the ... |
import sys
import collections
import numpy as np
try:
import StringIO
except ImportError:
# If Python 3 import io as StringIO (so we can still use StringIO.StringIO)
if sys.version_info[0] >= 3:
import io as StringIO
else:
raise
class GroundReflectance:
"""Produces strings for the... |
from datetime import datetime as d
from distutils.dir_util import copy_tree
import os
from racconto.generator import Generator
from racconto.settings_manager import SettingsManager as SETTINGS
def generate_archive(pages, posts):
"""
Generate archive from posts. Assumes posts have been generated (i.e directori... |
import time
from datetime import datetime
from dateutil.relativedelta import relativedelta
from calendar import isleap
from openerp.tools.translate import _
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
DATETIME_FORMAT = "%Y-%m-%d"
class hr_contract(osv.osv):
"""
Employee ... |
from direct.showbase.InputStateGlobal import inputState
#from DirectGui import *
#from PythonUtil import *
#from IntervalGlobal import *
#from otp.avatar import Avatar
from direct.directnotify import DirectNotifyGlobal
#import GhostWalker
#import GravityWalker
#import NonPhysicsWalker
#import PhysicsWalker
#if __debug... |
from . import mass_editing_wizard |
import distutils.cmd
import distutils.log
from setuptools import setup, find_packages
class CoverageCommand(distutils.cmd.Command):
description = "Generate a test coverage report."
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sub... |
import os
import sys
from setuptools import setup
from distutils.core import Command
from os.path import join as pjoin
try:
import epydoc # NOQA
has_epydoc = True
except ImportError:
has_epydoc = False
import libcloud.utils # NOQA
from libcloud.utils.dist import get_packages, get_data_files # NOQA
l... |
import numpy as np
from numpy.testing import assert_equal, assert_, run_module_suite
import scipy
from qutip import sigmax, sigmay, sigmaz, Qobj, rand_ket, rand_dm, ket2dm
def test_Transformation1():
"Transform 2-level to eigenbasis and back"
H1 = scipy.rand() * sigmax() + scipy.rand() * sigmay() + \
... |
import scanpy as sc
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import scipy as sp
import tensorflow as tf
from tensorflow.contrib.opt import ScipyOptimizerInterface
nb_zero = lambda t, mu: (t/(mu+t))**t
zinb_zero = lambda t, mu, p: p + ((1.-p)*((t/(mu+t))**t))
sigmoid... |
import urllib
import json
import time
import mismatch
import csv
import numpy as np
import cPickle
import os
import pdb
class Protein():
"""
Class describing a protein in terms of its amino acid sequence
Arguments
name : string
name of the protein
"""
def __init__(self,name):
... |
import numpy
import logging
from lazyflow.utility import blockwise_view
logger = logging.getLogger("tests.test_blockwise_view")
def test_2d():
# Adapted from:
# http://stackoverflow.com/a/8070716/162094
n=4
m=5
a = numpy.arange(1,n*m+1).reshape(n,m)
logger.debug("original data:\n{}".format(a)... |
import gc
import pprint
import sys
import unittest
from test import support
class TestGetProfile(unittest.TestCase):
def setUp(self):
sys.setprofile(None)
def tearDown(self):
sys.setprofile(None)
def test_empty(self):
self.assertIsNone(sys.getprofile())
def test_setget(self)... |
from functools import partial
import errno
import sys
try:
import eventlet
except ImportError:
raise RuntimeError("You need eventlet installed to use this worker.")
# validate the eventlet version
if eventlet.version_info < (0, 9, 7):
raise RuntimeError("You need eventlet >= 0.9.7")
from eventlet import... |
"""Generates and massages protocol buffer outputs.
"""
from __future__ import print_function
import sys
import io
import nanopb_generator as nanopb
import os
import os.path
import re
import shlex
import textwrap
from google.protobuf.descriptor_pb2 import FieldDescriptorProto
from lib import pretty_printing as print... |
#!/usr/bin/env python
#
# Generate Format tables
import os
from optparse import OptionParser
OUTPUT_FILE = "FormatTables.cpp"
def generate_table(f, type_name, name, map):
f.write("extern const {0} {1}[] = {{".format(type_name, name))
for i in range(0, 256):
if i % 2 == 0:
f.write("\n ")... |
import logging
import sys
import os
# Import the metrics/common module for pretty print xml.
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
import models
import presubmit_util
# Model definitions for rappor.xml content
_SUMMARY_TYPE = models.TextNodeType('summary')
_PARAMETERS_TYPE = model... |
from oslo.config import cfg
from nova.i18n import _
from nova.openstack.common import log as logging
from nova.virt.hyperv import hostutils
from nova.virt.hyperv import livemigrationutils
from nova.virt.hyperv import networkutils
from nova.virt.hyperv import networkutilsv2
from nova.virt.hyperv import pathutils
from n... |
import json
from django.conf import settings
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import logout as auth_logout, login
from social.backends.oauth import BaseOAuth1, BaseOAuth... |
# This module implements the RFCs 3490 (IDNA) and 3491 (Nameprep)
import stringprep, re, codecs
from unicodedata import ucd_3_2_0 as unicodedata
# IDNA section 3.1
dots = re.compile("[\u002E\u3002\uFF0E\uFF61]")
# IDNA section 5
ace_prefix = b"xn--"
sace_prefix = "xn--"
# This assumes query strings, so ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: scaleway_security_group_facts
short_description: Gather fa... |
from sqlite3 import Cursor
from typing import TYPE_CHECKING, Callable, Optional
if TYPE_CHECKING:
from sydent.sydent import Sydent
class HashingMetadataStore:
def __init__(self, sydent: "Sydent") -> None:
self.sydent = sydent
def get_lookup_pepper(self) -> Optional[str]:
"""Return the va... |
from Products.ZenRelations.RelSchema import ToManyCont, ToOne
from ZenPacks.zenoss.CloudStack import BaseComponent
class Cluster(BaseComponent):
meta_type = portal_type = "CloudStackCluster"
cluster_type = None
hypervisor_type = None
managed_state = None
_properties = BaseComponent._properties ... |
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, getdate, nowdate, fmt_money
from frappe import msgprint, _
from frappe.model.document import Document
form_grid_templates = {
"journal_entries": "templates/form_grid/bank_reconciliation_grid.html"
}
class BankReconciliation(Document)... |
import os
from os.path import join
###
def force_warning_level_3(file):
with open(file, "r") as in_file:
buf = in_file.readlines()
push = '#pragma warning(push, 3)\n'
pop = '#pragma warning(pop)\n'
last_line_has_mongo = False
with open(file, "w") as out_file:
for line in buf: ... |
"""
This module provides support for Twisted to interact with the glib mainloop.
This is like gtk2, but slightly faster and does not require a working
$DISPLAY. However, you cannot run GUIs under this reactor: for that you must
use the gtk2reactor instead.
In order to use this support, simply do the following::
f... |
"""The fallback skill implements a special type of skill handling
utterances not handled by the intent system.
"""
import operator
from mycroft.metrics import report_timing, Stopwatch
from mycroft.util.log import LOG
from .mycroft_skill import MycroftSkill, get_handler_name
class FallbackSkill(MycroftSkill):
""... |
import msgpack
import decimal
import datetime
from rest_framework.renderers import BaseRenderer
class MessagePackEncoder(object):
def encode(self, obj):
if isinstance(obj, datetime.datetime):
return {'__class__': 'datetime', 'as_str': obj.isoformat()}
elif isinstance(obj, datetime.da... |
"""
MySQL database backend for Django.
Requires MySQLdb: http://sourceforge.net/projects/mysql-python
"""
import re
import sys
try:
import MySQLdb as Database
except ImportError, e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
... |
"""
Runs small tests.
"""
import imp
import os
import sys
import unittest
import TestGyp
test = TestGyp.TestGyp()
# Add pylib to the import path (so tests can import their dependencies).
# This is consistant with the path.append done in the top file "gyp".
sys.path.insert(0, os.path.join(test._cwd, 'pylib'))
# Ad... |
"""
Key manager implementation that raises NotImplementedError
"""
from nova.keymgr import key_mgr
class NotImplementedKeyManager(key_mgr.KeyManager):
"""Key Manager Interface that raises NotImplementedError for all operations
"""
def create_key(self, ctxt, algorithm='AES', length=256, expiration=None,
... |
"""Does scraping for versions of Chrome from 0.1.101.0 up."""
from drivers import windowing
import chromebase
# Default version
version = "0.1.101.0"
def GetChromeRenderPane(wnd):
return windowing.FindChildWindow(wnd, "Chrome_TabContents")
def Scrape(urls, outdir, size, pos, timeout=20, **kwargs):
"""Invoke ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""tidydate
This file declares and implements the TidyDate class for TidyAll.
TidyDate converts and formats valid date columns into ISO 8601 (yyyy-mm-dd).
"""
import sys
from dateutil import parser as date_parser
import numpy as np
import pandas as pd
from .settings im... |
import argparse
import configparser
from time import strftime, localtime
from os.path import dirname, exists, join
from os import makedirs
from sys import path
# FIXME: hack to allow sibling imports
path.append(join(dirname(__file__), '..'))
from helpers.orm import Log # noqa
from helpers.sql import get_session # n... |
import sys
sys.path.append("../src/")
from backend import data_set, dependency_tree
from feature import feature_set
from learn import weight_learner
from evaluate import evaluator
import glm_parser
def write_file(msg):
f = open(output_file, "a+")
f.write(msg)
f.close()
return
if __name__ == "__main_... |
"""
Utility functions for handling images.
Requires Pillow as you might imagine.
"""
import struct
import zlib
from django.core.files import File
class ImageFile(File):
"""
A mixin for use alongside django.core.files.base.File, which provides
additional features for dealing with images.
"""
def ... |
"""
This module encapsulates functions related to Badlands SP finite volume discretisation.
"""
import time
import numpy
from pyBadlands.libUtils import FVframe
import warnings
import triangle
import mpi4py.MPI as mpi
class FVmethod:
"""
This class builds paramters required for the Finite Volume mesh algorit... |
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import os
from contextlib import closing
from calibre.customize import FileTypePlugin
def is_c... |
#!/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 100... |
from aloe import world
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
# Do not remove this import. Without it the hook will not be ran
from app.ho... |
"""
Benchmarks of Non-Negative Matrix Factorization
"""
from __future__ import print_function
from collections import defaultdict
import gc
from time import time
import numpy as np
from scipy.linalg import norm
from sklearn.decomposition.nmf import NMF, _initialize_nmf
from sklearn.datasets.samples_generator import... |
"""
Exercises tests on the base_store_provider file
"""
from django.test import TestCase
from instructor.enrollment_report import AbstractEnrollmentReportProvider
from instructor.paidcourse_enrollment_report import PaidCourseEnrollmentReportProvider
class BadImplementationAbstractEnrollmentReportProvider(AbstractEnr... |
from webkitpy.layout_tests.models import test_expectations
from webkitpy.common.net import resultsjsonparser
TestExpectations = test_expectations.TestExpectations
TestExpectationParser = test_expectations.TestExpectationParser
class BuildBotPrinter(object):
# This output is parsed by buildbots and must only be... |
import contextlib
import logging
import re
import shutil
import ssl
import urllib
logger = logging.getLogger(__name__)
re_filename = re.compile(r"filename=(.+)")
class DownloadApiMixin(object):
def download(self, token, **kwargs):
context = ssl.create_default_context()
if not self.session.verify... |
from fpdf import *
import re
class PDF(FPDF):
def __init__(self, orientation='P',unit='mm',format='A4'):
#Call parent constructor
FPDF.__init__(self,orientation,unit,format)
#Initialization
self.b=0
self.i=0
self.u=0
self.href=''
self.page_links={}
def write_html(self, html):
#HTML pars... |
"""rename user table
Revision ID: 2e82aab8ef20
Revises: 1968acfc09e3
Create Date: 2016-04-02 19:28:15.211915
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = '2e82aab8ef20'
down_revision = '1968acfc09e3'
branch_labels = None
depends_on = None
def upgrade():
op.rename_table('user',... |
import time
from math import floor
from django.test import RequestFactory
from django.utils.http import parse_http_date
from bedrock.mozorg.tests import TestCase
from bedrock.mozorg.tests import views
class ViewDecoratorTests(TestCase):
def setUp(self):
self.rf = RequestFactory()
def _test_cache_he... |
import os
import tempfile
from oslo_config import cfg
from oslotest import base
from neutron.tests import base as n_base
def load_config_file(string):
cfile = tempfile.NamedTemporaryFile(delete=False)
cfile.write(string.encode('utf-8'))
cfile.close()
n_base.BaseTestCase.config_parse(
cfg.CON... |
"""Supports the parsing of command-line options for check-webkit-style."""
import logging
from optparse import OptionParser
import os.path
import sys
from filter import validate_filter_rules
# This module should not import anything from checker.py.
_log = logging.getLogger(__name__)
_USAGE = """usage: %prog [--help... |
from twisted.trial import unittest
from twisted.test.proto_helpers import StringTransport
from twisted.conch.insults.insults import ServerProtocol, ClientProtocol
from twisted.conch.insults.insults import CS_UK, CS_US, CS_DRAWING, CS_ALTERNATE, CS_ALTERNATE_SPECIAL
from twisted.conch.insults.insults import G0, G1
from... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to manage symbolic link alternatives.
(c) 2014, Gabe Mulley <<EMAIL>>
This file is part of Ansible
Ansible 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 Founda... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: aci_epg
short_description: Manage End Point Groups (EPG) obj... |
from __future__ import absolute_import, division, print_function, \
with_statement
import sys
import os
import logging
import signal
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
from shadowsocks import shell, daemon, eventloop, tcprelay, udprelay, asyncdns
def main():
shell.check_pytho... |
#!/usr/bin/env python
# Creates a man page from a C file.
# Comments beginning with `/**` are treated as Groff man, except that
# 'this' is converted to \fIthis\fR, and ''this'' to \fBthis\fR.
# Non-blank lines immediately following a man page comment are treated
# as function signatures or examples and parsed into ... |
import os
import sys
import sphinx_rtd_theme
from typepy import __author__, __copyright__, __name__, __version__
sys.path.insert(0, os.path.abspath('../typepy'))
# -- General configuration ------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# ext... |
from .charsetgroupprober import CharSetGroupProber
from .utf8prober import UTF8Prober
from .sjisprober import SJISProber
from .eucjpprober import EUCJPProber
from .gb2312prober import GB2312Prober
from .euckrprober import EUCKRProber
from .cp949prober import CP949Prober
from .big5prober import Big5Prober
from .euctwpro... |
"""Snapcraft integrations layer.
Defines 'enable-ci' command infrastructure to support multiple integrations
systems in an isolated form.
"""
import importlib
SUPPORTED_CI_SYSTEMS = (
'travis',
)
def enable_ci(ci_system, refresh_only):
if not ci_system:
# XXX cprov 20161116: we could possibly auto-... |
"""Sample TensorFlow benchmark."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import tensorflow as tf
# Define a class that extends from tf.test.Benchmark.
class SampleBenchmark(tf.test.Benchmark):
# Note: benchmark method name must st... |
"""
List endpoints for an object, account or container.
This middleware makes it possible to integrate swift with software
that relies on data locality information to avoid network overhead,
such as Hadoop.
Using the original API, answers requests of the form::
/endpoints/{account}/{container}/{object}
/endp... |
import os
import glob
import time
import socket
import subprocess
import xmlrpclib
import logging
try:
import release
from osv import osv
from tools.translate import _
except ImportError:
import openerp
from openerp import release
from openerp.osv import osv
from openerp.tools.translate imp... |
# -*- coding: utf-8 -*-
DEPARTMENT_ASCII_CHOICES = (
('01', '01 - Ain'),
('02', '02 - Aisne'),
('03', '03 - Allier'),
('04', '04 - Alpes-de-Haute-Provence'),
('05', '05 - Hautes-Alpes'),
('06', '06 - Alpes-Maritimes'),
('07', '07 - Ardeche'),
('08', '08 - Ardennes'),
('09', '09 - Ar... |
import logging
from haas import config
from functools import wraps
def no_dry_run(f):
"""A decorator which "disables" a function during a dry run.
A can specify a `dry_run` option in the `devel` section of `haas.cfg`.
If the option is present (regardless of its value), any function or
method decorate... |
"""upload_gtest.py v0.1.0 -- uploads a Google Test patch for review.
This simple wrapper passes all command line flags and
--cc=<EMAIL> to upload.py.
USAGE: upload_gtest.py [options for upload.py]
"""
__author__ = '<EMAIL> (Zhanyong Wan)'
import os
import sys
CC_FLAG = '--cc='
GTEST_GROUP = '<EMAIL>'
def main():... |
from django.contrib.gis.gdal import OGRGeomType
from django.db.backends.postgresql.introspection import DatabaseIntrospection
class GeoIntrospectionError(Exception):
pass
class PostGISIntrospection(DatabaseIntrospection):
# Reverse dictionary for PostGIS geometry types not populated until
# introspectio... |
"""
Utilities for writing third_party_auth tests.
Used by Django and non-Django tests; must not have Django deps.
"""
from contextlib import contextmanager
import unittest
import mock
from third_party_auth import provider
AUTH_FEATURES_KEY = 'ENABLE_THIRD_PARTY_AUTH'
class FakeDjangoSettings(object):
"""A fa... |
""" test_management:
code related to the gathering / analysis / management of
the test cases
ie - collecting the list of tests in each suite, then
gathering additional, relevant information for the test-runner's dtr
mode. (traditional diff-based testing)
"""
# imports
import os
import re
import s... |
# -*- coding: utf-8 -*-
"""Provides ``RequeuePoller``, a utility that polls the db and add tasks
to the queue.
"""
__all__ = [
'RequeuePoller',
]
import logging
logger = logging.getLogger(__name__)
import time
import transaction
from datetime import datetime
from redis.exceptions import RedisError
from sqlal... |
import os,re,posixpath
## Get the Module Versions
#
# Walk the project tree looking for VERSION.scons files. Read in these files
# and parse the versions accordingly, generating versions which can help
# facilitate building later. The dictionary is then passed to the environment
# for easy access
def get_project_vers... |
from __future__ import with_statement
from globals import *
from dbtables import *
from PyQt4 import QtGui, QtCore
import operator
from util import extime
# Roles used in the items
sorting=QtCore.Qt.UserRole
display=QtCore.Qt.DisplayRole
post_id=QtCore.Qt.UserRole+1
class PostModel(QtGui.QStandardItemModel):
def __... |
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
def code_to_chars(code):
return CSI + str(code) + 'm'
class AnsiCodes(object):
def __init__(self, codes):
for name in dir(codes):
... |
"""Power state is the state we get by calling virt driver on a particular
domain. The hypervisor is always considered the authority on the status
of a particular VM, and the power_state in the DB should be viewed as a
snapshot of the VMs's state in the (recent) past. It can be periodically
updated, and should also be u... |
__docformat__ = 'restructuredtext'
# GAE imports
from google.appengine.api import urlfetch
from google.appengine.api import memcache
# IMPORTNAT:
# geoutil contains the an URL with a secret key used to parse the geo ip from a paid service
# so, geoutil it's not commited
# If geoutil is not found, it will use free Ge... |
#!/usr/bin/env python
from .common import match1, maybe_print, download_urls, get_filename, parse_host, set_proxy, unset_proxy
from .util import log
from . import json_output
import os
class Extractor():
def __init__(self, *args):
self.url = None
self.title = None
self.vid = None
s... |
# -*- coding: utf-8 -*-
""" Commerce app tests package. """
import datetime
import json
from django.conf import settings
from django.test import TestCase
from django.test.utils import override_settings
from freezegun import freeze_time
import httpretty
import jwt
import mock
from edx_rest_api_client import auth
from ... |
from modeller import *
import os
import mdt
import mdt.features
env = Environ()
mlib = mdt.Library(env)
mlib.bond_classes.read('${LIB}/bndgrp.lib')
xray = mdt.features.XRayResolution(mlib, bins=[(0.51, 2.001, 'High res(2.0A)')])
bond_type = mdt.features.BondType(mlib)
bond_length = mdt.features.BondLength(mlib,
... |
from __future__ import division, print_function, unicode_literals
import logging
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
_logger = logging.getLogger(__name__)
try:
from pybrasil.base import mascara
except (ImportError, IOError) as err:
_logger.debug(err)
class ... |
# -*- coding: utf-8 -*-
"""
Mimetypes-related utilities
# TODO: reexport stdlib mimetypes?
"""
import collections
import io
import logging
import re
import zipfile
__all__ = ['guess_mimetype']
_logger = logging.getLogger(__name__)
# We define our own guess_mimetype implementation and if magic is available we
# use ... |
import binascii
import base64
import md5
import random
def H(s):
return md5.new(s).digest()
def KD(k, s):
return H(k + ":" + s)
def HEX(n):
return binascii.hexlify(n)
def UNHEX(h):
return binascii.unhexlify(h)
def response(challenge, user, password, realm, digest_uri):
#parse challenge
... |
from os import path
import simplejson
def locate():
base = path.expandvars("%APPDATA%")
if base is not None:
return path.join(base, "sced.config.json")
else:
return None
def load():
sets = Settings()
try:
filename = locate()
f = open(filename, "r")
except:
... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ImportError:... |
#!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collector import Collector
from ipvs import IPV... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.