content stringlengths 4 20k |
|---|
#!/usr/bin/env python
"""NumPy: array processing for numbers, strings, records, and objects.
NumPy is a general-purpose array-processing package designed to
efficiently manipulate large multi-dimensional arrays of arbitrary
records without sacrificing too much speed for small multi-dimensional
arrays. NumPy is built ... |
# -*- coding: utf-8 -*-
"""Example for gam.AdditiveModel and PolynomialSmoother
This example was written as a test case.
The data generating process is chosen so the parameters are well identified
and estimated.
Created on Fri Nov 04 13:45:43 2011
Author: Josef Perktold
"""
from __future__ import print_function
fro... |
import sys
import string
from pyglet.gl import *
from pyglet.window import key, mouse
from wydget import event, anim, util, element
from wydget.widgets.frame import Frame
from wydget.widgets.label import Label
from wydget import clipboard
# for detecting words later
letters = set(string.letters)
class Cursor(elemen... |
import mantid.simpleapi as api
from mantid.api import AnalysisDataService
from mantid.api import MatrixWorkspaceProperty, PropertyMode, PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty
from mantid.api import FileProperty, FileAction, ITableWorkspace
from mantid.kernel import Direction
import mantid.kernel
imp... |
from __future__ import division, print_function, absolute_import
import os
from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
from numpy import get_include
from scipy._build_utils import numpy_nodepr_api
def configuration(parent_package='', top_path=None):
config = Confi... |
# -*- coding: utf-8 -*-
"""
jinja2.visitor
~~~~~~~~~~~~~~
This module implements a visitor for the nodes.
:copyright: (c) 2017 by the Jinja Team.
:license: BSD.
"""
from jinja2.nodes import Node
class NodeVisitor(object):
"""Walks the abstract syntax tree and call visitor functions for every... |
""" Standard "encodings" Package
Standard Python encoding modules are stored in this package
directory.
Codec modules must have names corresponding to normalized encoding
names as defined in the normalize_encoding() function below, e.g.
'utf-8' must be implemented by the module 'utf_8.py'.
Ea... |
from django.contrib.gis import forms
# Getting the SpatialBackend container and the geographic quoting method.
from django.contrib.gis.db.backend import SpatialBackend, gqn
# GeometryProxy, GEOS, and Distance imports.
from django.contrib.gis.db.models.proxy import GeometryProxy
from django.contrib.gis.measure import Di... |
"""
Czech-specific form helpers
"""
from __future__ import absolute_import, unicode_literals
import re
from django.contrib.localflavor.cz.cz_regions import REGION_CHOICES
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Select, RegexField, Field... |
#!/usr/bin/env python
"""
Logging functions
@contact: Debian FTP Master <<EMAIL>>
@copyright: 2001, 2002, 2006 James Troup <<EMAIL>>
@license: GNU General Public License version 2 or later
"""
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public Licen... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import copy
from ansible import constants as C
from ansible.module_utils._text import to_text
from ansible.module_utils.connection import Connection
from ansible.plugins.action.normal import ActionModule as _ActionModul... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='CalendarProvider',
fields=[
('id', models.AutoF... |
import os, sys, time, multiprocessing, re
from .processes import ForkedProcess
from .remoteproxy import ClosedError
from ..python2_3 import basestring, xrange
class CanceledError(Exception):
"""Raised when the progress dialog is canceled during a processing operation."""
pass
class Parallelize(object):
"... |
from pyflink.common import typeinfo
from pyflink.common.serialization import JsonRowDeserializationSchema, \
JsonRowSerializationSchema, SimpleStringEncoder
from pyflink.common.typeinfo import Types
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors import FlinkKafkaConsume... |
from django.test import TestCase
from courses import models
from courses.tests.factories import (
SemesterFactory, SemesterDepartmentFactory,
OfferedForFactory, CourseFactory, SectionFactory, DepartmentFactory,
PeriodFactory, SectionPeriodFactory
)
class SemesterBasedQuerySetTest(TestCase):
def setUp... |
from __future__ import absolute_import
from django.db import models
from website.util import api_v2_url
from django.core.files.storage import Storage
from django.core.files.base import ContentFile
from django.utils.deconstruct import deconstructible
# Could easily be genericized - would just need a generic url to se... |
import unittest, collections
from datetime import date as date
import rating.rating_math as rm
Player = collections.namedtuple('Player', ['user_id'])
Game = collections.namedtuple('Game', ['white', 'black', 'result', 'date_played'])
class RatingsMathTestCase(unittest.TestCase):
def setUp(self):
pass
... |
"""JsLex: a lexer for Javascript"""
# Originally from https://bitbucket.org/ned/jslex
import re
class Tok:
"""
A specification for a token class.
"""
num = 0
def __init__(self, name, regex, next=None):
self.id = Tok.num
Tok.num += 1
self.name = name
self.regex = re... |
"""Define the menu contents, hotkeys, and event bindings.
There is additional configuration information in the EditorWindow class (and
subclasses): the menus are created there based on the menu_specs (class)
variable, and menus not created are silently skipped in the code here. This
makes it possible, for example, to... |
"""
================
Confusion matrix
================
Example of confusion matrix usage to evaluate the quality
of the output of a classifier on the iris data set. The
diagonal elements represent the number of points for which
the predicted label is equal to the true label, while
off-diagonal elements are those that ... |
#!/usr/bin/env python
from splparser.parsetree import *
from splparser.rules.common.asrules import *
from splparser.rules.common.fieldrules import *
from splparser.lexers.deltalexer import tokens
start = 'cmdexpr'
def p_cmdexpr_delta(p):
"""cmdexpr : deltacmd"""
p[0] = p[1]
def p_delta_arg(p):
"""delt... |
import pytest
from pootle_app.project_tree import match_template_filename
from pootle_format.models import Format
from pootle_project.models import Project
@pytest.mark.django_db
def test_match_template_filename():
project = Project.objects.get(code="project0")
po = Format.objects.get(name="po")
xliff = ... |
from anagrafica.models import Persona
from autenticazione.funzioni import pagina_pubblica
__author__ = 'alfioemanuele'
"""
Qui sono contenute le varie viste relative agli errori (namespace /errore/*)
"""
@pagina_pubblica
def non_trovato(request, me, exception=None):
"""
Questa vista viene chiamata quando una... |
"""Tests for custom user ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path
import tensorflow as tf
class AckermannTest(tf.test.TestCase):
def testBasic(self):
library_filename = os.path.join(tf.resource_loader.get_data_files_pa... |
# Standard library imports
import unittest
# System library imports
from IPython.external.qt import QtCore, QtGui
# Local imports
from IPython.qt.console.console_widget import ConsoleWidget
import IPython.testing.decorators as dec
setup = dec.skip_file_no_x11(__name__)
class TestConsoleWidget(unittest.TestCase):
... |
"""
Serializers for Bulk Enrollment.
"""
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from rest_framework import serializers
from six.moves import zip
from openedx.core.djangoapps.course_groups.cohorts import is_cohort_exists
class StringListField(serializers.ListField):
d... |
from __future__ import unicode_literals
import docker
from .. import mock
from .. import unittest
from compose.container import Container
from compose.container import get_container_name
class ContainerTest(unittest.TestCase):
def setUp(self):
self.container_dict = {
"Id": "abc",
... |
import copy
import json
import pytest
from ansible.modules.packaging.language import gem
from units.modules.utils import AnsibleExitJson, AnsibleFailJson, ModuleTestCase, set_module_args
def get_command(run_command):
"""Generate the command line string from the patched run_command"""
args = run_command.call... |
from gnuradio import gr, gr_unittest
class test_mute (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def help_ii (self, src_data, exp_data, op):
for s in zip (range (len (src_data)), src_data):
src = gr.vector_so... |
"""Tests for tensorflow.ops.registry."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import registry
from tensorflow.python.platform import googletest
class RegistryTest(googletest.TestCase):
class Foo(object):
... |
import os
from os.path import join
import numpy
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('svm', parent_package, top_path)
config.add_subpackage('tests')
# newrand wrappers
config.add_extension('_newrand',
... |
from django.conf import settings
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
from django.utils.functional import cached_property
class PostGISCreation(DatabaseCreation):
geom_index_type = 'GIST'
geom_index_ops = 'GIST_GEOMETRY_OPS'
geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND... |
import unittest
import json
import requests
import requests_mock
import tenacity
from airflow import configuration
from airflow.exceptions import AirflowException
from airflow.hooks.http_hook import HttpHook
from airflow.models.connection import Connection
try:
from unittest import mock
except ImportError:
... |
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.aggregates import constants
INDEX_URL = constants.AGGREGATES_INDEX_URL
class UpdateAggregateFor... |
class MockFileLock(object):
def __init__(self, lock_file_path, max_wait_time_sec=20):
pass
def acquire_lock(self):
return True
def release_lock(self):
return True |
# -*- coding: utf-8 -*-
import heapq
from LOTlib.Miscellaneous import Infinity
class QueueItem(object):
"""
A wrapper to hold items and scores in the queue--just wraps "cmp" on a priority value
"""
def __init__(self, item, p):
self.item = item
self.priority = p
def __cmp__... |
"""
Digress errors.
"""
class DigressError(Exception):
"""
Digress error base class.
"""
class NoSuchTestError(DigressError):
"""
Raised when no such test exists.
"""
class DisabledTestError(DigressError):
"""
Test is disabled.
"""
class SkippedTestError(DigressError):
"""
... |
"""Use the HTMLParser library to parse HTML files that aren't too bad."""
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
__all__ = [
'HTMLParserTreeBuilder',
]
from HTMLParser import HTMLParser
try:
from HTMLParser import HTMLParseError
except Impor... |
###############################################################################
# Python Script to Trim Based on Moving Average
###############################################################################
# Written by Mario Muscarella
# Last Update 2 May 2013
# Directions:
# use the following command: > python Tri... |
"""
Tests for management command backfill_sso_verifications_for_old_account_links
"""
from mock import patch
from django.core.management import call_command
from django.core.management.base import CommandError
from lms.djangoapps.program_enrollments.management.commands.tests.utils import UserSocialAuthFactory
from l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
examples/ScriptingService/adminWorkflow.py
-----------------------------------------------------------------------------
Copyright (C) 2006-2014 University of Dundee. All rights reserved.
This program is free software; you can redistribute it and/or modify
it ... |
import argparse
import datetime
from distutils.core import Command
from distutils.errors import DistutilsOptionError
class BuildManPage(Command):
"""
Add a ``build_manpage`` command to your setup.py.
To use this Command class add a command to call this class::
# For setuptools
setup(
... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import unittest
import datetime
from django.utils import six
from django.utils.encoding import (force_bytes, force_text, filepath_to_uri,
python_2_unicode_compatible)
class TestEncodingUtils(unittest.TestCase):
def test_force_text_excepti... |
"""
Tests for L{twisted.conch.ssh.agent}.
"""
import struct
from twisted.trial import unittest
from twisted.test import iosim
try:
import cryptography
except ImportError:
cryptography = None
try:
import pyasn1
except ImportError:
pyasn1 = None
if cryptography and pyasn1:
from twisted.conch.ssh ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 02 08:41:08 2014
@author: Acer
"""
import sys
import pycd3
class NodeFactory(pycd3.INodeFactory):
def __init__(self, node):
pycd3.INodeFactory.__init__(self)
self.node = node
print "NodeFactory.__init__"
def getNodeName(self):
... |
import imaplib
import time
import re
class Google(Page):
_GOOGLE_PAGE = "div.google-header-bar"
_APPROVE = "input#approve_button"
_EMAIL = "input#Email"
_PASSWORD = "input#Passwd"
_SUBMIT = "input#signIn.g-button"
def activate_mc_user_account(self, email, password, url):
... |
# -*- coding: utf-8 -*-
import warnings
import os
from collections import namedtuple
from . import djbec
__all__ = ['crypto_sign', 'crypto_sign_open', 'crypto_sign_keypair', 'Keypair',
'PUBLICKEYBYTES', 'SECRETKEYBYTES', 'SIGNATUREBYTES']
PUBLICKEYBYTES=32
SECRETKEYBYTES=64
SIGNATUREBYTES=64
Keypair = n... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.compat.tests.mock import patch
from ansible.modules.network.iosxr import iosxr_user
from units.modules.utils import set_module_args
from .iosxr_module import TestIosxrModule, load_fixture
class TestIosxrUserModule(Te... |
"""Initial database
Revision ID: 46a3d679666e
Revises: None
Create Date: 2013-10-08 01:34:51.501561
"""
# revision identifiers, used by Alembic.
revision = '46a3d679666e'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ... |
# -*- coding: utf-8 -*-
from cms.exceptions import DontUsePageAttributeWarning
from cms.models.placeholdermodel import Placeholder
from cms.plugin_rendering import PluginContext, PluginRenderer
from cms.utils.helpers import reversion_register
from cms.utils.placeholder import get_page_from_placeholder_if_exists
from da... |
"""For seeding individual ops based on a graph-level seed.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import context
from tensorflow.python.framework import ops
DEFAULT_GRAPH_SEED = 87654321
_MAXINT32 = 2**31 - 1
de... |
# -*- coding: utf-8 -*-
import re
from ..internal.SimpleHoster import SimpleHoster
class SendspaceCom(SimpleHoster):
__name__ = "SendspaceCom"
__type__ = "hoster"
__version__ = "0.23"
__status__ = "testing"
__pattern__ = r'https?://(?:www\.)?sendspace\.com/file/\w+'
__config__ = [("activate... |
import sleekxmpp
import magic # find out encoding of text files
import logging
import codecs
import sys
import time
class SubtitleManager(sleekxmpp.ClientXMPP):
"""
A XMPP message sender
"""
subtitles = []
def __init__(self, jid, password, subtitle_filename):
# make a jabber clien... |
import WebIDL
def WebIDLTest(parser, harness):
parser.parse("""
callback interface TestCallbackInterface {
attribute boolean bool;
};
""")
results = parser.finish()
iface = results[0]
harness.ok(iface.isCallback(), "Interface should be a callback")
parser = parser.... |
from msrest.serialization import Model
class ScheduleEntry(Model):
"""Patch schedule entry for a Premium Redis Cache.
:param day_of_week: Day of the week when a cache can be patched. Possible
values include: 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday', 'Everyday', '... |
from __future__ import print_function
import atexit
import math
import os
import random
import re
import shlex
import subprocess
import sys
import tempfile
import time
from math import acos, atan2, cos, pi, sqrt
from subprocess import PIPE, Popen, call, check_call
import pexpect
from . rotmat import Matrix3, Vector3... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from collections import Iterable
from django.conf import settings
from django.contrib.auth.decorators import REDIRECT_FIELD_NAME
from django.core.exceptions import ImproperlyConfigured
from django.core.exceptions import PermissionDenied
from django.http... |
# -*- coding: utf-8 -*-
"""
.. module:: djbraintree.event_handlers
:synopsis: dj-braintree - webhook event handlers for the various models
.. moduleauthor:: Bill Huneke (@wahuneke)
Implement webhook event handlers for all the models that need to respond to webhook events.
"""
from django.utils import timezone
fr... |
"""Unit tests for the Deposit models."""
from flask_registry import RegistryError
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
class DepositionTest(InvenioTestCase):
def setUp(self):
from invenio.modules.deposit.models import DepositionType
from invenio.modules.d... |
"""add reply_to_message_id
Revision ID: 1d7a72222b7c
Revises:2d8a350b4885
Create Date: 2015-02-18 21:40:50.082303
"""
# revision identifiers, used by Alembic.
revision = '1d7a72222b7c'
down_revision = '2d8a350b4885'
from alembic import op
def upgrade():
conn = op.get_bind()
# This rigamarole is only neces... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import unified_strdate, determine_ext
class RoxwelIE(InfoExtractor):
_VALID_URL = r'https?://www\.roxwel\.com/player/(?P<filename>.+?)(\.|\?|$)'
_TEST = {
'url': 'http://www.roxwel.com/player/passionpit... |
"""Tests for the `ShuffleAndRepeatFusion` optimization."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.experimental.ops import optimization
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.... |
import json
import pytest
from ansible.modules.packaging.language import pip
pytestmark = pytest.mark.usefixtures('patch_ansible_module')
@pytest.mark.parametrize('patch_ansible_module', [{'name': 'six'}], indirect=['patch_ansible_module'])
def test_failure_when_pip_absent(mocker, capfd):
get_bin_path = mocke... |
import sys
import thread
import time
import argparse
from twisted.python import log
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
from client_confi... |
from __future__ import unicode_literals
from c1218.errors import C1218ReadTableError
from c1219.access.security import C1219SecurityAccess
from c1219.constants import C1219_TABLES, C1219_PROCEDURE_NAMES
from termineter.module import TermineterModuleOptical
class Module(TermineterModuleOptical):
def __init__(self, *a... |
from openerp import models, fields, api, exceptions
import logging
import base64
import tempfile
import shutil
import pysftp
import os
_logger = logging.getLogger(__name__)
class fds_inherit_post_dd_export_upload_wizard(models.TransientModel):
''' This addon allows you to upload the Direct Debit gebe... |
# -*- coding: utf-8 -*-
import hashlib
import json
import zlib
from base64 import b64decode
from django.conf.urls import url, include
from django.contrib.staticfiles import views
from rest_framework import routers
from rest_framework.response import Response
from rest_framework import viewsets, serializers
from vmpr... |
from __future__ import absolute_import
from django.db import models, IntegrityError
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from .models import (R, RChild, S, T, U, A, M, MR, MRNull,
create_a, get_default_r, User, Avatar, HiddenUser, HiddenUserProfile)
class OnDeleteTests(TestCase... |
from __future__ import print_function
import os
import sys
import subprocess as sp
import shlex
import shutil
import tempfile
import time
import platform as plat
class ModelTestSetup(object):
def __init__(self):
self.my_dir = os.path.dirname(os.path.realpath(__file__))
self.exp_dir = os.path.joi... |
import os, os.path, unittest
from django.contrib.gis.gdal import Driver, OGRException
valid_drivers = ('ESRI Shapefile', 'MapInfo File', 'TIGER', 'S57', 'DGN',
'Memory', 'CSV', 'GML', 'KML')
invalid_drivers = ('Foo baz', 'clucka', 'ESRI Shp')
aliases = {'eSrI' : 'ESRI Shapefile',
'TigER/l... |
from gnuradio import gr
from gnuradio import filter
import sys, time
try:
import scipy
from scipy import fftpack
except ImportError:
print "Error: Program requires scipy (see: www.scipy.org)."
sys.exit(1)
try:
import pylab
from pylab import mlab
except ImportError:
print "Error: Program re... |
__author__ = 'Ashoo'
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.stats
import warnings
sns.set(color_codes=True)
# Reading the data where low_memory=False increases the program efficiency
data= pd.read_csv("gapminder.csv", low_memory=False)
# setting variab... |
"""Tests for samba.hostconfig."""
from samba.hostconfig import SharesContainer
from samba.tests import TestCase
class MockService(object):
def __init__(self, data):
self.data = data
def __getitem__(self, name):
return self.data[name]
class MockLoadParm(object):
def __init__(self, dat... |
# -*- coding: utf-8 -*-
from utilities import *
reload(sys)
sys.setdefaultencoding('utf8')
bot= telegram.Bot(TOKEN)
updater = Updater(TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
def main():
dp.add_handler(RegexHandler('^(/help|/Help|/HELP)$',help))
dp.add_handler(RegexHandler('^(/rappr... |
import struct
from enum import IntEnum
from typing import List
import common
import ipaddress
import mle
class TlvType(IntEnum):
EXT_ADDRESS = 0
ADDRESS16 = 1
MODE = 2
POLLING_PERIOD = 3
CONNECTIVITY = 4
ROUTE64 = 5
LEADER_DATA = 6
NETWORK_DATA = 7
IPV6_ADDRESS_LIST = 8
MAC_C... |
import re
import os
import struct
import bitstring
import sys
import numbers
from collections import namedtuple
def int_or_float(s):
# return number, trying to maintain int format
try:
return int(s)
except ValueError:
return float(s)
DBCSignal = namedtuple(
"DBCSignal", ["name", "start_bit", "size", "... |
def WebIDLTest(parser, harness):
threw = False
try:
parser.parse("""
[Constructor, NoInterfaceObject]
interface TestConstructorNoInterfaceObject {
};
""")
results = parser.finish()
except:
threw = True
harness.ok(threw, "Should have t... |
import asyncio
from unittest.mock import Mock
from asynctest import CoroutineMock
import pytest
@pytest.mark.asyncio
@asyncio.coroutine
def test_skip_outdated():
from jenkins_epo.extensions.jenkins import PollExtension
ext = PollExtension('test', Mock())
ext.current = ext.bot.current
ext.current.hea... |
from django.db.models import signals
from django.test import TestCase
from django.core import management
from django.utils import six
from . import models
PRE_SYNCDB_ARGS = ['app', 'create_models', 'verbosity', 'interactive', 'db']
SYNCDB_DATABASE = 'default'
SYNCDB_VERBOSITY = 1
SYNCDB_INTERACTIVE = False
class P... |
"""
MySQL database backend for Django.
Requires mysqlclient: https://pypi.python.org/pypi/mysqlclient/
MySQLdb is supported for Python 2 only: http://sourceforge.net/projects/mysql-python
"""
from __future__ import unicode_literals
import datetime
import re
import sys
import warnings
from django.conf import settings... |
#!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2010 (ita)
"""
Runner.py: Task scheduling and execution
"""
import random, atexit
try:
from queue import Queue
except ImportError:
from Queue import Queue
from waflib import Utils, Task, Errors, Logs
GAP = 10
"""
Wait for free tasks if there are at least... |
"""The tests for the microsoft face detect platform."""
from unittest.mock import patch, PropertyMock
from homeassistant.core import callback
from homeassistant.const import ATTR_ENTITY_PICTURE
from homeassistant.setup import setup_component
import homeassistant.components.image_processing as ip
import homeassistant.c... |
"""Tests for stream module."""
import unittest
import set_sys_path # Update sys.path to locate mod_pywebsocket module.
from mod_pywebsocket.stream import StreamHixie75
from test.test_msgutil import _create_request_hixie75
class StreamHixie75Test(unittest.TestCase):
"""A unittest for StreamHixie75 class."""
... |
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
import argparse as _argparse
import os
import tempfile
import sys
from pyLibrary.jsons import ref
from pyLibrary.dot import listwrap, wrap, unwrap
from pyLibrary.debugs.logs import Log
from pyLibrary.env.file... |
import os
EMPTY_PAGE_URL = 'file://' + os.path.abspath(os.path.dirname(__file__)) + '/../../resources/empty.html'
class LoadingHtmlPage(object):
def __init__(self, timeout=0, body=""):
self._body = body
self._timeout = timeout
def load_in(self, driver):
driver.get(EMPTY_PAGE_URL)
... |
"""Fixes listen mailing lists that have got purged from the IListLookup
utility. If an optional argument is provided, it's assumed to be
a log file (from a previous run) from which we read FAILED fixes
to try again.
"""
from zope.event import notify
from zope.app.event.objectevent import ObjectModifiedEvent
from zop... |
import jmespath
from pytest_terraform import terraform
from unittest import TestCase
from .common import event_data, BaseTest
from c7n.cwe import CloudWatchEvents
@terraform('event_bridge_bus')
def test_event_bus_describe(test, event_bridge_bus):
factory = test.replay_flight_data('test_cwe_bus_xaccount')
p ... |
#!/usr/bin/python
try:
import elementtree.ElementTree as et
except:
import xml.etree.ElementTree as et
import os
skip = ["emptyspace.jsp"]
def parsefile(file):
items = []
tree = et.parse(file)
root = tree.getroot()
for i in root.getiterator():
if i.tag.endswith('trans-unit'):
... |
"""Self-test suite for Cryptodome.Hash.SHA384"""
# Test vectors from various sources
# This is a list of (expected_result, input[, description]) tuples.
test_data = [
# RFC 4634: Section Page 8.4, "Test 1"
('cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7', 'ab... |
import sys
from oslo_db.sqlalchemy import models
from oslo_db.sqlalchemy import types as oslo_types
from oslo_log import log as logging
from oslo_utils import timeutils
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import DateTime
from sqlalchemy.dialects.postgresql import JSONB
from sq... |
import re
import sys
import time
import config
import multiprocessing
from os import getpid
from os import path
from os import makedirs
from os import environ
from os import fork
from os import dup2
from os import chdir
from os import setsid
from os import umask
from os import devnull
from os import listdir
from shuti... |
"""
Find the longest sequence of prefix shared by all the words in a string.
Example:
"abcdef abcdxxx abcdabcdef abcyy" => "abc"
"""
import unittest
import itertools
def longest_prefix(string):
words = string.split()
prefix = words[0]
for word in words[1:]:
l = 0
for pr, ch in zip(prefix... |
"""Upgrade Submit models."""
import warnings
from invenio.ext.sqlalchemy import db
from invenio.legacy.dbquery import run_sql
from invenio_upgrader.api import op
from sqlalchemy.exc import OperationalError
depends_on = ['invenio_release_1_1_0']
def info():
"""Info."""
return "Add a autoincrement id in sbm... |
from modules.OsmoseTranslation import T_
from .Analyser_Merge import Analyser_Merge, SourceDataGouv, CSV, Load, Conflate, Select, Mapping
class Analyser_Merge_Milestone_FR_metropole(Analyser_Merge):
def __init__(self, config, logger = None):
Analyser_Merge.__init__(self, config, logger)
doc = dict... |
import os
import re
def update_package_db(module):
cmd = "%s update" % (APK_PATH)
rc, stdout, stderr = module.run_command(cmd, check_rc=False)
if rc == 0:
return True
else:
module.fail_json(msg="could not update package db")
def query_package(module, name):
cmd = "%s -v info --inst... |
"""Main program for testing the infrastructure."""
__author__ = "Guido van Rossum <<EMAIL>>"
# Support imports (need to be imported first)
from . import support
# Python imports
import os
import sys
import logging
# Local imports
from .. import pytree
import pgen2
from pgen2 import driver
logging.basicConfig()
de... |
"""
Django settings for example project.
Generated by 'django-admin startproject' using Django 3.1a1.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from pathlib... |
from django.db.backends.base.features import BaseDatabaseFeatures
from django.db.utils import InterfaceError
class DatabaseFeatures(BaseDatabaseFeatures):
empty_fetchmany_value = ()
interprets_empty_strings_as_nulls = True
uses_savepoints = True
has_select_for_update = True
has_select_for_update_n... |
import mock
from nova import db
from nova.objects import virtual_interface as vif_obj
from nova.tests.objects import test_objects
fake_vif = {
'created_at': None,
'updated_at': None,
'deleted_at': None,
'deleted': 0,
'id': 1,
'address': '00:00:00:00:00:00',
'network_id': 123,
'instanc... |
"""
Studio unit test configuration and fixtures.
This module needs to exist because the pytest.ini in the cms package stops
pytest from looking for the conftest.py module in the parent directory when
only running cms tests.
"""
from __future__ import absolute_import, unicode_literals
import importlib
import os
impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.