content stringlengths 4 20k |
|---|
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import ast
import re
from pants.contrib.python.checks.tasks.checkstyle.common import CheckstylePlugin
class PrintStatements(CheckstylePlugin):
"""Enforce the use ... |
"""
Tools for sending email.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
# Imported for backwards compatibility, and for the sake
# of a cleaner namespace. These symbols used to be in
# django/core/mail.py before the int... |
from decimal import Decimal
from .db import StatsDict
class DictKey(object):
"""A simple wrapper used to prevent collisions with string dictionary keys.
Used by ``unknown_gen``.
"""
def __init__(self, name):
self.name = name
def __str__(self):
return str(self.name)
def csv_pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from translate.convert import php2po
from translate.convert import test_convert
from translate.misc import wStringIO
from translate.storage import po
from translate.storage import php
class TestPhp2PO:
def php2po(self, phpsource, phptemplate=None):
"""helper... |
from __future__ import division, absolute_import, print_function
from numpy.testing import *
import numpy.core as nx
import numpy.lib.ufunclike as ufl
from numpy.testing.decorators import deprecated
class TestUfunclike(TestCase):
def test_isposinf(self):
a = nx.array([nx.inf, -nx.inf, nx.nan, 0.0, 3.0, ... |
import datetime
import json
import logging
import select
import time
import openerp
import openerp.tools.config
import openerp.modules.registry
from openerp import http
from openerp.http import request
from openerp.osv import osv, fields, expression
from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
_logge... |
import sys
from twisted.internet import reactor
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.python import log
from autobahn.twisted.websocket import WebSocketClientFactory, \
WebSocketClientProtocol, \
connectWS
class EchoClientProtocol(WebSocketClientProtocol):
def sen... |
"""
Various data structures used in query construction.
Factored out from django.db.models.query to avoid making the main module very
large and/or so that they can be used by other modules without getting into
circular import difficulties.
"""
import weakref
from django.utils.copycompat import deepcopy
from django.u... |
from django.http import HttpResponse
from django.shortcuts import render
from sapl.crud.base import CrudAux, Crud
from sapl.lexml.OAIServer import OAIServerFactory, get_config
from sapl.rules import RP_DETAIL, RP_LIST
from .models import LexmlProvedor, LexmlPublicador
from .forms import LexmlProvedorForm
LexmlPubli... |
import os
import sys
import unittest
import http.client
import traceback
import github
atLeastPython26 = sys.hexversion >= 0x02060000
atLeastPython3 = sys.hexversion >= 0x03000000
atMostPython32 = sys.hexversion < 0x03030000
if atLeastPython26:
import json
else: # pragma no cover (Covered by all tests with Pyth... |
# -*- coding: utf-8 -*-
import re
import time
import urllib.parse
from pyload.core.datatypes.pyfile import PyFile
from ..base.account import BaseAccount
from ..base.captcha import BaseCaptcha
class ExtmatrixCom(BaseAccount):
__name__ = "ExtmatrixCom"
__type__ = "account"
__version__ = "0.01"
__stat... |
from model.project import Project
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
class ProjectHelper:
def __init__(self, app):
self.app = app
def open_projects(self):
... |
import os
import imp
from itertools import product, starmap
import distutils.command.install_lib as orig
class install_lib(orig.install_lib):
"""Don't add compiled flags to filenames of non-Python files"""
def run(self):
self.build()
outfiles = self.install()
if outfiles is not None:
... |
import core.modules
import core.modules.module_registry
from core.modules.vistrails_module import Module, ModuleError
import scipy
import scipy.interpolate
import scipy.ndimage
import vtk
from Array import *
from Matrix import *
class ArrayInterpModule(object):
my_namespace = 'scipy|interpolation'
class RBFIn... |
####################################################################################################
# neuropythy/geometry/__init__.py
# This file defines common rotation functions that are useful with cortical mesh spheres, such as
# those produced with FreeSurfer.
'''
The neuropythy.geometry package contains a numbe... |
"""
Object representing an OCR project, used to group files, batches,
and presets.
"""
import datetime
from django.db import models
from django.contrib.auth.models import User
from tagging import fields as taggingfields
import autoslug
from ocradmin.core import utils as ocrutils
from ocradmin.storage import registry... |
import mock
from neutron.agent.linux import polling
from neutron.tests import base
class TestGetPollingManager(base.BaseTestCase):
def test_return_always_poll_by_default(self):
with polling.get_polling_manager() as pm:
self.assertEqual(pm.__class__, polling.AlwaysPoll)
def test_manage_p... |
from __future__ import absolute_import
from kombu import Connection
from kombu.transport.virtual import exchange
from kombu.tests.mocks import Transport
from kombu.tests.utils import TestCase
from kombu.tests.utils import Mock
class ExchangeCase(TestCase):
type = None
def setUp(self):
if self.type:... |
from nupic.frameworks.prediction.helpers import importBaseDescription
config = dict(
#sensorVerbosity=3,
iterationCount = 25000,
spPeriodicStats = 0,
#numAValues = 25,
#numBValues = 25,
#encodingFieldStyleA = 'contiguous',
#encodingFieldWidthA = 50,
#encodingOnBits... |
import os
import shutil
import tempfile
import unittest
from multiprocessing import Manager, Process
from threading import Thread
from pants.pantsd.lock import OwnerPrintingInterProcessFileLock
def hold_lock_until_terminate(path, lock_held, terminate):
lock = OwnerPrintingInterProcessFileLock(path)
lock.acqu... |
import unittest
from numpy.testing import *
from numpy import array
from numpy.oldnumeric import *
from numpy.core.numeric import float32, float64, complex64, complex128, int8, \
int16, int32, int64, uint, uint8, uint16, uint32, uint64
class test_oldtypes(unittest.TestCase):
def test_oldtypes(self, level... |
import os
import argparse
import numpy as np
import matplotlib.pyplot as plt
# parse command line parameters
parser = argparse.ArgumentParser(description='Plot phase diagram.')
parser.add_argument('spikefiles', type=str, nargs='+', help='input files')
parser.add_argument('plotfile', type=str, help='output file')
args... |
import unittest
from telemetry import benchmark
from telemetry import benchmark_runner
from telemetry.testing import stream
import mock
class BenchmarkFoo(benchmark.Benchmark):
""" Benchmark Foo for testing."""
@classmethod
def Name(cls):
return 'FooBenchmark'
class BenchmarkBar(benchmark.Benchmark):
... |
#!/usr/bin/env python
#
# Generated Tue Jun 29 16:14:16 2004 by generateDS.py.
#
import sys
from xml.dom import minidom
from xml.sax import handler, make_parser
import xmlbehavior as supermod
class xml_behaviorSub(supermod.xml_behavior):
def __init__(self, base_impl_url='', behaviors=None):
supermod.xml... |
from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.utils... |
from __future__ import absolute_import, division, unicode_literals
import os
import sys
import codecs
import glob
import xml.sax.handler
base_path = os.path.split(__file__)[0]
test_dir = os.path.join(base_path, 'testdata')
sys.path.insert(0, os.path.abspath(os.path.join(base_path,
... |
import numpy
class MRSData(numpy.ndarray):
"""
numpy.ndarray subclass with additional metadata like sampling rate and echo
time.
"""
def __new__(cls, input_array, dt, f0, te=30, ppm0=4.7, voxel_dimensions=(10, 10, 10), transform=None, metadata=None):
# Input array is an already formed nda... |
"""Integration tests for Azure Active Directory / Microsoft Account provider."""
from third_party_auth.tests.specs import base
# pylint: disable=test-inherits-tests
class AzureADOauth2IntegrationTest(base.Oauth2IntegrationTest):
"""Integration tests for Azure Active Directory / Microsoft Account provider."""
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import copy
from ansible import constants as C
from ansible.module_utils.basic import AnsibleFallbackNotFound
from ansible.module_utils.iosxr import iosxr_argument_spec
from ansible.module_utils.six import iteritems
fro... |
from openerp import api, fields, models
# from openerp.exceptions import Warning
class ProductTemplate(models.Model):
_inherit = 'product.template'
def _get_property_context(property_field):
return (
"{'active_model': 'product.template', 'active_id': id, "
"'property_field': '... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import itertools
import time
import traceback
import warnings
from collections import OrderedDict
from importlib import import_module
from django.apps import apps
from django.core.management import call_command
from django.core.management.base import Bas... |
import sys
import re
import os
import ConfigParser
from novaclient import client as nova_client
from six import iteritems, itervalues
try:
import json
except ImportError:
import simplejson as json
sys.stderr.write("WARNING: this inventory module is deprecated. please migrate usage to openstack.py\n")
######... |
import os
import six
import imath
import IECore
import Gaffer
import GafferUITest
import GafferScene
import GafferSceneUI
class TransformToolTest( GafferUITest.TestCase ) :
def testSelectionEditability( self ) :
script = Gaffer.ScriptNode()
script["box"] = Gaffer.Box()
script["box"]["plane"] = GafferScene... |
#!/usr/bin/env python
# This example shows how to construct a surface from a point cloud.
# First we generate a volume using the
# vtkSurfaceReconstructionFilter. The volume values are a distance
# field. Once this is generated, the volume is countoured at a
# distance value of 0.0.
import os
import string
import vtk... |
import time
import json
import re
def retrieve_from_stash(request, key, timeout, default_value):
t0 = time.time()
while time.time() - t0 < timeout:
time.sleep(0.5)
value = request.server.stash.take(key=key)
if value is not None:
return value
return default_value
def main(request, response):
... |
import os
import subprocess
TEXT_FILE_EXTENSION = [
".bat",
".c",
".cfg",
".cmake",
".cpp",
".css",
".h",
".hh",
".hpp",
".html",
".inl",
".java",
".js",
".m",
".mk",
".mm",
".py",
".rule",
".sh",
".test",
".txt",
".xml",
".xsl... |
from __future__ import print_function, division, absolute_import, unicode_literals
import os
from textwrap import dedent
import defcon
from glyphsLib import to_glyphs, to_ufos, classes
import pytest
def make_font(features):
ufo = defcon.Font()
ufo.features = dedent(features)
return ufo
def roundtrip... |
import datetime
import logging
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'JobDesign'
db.create_table('jobsub_jobdesign', (
('description', self.gf('django.db.models... |
#! -*- Encoding: Latin-1 -*-
import os
import threading
import logging
import logging.handlers
import eftepede_globals
import pyftpdlib.authorizers
import eftepede_password
class Authorizer(pyftpdlib.authorizers.DummyAuthorizer):
def __init__(self, config, logger):
pyftpdlib.authorizers.D... |
"""
Chile specific form helpers.
"""
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField, Select
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_unicode
class CLRegionSelect(Select):
""... |
import unittest
import settings
from core.runners import TrashSiminar
from core.decorators import authorize
from simtools.timezone import system_now
class SubscribeUser(TrashSiminar):
@authorize(settings.INSTRUCTOR_EMAIL, settings.INSTRUCTOR_PASSWORD)
def test11_create_payment_card():
pass
@autho... |
"""Chain bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops.distributio... |
import sys
import argparse
import ConfigParser
from provision_dns import DnsProvisioner
from requests.exceptions import ConnectionError
class AddVirtualDns(object):
def __init__(self, args_str = None):
self._args = None
if not args_str:
args_str = ' '.join(sys.argv[1:])
self._p... |
"""Allow Google Apps domain administrators to set users' email settings.
EmailSettingsService: Set various email settings.
"""
__author__ = '<EMAIL>'
import gdata.apps
import gdata.apps.service
import gdata.service
API_VER='2.0'
# Forwarding and POP3 options
KEEP='KEEP'
ARCHIVE='ARCHIVE'
DELETE='DELETE'
ALL_MAI... |
"""
Django settings for CarFinder project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
... |
"""
Class for outlier detection.
This class provides a framework for outlier detection. It consists in
several methods that can be added to a covariance estimator in order to
assess the outlying-ness of the observations of a data set.
Such a "outlier detector" object is proposed constructed from a robust
covariance es... |
#!/usr/bin/env python3.3
# -*- coding: UTF-8 -*-
# enable debugging
import re
from os import listdir
from os.path import isfile, join
class FileSearch:
"""This object does the following:
1. looks into a specified folder
2.returns a list of all files.
3. excludes '~' files
4. evaluates the type of... |
"""Base constants and handlers."""
__author__ = 'Sean Lip'
import base64
import datetime
import hmac
import json
import logging
import os
import sys
import time
import traceback
import urllib
from core import counters
from core.domain import config_domain
from core.domain import config_services
from core.domain impo... |
"""
Load Override Data Transformer
"""
import json
from lms.djangoapps.courseware.models import StudentFieldOverride
from openedx.core.djangoapps.content.block_structure.transformer import BlockStructureTransformer
# The list of fields are in support of Individual due dates and could be expanded for other use cases... |
from __future__ import unicode_literals
from django.db.backends import BaseDatabaseIntrospection, FieldInfo
from django.utils.encoding import force_text
class DatabaseIntrospection(BaseDatabaseIntrospection):
# Maps type codes to Django Field types.
data_types_reverse = {
16: 'BooleanField',
... |
import netaddr
from nova import db
from nova import exception
from nova import flags
from nova import ipv6
from nova.network import manager
from nova.openstack.common import log as logging
LOG = logging.getLogger(__name__)
FLAGS = flags.FLAGS
def get_ipam_lib(net_man):
return QuantumNovaIPAMLib(net_man)
cla... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
import traceback
from ansible.module_utils.network.common.network import Network... |
import pytest
from datetime import datetime, timedelta
import pytz
import numpy as np
from pandas import (NaT, Index, Timestamp, Timedelta, Period,
DatetimeIndex, PeriodIndex,
TimedeltaIndex, Series, isna)
from pandas.util import testing as tm
from pandas._libs.tslib import iNa... |
"""
Satellite acquisition messages from the device.
"""
from construct import *
import json
from sbp.msg import SBP, SENDER_ID
from sbp.utils import fmt_repr, exclude_fields, walk_json_dict, containerize, greedy_string
# Automatically generated from piksi/yaml/swiftnav/sbp/acquisition.yaml with generate.py.
# Please ... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 31 10:40:14 2016
@author: jeremy
"""
import chimera.extension
class TetrEMO(chimera.extension.EMO):
def name(self):
return 'Tetr'
def description(self):
return 'Run the Tetr utility'
def categories(self):
return ['Utilities']
d... |
from __future__ import absolute_import, print_function, unicode_literals, division
from flask_restful import Resource
class ModuleResourcesManager(object):
def __init__(self, module):
self.resources = list()
self.module = module
def register_resource(self, resource):
"""
... |
from spack import *
from glob import glob
class Libxsmm(Package):
'''Library targeting Intel Architecture
for small, dense or sparse matrix multiplications,
and small convolutions.'''
homepage = 'https://github.com/hfp/libxsmm'
url = 'https://github.com/hfp/libxsmm/archive/1.8.1.tar.gz'
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import json
from ansible.module_utils.basic import AnsibleModule
def main():
module ... |
'''OpenGL extension EXT.texture_snorm
This module customises the behaviour of the
OpenGL.raw.GL.EXT.texture_snorm to provide a more
Python-friendly API
Overview (from the spec)
Fixed-point textures in unextended OpenGL have integer components,
but those values are taken to represent floating-point values in
th... |
"""Anima Previs Editor
"""
import os
import pymel
import anima
from anima.env.mayaEnv import Maya
from pymel import core
class PrevisUI(object):
"""Main class for managing the previs UI
"""
def __init__(self):
self.mEnv = Maya()
self.width = 265
self.height = 300
self... |
"""
Test cases for L{twisted.logger._file}.
"""
from io import StringIO
from zope.interface.verify import verifyObject, BrokenMethodImplementation
from twisted.trial.unittest import TestCase
from twisted.python.failure import Failure
from twisted.python.compat import unicode
from .._observer import ILogObserver
fro... |
import os
import argparse
import logging
logging.basicConfig(level=logging.DEBUG)
from common import find_mxnet, data, fit
from common.util import download_file
import mxnet as mx
def download_cifar10():
data_dir="data"
fnames = (os.path.join(data_dir, "cifar10_train.rec"),
os.path.join(data_dir,... |
from openerp.osv import fields, osv
class account_partner_ledger(osv.osv_memory):
"""
This wizard will provide the partner Ledger report by periods, between any two dates.
"""
_name = 'account.partner.ledger'
_inherit = 'account.common.partner.report'
_description = 'Account Partner Ledger'
... |
# -*- coding: utf-8 -*-
r"""
werkzeug.contrib.iterio
~~~~~~~~~~~~~~~~~~~~~~~
This module implements a :class:`IterIO` that converts an iterator into
a stream object and the other way round. Converting streams into
iterators requires the `greenlet`_ module.
To convert an iterator into a stream... |
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import print_function
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import os, shutil, time, sys
from calibre import isbytestring
from calibre.constants import (isw... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
REPO_DIR = os.path.join(BASE_DIR, os.pardir)
SECRET_KEY = 'w11nbg_3n4+e@qk^b55qgo5qygesn^3=&s1kwtlbpkai$(1jv3'
DEBUG = False
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = [
'localhost',
'127.0.0.1',
]
STATIC_ROOT = os.path.join(BASE_DIR, ".static")
INSTAL... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
class Bower(object):
def __init__(self, module, **kwargs):
self.module = module
self.name = kwargs['name']
self.offline = kwargs['offline']
sel... |
import base64
import time
import urllib
from openerp import osv, tools
from openerp.osv import fields, osv
from openerp.tools.translate import _
class base_report_sxw(osv.osv_memory):
"""Base Report sxw """
_name = 'base.report.sxw'
_columns = {
'report_id': fields.many2one('ir.actions.report.xml... |
"""
A classifier based on the Naive Bayes algorithm. In order to find the
probability for a label, this algorithm first uses the Bayes rule to
express P(label|features) in terms of P(label) and P(features|label)::
P(label) * P(features|label)
P(label|features) = ------------------------------
... |
from msrest.serialization import Model
class AzureIaaSVMErrorInfo(Model):
"""Azure IaaS VM workload-specific error information.
:param error_code: Error code.
:type error_code: int
:param error_title: Title: Typically, the entity that the error pertains
to.
:type error_title: str
:param ... |
"""Wrappers for primitive Neural Net (NN) Operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import,wildcard-import
from tensorflow.python.framework import common_shapes
from tensorflow.python.framework import ops
from t... |
"""
Eigenvalue spectrum of graphs.
"""
# Copyright (C) 2004-2011 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
import networkx as nx
__author__ = "\n".join(['Aric Hagberg (<EMAIL>)',
'Pieter Swart (<EMAIL>)',
... |
"""Contains definitions for the original form of Residual Networks.
The 'v1' residual networks (ResNets) implemented in this module were proposed
by:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
Other variants were introduced in:
[2] Kaiming ... |
#!/usr/bin/env python
from vtk import *
FILENAME_VERT_TABLE = "nodes.csv"
FILENAME_EDGE_TABLE = "edges.csv"
# Load the vertex table from CSV file
csv_vert_source = vtkDelimitedTextReader()
csv_vert_source.SetFieldDelimiterCharacters(",")
csv_vert_source.DetectNumericColumnsOn()
csv_vert_source.SetHaveHeaders(True)
... |
# -*- coding: utf-8 -*-
"""
Disqus static comment plugin for Pelican
====================================
This plugin adds a disqus_comments property to all articles.
Comments are fetched at generation time using disqus API.
"""
from disqusapi import DisqusAPI, Paginator
from pelican import signals
def init... |
"""
Test cases for the barbican key manager.
"""
import array
import base64
import binascii
import mock
from oslo_config import cfg
from cinder import exception
from cinder.keymgr import barbican
from cinder.keymgr import key as keymgr_key
from cinder.tests.unit.keymgr import test_key_mgr
CONF = cfg.CONF
CONF.impor... |
"""Class for Braava devices."""
import logging
from homeassistant.components.vacuum import SUPPORT_FAN_SPEED
from .irobot_base import SUPPORT_IROBOT, IRobotVacuum
_LOGGER = logging.getLogger(__name__)
ATTR_DETECTED_PAD = "detected_pad"
ATTR_LID_CLOSED = "lid_closed"
ATTR_TANK_PRESENT = "tank_present"
ATTR_TANK_LEVE... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 4 10:35:23 2015
@author: Anton O Lindhal
"""
import numpy as np
import lmfit
from . progress import update_progress
_2pi = 2 * np.pi
_gauss_fwhm_factor = 2 * np.sqrt(2 * np.log(2))
def gaussian(x, amplitude, center, sigma):
return amplitude * np.exp(-(x-center)**... |
from __future__ import print_function
try:
# Python 2 version
import ConfigParser
except ImportError:
# Python 3 version
import configparser as ConfigParser
import json
import argparse
import copy
import os
import re
import sys
from time import time
from collections import defaultdict
from distutils.ver... |
{
'name': 'MRP',
'version': '1.1',
'author': 'OpenERP SA',
'website': 'https://www.odoo.com/page/manufacturing',
'category': 'Manufacturing',
'sequence': 18,
'summary': 'Manufacturing Orders, Bill of Materials, Routing',
'depends': ['product', 'procurement', 'stock_account', 'resource', ... |
from blur.Stone import *
from blur.Classes import *
from blur.Burner import *
from PyQt4.QtCore import *
from PyQt4.QtSql import *
import re, traceback
class FusionBurner(JobBurner):
def __init__(self,job,slave):
JobBurner.__init__(self,job,slave)
self.Job = job
self.Slave = slave
self.CurrentFrame = None
s... |
"""
## @file
"""
from PIL import Image
from nupic.regions.ImageSensorFilters.BaseFilter import BaseFilter
class PadToFit(BaseFilter):
"""
** DEPRECATED ** Pad the image so that it fits the specified size.
"""
def __init__(self, width, height):
"""
** DEPRECATED **
@param width -- Target width,... |
"""
Support for starting, monitoring, and restarting child process.
"""
import warnings
from twisted.python import log
from twisted.internet import error, protocol, reactor as _reactor
from twisted.application import service
from twisted.protocols import basic
class DummyTransport:
disconnecting = 0
transport =... |
#!/usr/bin/env python
from __future__ import print_function
import os
from scriptCommon import catchPath
changedFiles = 0
def isSourceFile( path ):
return path.endswith( ".cpp" ) or path.endswith( ".h" ) or path.endswith( ".hpp" )
def fixAllFilesInDir( dir ):
for f in os.listdir( dir ):
path = os.... |
"""Module for handling Qt Linguist Phrase Book (.qph) files.
Extract from the `Qt Linguist Manual: Translators
<http://doc.trolltech.com/4.3/linguist-translators.html>`_:
.qph Qt Phrase Book Files are human-readable XML files containing standard
phrases and their translations. These files are created and updated by Qt... |
from msrest.pipeline import ClientRawResponse
from .. import models
class InheritanceOperations(object):
"""InheritanceOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserial... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Palestra',
fields=[
... |
from DocXMLRPCServer import DocXMLRPCServer
import httplib
import sys
from test import test_support
threading = test_support.import_module('threading')
import time
import socket
import unittest
PORT = None
def make_request_and_skipIf(condition, reason):
# If we skip the test, we have to make a request because the... |
#!/usr/bin/env python
'''
Pymodbus Server With Callbacks
--------------------------------------------------------------------------
This is an example of adding callbacks to a running modbus server
when a value is written to it. In order for this to work, it needs
a device-mapping file.
'''
#--------------------------... |
import threading
from fake_switches.switch_configuration import SwitchConfiguration
class ThreadedReactor(threading.Thread):
_threaded_reactor = None
@classmethod
def start_reactor(cls, models, reactor_hook_callbacks):
cls._threaded_reactor = ThreadedReactor()
for callback in reactor_h... |
#1
#Поиск работает в основном быстрее для set и dict т.к это hash таблицы.
#Перебор элементов быстрее в list и tuple,т.к это обычные массивы а set и dict для этого не предназначены.
#2
#Разница в том, что в первом случае массив будет содеержать три указателя на дин и тот же массив.
# Если мы изменим элемент в одном из... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
def crear_unidad_negocio_y_asociar(apps, schema_editor):
UnidadNegocio = apps.get_model('organizacion.UnidadNegocio')
ms, _ = UnidadNegocio.objects.get_or_create(codigo='M... |
from __future__ import absolute_import, unicode_literals
import argparse
import os
import haas
from .loader import Loader
from .plugin_context import PluginContext
from .plugin_manager import PluginManager
from .result import ResultCollector
from .utils import configure_logging
def create_argument_parser():
"""... |
# -*- coding: utf-8 -*-
import time
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QCursor
from PyQt5.QtTest import QTest
from PyQt5.QtWidgets import QApplication
from . import event_loop
from .gestures import Automaton, MIN_TIME_TO_AVOID_DOUBLE_CLICK
ONE_SECOND_IN_MILLIS = 1000
class KeyboardLayout:
... |
root = None
def run_test(root):
# Called from tests/run.py
# Execute the script we are wrapping
execfile('configs/learning_gem5/part1/simple.py') |
"""
Contains basic caching classes.
"""
import os
import suds
from tempfile import gettempdir as tmp
from suds.transport import *
from suds.sax.parser import Parser
from suds.sax.element import Element
from datetime import datetime as dt
from datetime import timedelta
from cStringIO import StringIO
from logging import... |
# coding: utf-8
from django.test import TestCase
class URLHandling(TestCase):
"""
Tests for URL handling in views and responses.
"""
redirect_target = "/views/%E4%B8%AD%E6%96%87/target/"
def test_combining_redirect(self):
"""
Tests that redirecting to an IRI, requiring encoding bef... |
import psycopg2 as dbapi2
import datetime
class Favorite:
def __init__(self, app):
self.app = app
def initialize_Favorite(self):
with dbapi2.connect(self.app.config['dsn']) as connection:
try:
cursor = connection.cursor()
cursor.execute(""... |
"""
NetEngine SNMP OpenWRT backend
"""
__all__ = ['OpenWRT']
import binascii
from datetime import timedelta
from netengine.backends.snmp import SNMP
class OpenWRT(SNMP):
"""
OpenWRT SNMP backend
"""
_oid_to_retrieve = '1.3.6.1.2.1.2.2.1.1'
_interface_dict = {}
def __str__(self):
... |
"""Package that handles non-debug, non-file output for run-webkit-tests."""
import math
import optparse
from webkitpy.tool import grammar
from webkitpy.layout_tests.models import test_expectations
from webkitpy.layout_tests.models.test_expectations import TestExpectations, TestExpectationParser
from webkitpy.layout_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.