content string |
|---|
import csv
import re
from FaustBot.Communication.Connection import Connection
from FaustBot.Modules.PrivMsgObserverPrototype import PrivMsgObserverPrototype
class ICDObserver(PrivMsgObserverPrototype):
@staticmethod
def cmd():
return None
@staticmethod
def help():
return None
de... |
"""
Produce k-mer counts for all the k-mers in the given sequence file,
using the given countgraph.
% python sandbox/count-kmers-single.py <fasta/fastq>
Use '-h' for parameter help.
"""
from __future__ import print_function
import sys
import khmer
import argparse
import screed
import csv
from khmer.khmer_args import... |
import re
import rope.base.pynames
from rope.base import pynames, pyobjects, codeanalyze, evaluate, exceptions, utils, worder
class Finder(object):
"""For finding occurrences of a name
The constructor takes a `filters` argument. It should be a list
of functions that take a single argument. For each po... |
# -*- coding: utf-8 -*-
import logging
import os
import time
from os import listdir
from os.path import join
from threading import Thread, Lock
from select import select
from Queue import Queue, Empty
import openerp
import openerp.addons.hw_proxy.controllers.main as hw_proxy
from openerp import http
from openerp.http ... |
from django.core import urlresolvers
from django.template import defaultfilters as d_filters
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from horizon import exceptions
from horizon import tables
from hori... |
"""
Model used by Video module for Branding configuration.
Includes:
BrandingInfoConfig: A ConfigurationModel for managing how Video Module will
use Branding.
"""
import json
from django.db.models import TextField
from django.core.exceptions import ValidationError
from config_models.models import Configura... |
from __future__ import unicode_literals
import datetime
import pickle
import unittest
import warnings
from django.test import TestCase
from django.utils import six
from django.utils.encoding import force_text
from django.utils.version import get_version
from .models import Container, Event, Group, Happening, M2MMode... |
import os
import tempfile
def add_job(module, result, at_cmd, count, units, command, script_file):
at_command = "%s -f %s now + %s %s" % (at_cmd, script_file, count, units)
rc, out, err = module.run_command(at_command, check_rc=True)
if command:
os.unlink(script_file)
result['changed'] = True
... |
"""
:module: mom.os.path
:synopsis: Directory walking, listing, and path sanitizing functions.
Functions
---------
.. autofunction:: get_dir_walker
.. autofunction:: walk
.. autofunction:: listdir
.. autofunction:: list_directories
.. autofunction:: list_files
.. autofunction:: absolute_path
.. autofunction:: real_abs... |
import cgi
import logging
import re
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import memcache
from google.appengine.api import urlfetch
# TODO(nickbaum): unit tests
# TODO(nickbaum): is this the right way to do constants?
cl... |
# this contains imports plugins that configure py.test for astropy tests.
# by importing them here in conftest.py they are discoverable by py.test
# no matter how it is invoked within the source tree.
from astropy.tests.pytest_plugins import *
## Uncomment the following line to treat all DeprecationWarnings as
## exc... |
from __future__ import absolute_import
from collections import OrderedDict
import os
import re
import shutil
import signal
import time
import traceback
import flask
import gevent
import gevent.event
import gevent.queue
from . import utils
from .config import config_value
from .dataset import DatasetJob
from .job imp... |
import unittest
from datasets import *
class TestSimplest(Structure):
_fields = [Parsable('base', required=True, positional=True, keyword=False),
Parsable('myParam', required=True, positional=False, keyword=True)]
def test_simplest():
t = TestSimplest(base='a', myParam='b')
assert t.get_di... |
from . import widget
from browser import doc,html
class Slider(widget.Widget):
def __init__(self, id=None, label=False):
self._div_shell=html.DIV(Class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all")
widget.Widget.__init__(self, self._div_shell, 'slider', id)
self._h... |
"""Python v2 to v3 migration module"""
from decimal import Decimal
import struct
import sys
from .custom_types import HexLiteral
# pylint: disable=E0602,E1103
PY2 = sys.version_info[0] == 2
if PY2:
NUMERIC_TYPES = (int, float, Decimal, HexLiteral, long)
INT_TYPES = (int, long)
UNICODE_TYPES = (unicode,... |
"""Administrative frontend for viewing reports and setting status of hosts."""
__author__ = '<EMAIL> (Drew Hintz)'
import json
import logging
import os
import auth
import datastore
import jinja2
import password_change
import webapp2
import xsrf
from google.appengine.ext import db
JINJA_ENVIRONMENT = jinja2.Enviro... |
# This is just a kludge so that bdist_rpm doesn't guess wrong about the
# distribution name and version, if the egg_info command is going to alter
# them, another kludge to allow you to build old-style non-egg RPMs, and
# finally, a kludge to track .rpm files for uploading when run on Python <2.5.
from distutils.comma... |
# -*- coding:utf-8 -*-
"""
Created on 2014/07/31
@author: Jimmy Liu
@group : waditu
@contact: <EMAIL>
"""
VERSION = '0.3.6'
K_LABELS = ['D', 'W', 'M']
K_MIN_LABELS = ['5', '15', '30', '60']
K_TYPE = {'D': 'akdaily', 'W': 'akweekly', 'M': 'akmonthly'}
INDEX_LABELS = ['sh', 'sz', 'hs300', 'sz50', 'cyb', 'zxb... |
"""
Benchmarks on the power iterations phase in randomized SVD.
We test on various synthetic and real datasets the effect of increasing
the number of power iterations in terms of quality of approximation
and running time. A number greater than 0 should help with noisy matrices,
which are characterized by a slow spectr... |
"""Django middleware for NDB."""
__author__ = 'James A. Morrison'
from . import eventloop, tasklets
class NdbDjangoMiddleware(object):
"""Django middleware for NDB.
To use NDB with django, add
'ndb.NdbDjangoMiddleware',
to the MIDDLEWARE_CLASSES entry in your Django settings.py file.
Or, if you are u... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from .generic import GenericIE
from ..utils import (
determine_ext,
ExtractorError,
qualities,
int_or_none,
parse_duration,
unified_strdate,
xpath_text,
update_url_query,
)
from ..compat... |
from ..base import BaseEstimator, TransformerMixin
from ..utils import check_array
def _identity(X):
"""The identity function.
"""
return X
class FunctionTransformer(BaseEstimator, TransformerMixin):
"""Constructs a transformer from an arbitrary callable.
A FunctionTransformer forwards its X (a... |
{
'name': 'Recurring Documents',
'version': '1.0',
'category': 'Tools',
'description': """
Create recurring documents.
===========================
This module allows to create new documents and add subscriptions on that document.
e.g. To have an invoice generated automatically periodically:
----------... |
import zookeeper, time, threading
f = open("out.log","w")
zookeeper.set_log_stream(f)
connected = False
conn_cv = threading.Condition( )
def my_connection_watcher(handle,type,state,path):
global connected, conn_cv
print "Connected, handle is ", handle
conn_cv.acquire()
connected = True
conn_cv.no... |
#!/usr/bin/env python
"""Reporting tests."""
from grr.lib import aff4
from grr.lib import flags
from grr.lib import test_lib
from grr.lib.aff4_objects import reports
from grr.lib.rdfvalues import client as rdf_client
class ReportsTest(test_lib.AFF4ObjectTest):
"""Test the timeline implementation."""
def testCli... |
from django.test import SimpleTestCase
from ..utils import setup
class InvalidStringTests(SimpleTestCase):
libraries = {'i18n': 'django.templatetags.i18n'}
@setup({'invalidstr01': '{{ var|default:"Foo" }}'})
def test_invalidstr01(self):
output = self.engine.render_to_string('invalidstr01')
... |
#!/usr/bin/env python
import env
import os
import sys
from subprocess import Popen, call
from tempfile import TemporaryFile
from run_unit_tests import run_unit_tests
ROBOT_ARGS = [
'--doc', 'SeleniumSPacceptanceSPtestsSPwithSP%(browser)s',
'--outputdir', '%(outdir)s',
'--variable', 'browser:%(browser)s',... |
#!/user/bin/env python
# Gmail.py
# Checks for new mail using IMAPclient and gmail account
# Uses callback to react to push button to send text message
from imapclient import IMAPClient
import time
import RPi.GPIO as GPIO
# Flag to enable debugging statements
DEBUG = True
# Used for IMAP mail retrieval
HOSTNAME = '... |
import pygtk
pygtk.require("2.0")
import gtk
from skarphedadmin.glue.lng import _
class YesNoPage(gtk.Frame):
def __init__(self, par, message, callback):
gtk.Frame.__init__(self, _("Yes/No"))
self.par = par
self.hbox = gtk.HBox()
self.vbox = gtk.VBox()
self.dummy = gtk.Labe... |
#!/usr/bin/env python
#
# Tests for dakota_utils.models.hydrotrend.
#
# Call with:
# $ nosetests -sv
#
# Mark Piper (<EMAIL>)
from nose.tools import *
import os
import tempfile
import shutil
from dakota_utils.models.hydrotrend import HydroTrend
def setup_module():
print('HydroTrend tests:')
os.environ['_tes... |
"""General tests for embeddings"""
# LICENSE: Simplified BSD https://github.com/mmp2/megaman/blob/master/LICENSE
from itertools import product
import numpy as np
from numpy.testing import assert_raises, assert_allclose
from megaman.embedding import (Isomap, LocallyLinearEmbedding,
LTS... |
from .euctwfreq import (EUCTWCharToFreqOrder, EUCTW_TABLE_SIZE,
EUCTW_TYPICAL_DISTRIBUTION_RATIO)
from .euckrfreq import (EUCKRCharToFreqOrder, EUCKR_TABLE_SIZE,
EUCKR_TYPICAL_DISTRIBUTION_RATIO)
from .gb2312freq import (GB2312CharToFreqOrder, GB2312_TABLE_SIZE,
... |
from heat.common.i18n import _
from heat.engine import constraints
from heat.engine import properties
from heat.engine import resource
from heat.engine import support
class GlanceImage(resource.Resource):
'''
A resource managing for image in Glance.
'''
support_status = support.SupportStatus(version=... |
"""Simple routines for logging, obtaining thread stack information."""
import sys
import traceback
def log_thread_state(logger, name, thread_id, msg=''):
"""Log information about the given thread state."""
stack = _find_thread_stack(thread_id)
assert(stack is not None)
logger("")
logger("%s (tid ... |
"""
Implementation of JSONDecoder
"""
import re
from simplejson.scanner import Scanner, pattern
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
def _floatconstants():
import struct
import sys
_BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
if sys.byteorder != 'big':
_BYT... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
try:
import botocore
except ImportError:
pass # handled by AnsibleAWSModule
from ansible.module_utils.aws.core import AnsibleAWSModule
from ansible.module_util... |
# -*- coding: utf-8 -*-
import calendar
from datetime import date
from dateutil import relativedelta
import json
from openerp import tools
from openerp.osv import fields, osv
class crm_case_section(osv.Model):
_inherit = 'crm.case.section'
_inherits = {'mail.alias': 'alias_id'}
def _get_opportunities_d... |
import hashlib
import numpy as np
import h5py
from ..database import db
class BrainData(object):
def __init__(self, data, subject, **kwargs):
if isinstance(data, str):
import nibabel
nib = nibabel.load(data)
data = nib.get_data().T
self._data = data
try:... |
"""
setup for HomeSpendWatch
"""
from setuptools import setup, find_packages
import os, glob
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
def get_version():
""" return a version number, or error string.
We are assuming a file version.txt al... |
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
ALIAS = "image-size"
authorize = extensions.soft_extension_authorizer('compute', 'v3:' + ALIAS)
class ImageSizeController(wsgi.Controller):
def _extend_image(self, image, image_cache):
key = "OS-EXT-IMG-SIZE:size"
ima... |
"""
Global Django exception and warning classes.
"""
from django.utils import six
from django.utils.encoding import force_text
class FieldDoesNotExist(Exception):
"""The requested model field does not exist"""
pass
class DjangoRuntimeWarning(RuntimeWarning):
pass
class AppRegistryNotReady(Exception):
... |
import time, sys, signal, atexit
import pyupm_vcap as sensorObj
## Exit handlers ##
# This function stops python from printing a stacktrace when you hit control-C
def SIGINTHandler(signum, frame):
raise SystemExit
# This function lets you run code on exit
def exitHandler():
print "Exiting..."
sys.exit(0)
# Regist... |
import platform
import signal
import subprocess
import time
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common import utils
class Service(object):
"""
Object that manages the starting and stopping of PhantomJS / Ghostdriver
"""
def __init__(self, executable_path,... |
import hr_payroll_payslips_by_employees
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""Command line tool for generating ProtoRPC definitions from descriptors."""
import errno
import logging
import optparse
import os
import sys
from protorpc import descriptor
from protorpc import generate_python
from protorpc import protobuf
from protorpc import registry
from protorpc import transport
from protorpc i... |
import unittest
from urllib3.filepost import encode_multipart_formdata, iter_fields
from urllib3.fields import RequestField
from urllib3.packages.six import b, u
BOUNDARY = '!! test boundary !!'
class TestIterfields(unittest.TestCase):
def test_dict(self):
for fieldname, value in iter_fields(dict(a='b... |
#!/usr/bin/env python
"""
Syncronizam doua fisiere
"""
from __future__ import print_function
import os
import argparse
import shutil
from functii_auxiliare import get_hash
from functii_auxiliare import get_last_edit
from functii_auxiliare import write_sync_file
from functii_auxiliare import read_sync_file
from functii_... |
root.system.cpu.workload = EioProcess(file = binpath('anagram',
'anagram-vshort.eio.gz'))
root.system.cpu.max_insts_any_thread = 500000 |
import os
import logging
from collections import OrderedDict
from edalize.edatool import Edatool
logger = logging.getLogger(__name__)
class Xsim(Edatool):
argtypes = ['plusarg', 'vlogdefine', 'vlogparam', 'generic']
MAKEFILE_TEMPLATE="""#Auto generated by Edalize
include config.mk
all: xsim.dir/$(TARGET)/... |
from __future__ import print_function
import json
import sys
def PrintError(*err):
print(*err, file=sys.stderr)
def main():
try:
obj = json.load(sys.stdin)
except Exception, e:
PrintError("Error loading JSON: {0}".format(str(e)))
if len(sys.argv) == 1:
# if we don't have a query string, return s... |
import os
import signal
import subprocess
import time
from watchdog.utils import echo, has_attribute
from watchdog.events import PatternMatchingEventHandler
class Trick(PatternMatchingEventHandler):
"""Your tricks should subclass this class."""
@classmethod
def generate_yaml(cls):
context = dic... |
from django.db import models
from countries.models import Country
from people.models import Person
# Models -----------------------------------------
class Company(models.Model):
SOLE_TRADER = 1
CORPORATION = 2
TYPE_CHOICES = (
(SOLE_TRADER, 'Sole Trader'),
(CORPORATION, 'Corporation'),... |
from FileManagement.interface_filehandler import *
# Brendan
import pickle
import os
import sys
import math
# kate
import re
from datetime import *
# Kris Little design
class FileHandler(IFileHandler):
def __init__(self):
self.valid = True
# Kris
def load_file(self, file):
... |
"""Tests for templates module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gast
from tensorflow.contrib.py2tf.pyct import compiler
from tensorflow.contrib.py2tf.pyct import templates
from tensorflow.python.platform import test
class Templat... |
import unittest
import pfg
from pfg import util
class TestCase(unittest.TestCase):
def assertFormatMatches(self, format_str, data_type, native, memory_le, memory_be):
fd = pfg.describe(format_str)
self.assertEqual(data_type, fd.data_type)
self.assertEqual(native, fd.native)
self.ass... |
import time
from mcts.webapi_tests.semiauto import TestCase
from mcts.webapi_tests.telephony import TelephonyTestCommon
class TestTelephonyOutgoing(TestCase, TelephonyTestCommon):
"""
This is a test for the `WebTelephony API`_ which will:
- Disable the default gaia dialer, so that the test app can handl... |
from __future__ import unicode_literals
from functools import total_ordering
from django.contrib.gis.geos import (
LinearRing, LineString, Point, Polygon, fromstr,
)
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
from django.utils.html import html_safe
@html_safe
@pyt... |
#coding:utf8
from baseclass.IterativeRecommender import IterativeRecommender
from random import choice
from tool.qmath import sigmoid
from math import log
from collections import defaultdict
#import tensorflow as tf
class BPR(IterativeRecommender):
# BPR:Bayesian Personalized Ranking from Implicit Feedback
# S... |
"""Tool for checking if patch contains a regression test.
By default runs against current patch but can be set to use any gerrit review
as specified by change number (uses 'git review -d').
Idea: take tests from patch to check, and run against code from previous patch.
If new tests pass, then no regression test, if n... |
import logging
import re
import os
from autotest.client.shared import error
from autotest.client.shared import utils
from virttest import utils_net, utils_test, utils_misc
from virttest import aexpect
from virttest import remote
from virttest import data_dir
@error.context_aware
def run(test, params, env):
"""
... |
"""
The I{builder} module provides an wsdl/xsd defined types factory
"""
from logging import getLogger
from suds import *
from suds.sudsobject import Factory
log = getLogger(__name__)
class Builder:
""" Builder used to construct an object for types defined in the schema """
def __init__(self, resolver)... |
# coding: utf-8
import json
import re
import xml.etree.ElementTree
from .common import InfoExtractor
class JeuxVideoIE(InfoExtractor):
_VALID_URL = r'http://.*?\.jeuxvideo\.com/.*/(.*?)-\d+\.htm'
_TEST = {
u'url': u'http://www.jeuxvideo.com/reportages-videos-jeux/0004/00046170/tearaway-playstation-... |
"""Implementation of compile_html based on Mistune."""
from __future__ import unicode_literals
import codecs
import os
import re
try:
import mistune
except ImportError:
mistune = None # NOQA
try:
from collections import OrderedDict
except ImportError:
OrderedDict = dict # NOQA
from nikola.plugin_c... |
from __future__ import division
from os.path import join
from .base import QiitaObject
from .exceptions import QiitaDBDuplicateError
from .util import (insert_filepaths, convert_to_id,
get_mountpoint)
from .sql_connection import SQLConnectionHandler
class Reference(QiitaObject):
r"""Object to ... |
from __future__ import unicode_literals
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j. F Y'
TIME_FORMAT = 'H:i'
DATETIME_FORMAT = 'j. F Y H:i'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j. F'
SHORT_DATE_FORMAT = 'd.... |
import logging
from functools import wraps, partial
from django.views.decorators.csrf import csrf_exempt
from django import http
from astakos.im import transaction
from django.utils import simplejson as json
from django.forms.models import model_to_dict
from django.core.validators import validate_email, ValidationErr... |
from __future__ import with_statement
from django.db import connection, transaction, IntegrityError
from django.test import TransactionTestCase, skipUnlessDBFeature
from models import Reporter
class TransactionContextManagerTests(TransactionTestCase):
def create_reporter_and_fail(self):
Reporter.objects... |
"""
This package contains objects used by
:py:class:`~.Node`\ s, but are not nodes themselves. This includes the
parameters of Templates or the attributes of HTML tags.
"""
from .attribute import Attribute
from .parameter import Parameter |
from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from ..medications import medications
from ..models import Prescription, MedicationDefinition
class PrescriptionCreator:
"""Creates all prescription records after completing patient history model.
"""
def __init__(self, ... |
from unittest import TestCase
import json
from pycrunchbase.resource.node import Node
from pycrunchbase.resource.utils import parse_date
class TestNode(Node):
KNOWN_PROPERTIES = ['property1', 'property2']
def _coerce_values(self):
# intentionally coerce bad values for test purposes
attr = '... |
import zlib
import struct
import socket
import ssl
from synchronousdeluge import rencode
__all__ = ["DelugeTransfer"]
class DelugeTransfer(object):
def __init__(self):
self.sock = None
self.conn = None
self.connected = False
def connect(self, hostport):
if self.connected:
... |
from . import ServiceBase
from ..language import language_set
from ..subtitles import get_subtitle_path, ResultSubtitle
from ..videos import Episode, Movie, UnknownVideo
import logging
logger = logging.getLogger(__name__)
class TheSubDB(ServiceBase):
server_url = 'http://api.thesubdb.com'
user_agent = 'SubD... |
"""
============================================================
Empirical evaluation of the impact of k-means initialization
============================================================
Evaluate the ability of k-means initializations strategies to make
the algorithm convergence robust as measured by the relative stan... |
from . import AWSProperty, AWSAttribute, validate_pausetime
from .validators import positive_integer, integer, boolean
class AutoScalingRollingUpdate(AWSProperty):
props = {
'MaxBatchSize': (positive_integer, False),
'MinInstancesInService': (integer, False),
'PauseTime': (validate_pauseti... |
# -*- coding: utf-8 -*-
from flask.ext import wtf
from google.appengine.api import app_identity
import flask
import auth
import util
import model
import config
from main import app
class ConfigUpdateForm(wtf.Form):
analytics_id = wtf.StringField('Analytics ID', filters=[util.strip_filter])
announcement_html = ... |
"""Libraries for constructing baseline tasks for the CIFAR-100 dataset."""
from tensorflow_federated.python.simulation.baselines.cifar100.image_classification_tasks import create_image_classification_task
from tensorflow_federated.python.simulation.baselines.cifar100.image_classification_tasks import DEFAULT_CROP_HEIG... |
import asyncio
import aiohttp
from aiohttp import web
import logging
from logging import handlers
import signal
import socket
import time
import unifi_ws_server
class StreamerContext(object):
pass
class RequestHandler(aiohttp.server.ServerHttpProtocol):
def __init__(self, **kwargs):
self._log = kwar... |
from xml.etree.ElementTree import Element, SubElement, tostring
import os
import re
import traceback
import xml.dom.minidom
from couchpotato.core.media.movie.providers.metadata.base import MovieMetaData
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import getTitle
from ... |
import argparse
import sys
import os
from osgeo import ogr
from osgeo import osr
import anyjson
import shapely.geometry
import shapely.ops
import codecs
import time
format = '%.8f %.8f'
tolerance = 0.01
infile = '/Users/kirilllebedev/Maps/50m-admin-0-countries/ne_50m_admin_0_countries.shp'
outfile = 'map.shp'
# Open... |
"""Test zha switch."""
from unittest.mock import call, patch
from homeassistant.components.switch import DOMAIN
from homeassistant.const import STATE_ON, STATE_OFF, STATE_UNAVAILABLE
from tests.common import mock_coro
from .common import (
async_init_zigpy_device, make_attribute, make_entity_id,
async_test_devi... |
#!/usr/bin/python
import struct
import sys
import hashlib
from pyasn1.type import univ
from pyasn1.codec.ber import encoder, decoder
f = open(sys.argv[1], 'rb')
filehdr = f.read(1024)
if filehdr[0:2] != 'MZ':
print "Not a DOS file."
sys.exit(0)
pepos = struct.unpack('<I', filehdr[60:64])[0]
if filehdr[pepos:p... |
import os
import zipfile
from thefuck.utils import for_app
def _is_bad_zip(file):
with zipfile.ZipFile(file, 'r') as archive:
return len(archive.namelist()) > 1
def _zip_file(command):
# unzip works that way:
# unzip [-flags] file[.zip] [file(s) ...] [-x file(s) ...]
# ^ ... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Project.status'
db.add_column('sentry_project', 'status', self.gf('django.db.models.fields.Positiv... |
from django.db.models import Prefetch, prefetch_related_objects
from django.test import TestCase
from .models import Author, Book, Reader
class PrefetchRelatedObjectsTests(TestCase):
"""
Since prefetch_related_objects() is just the inner part of
prefetch_related(), only do basic tests to ensure its API h... |
from . import constants
import sys
import codecs
from .latin1prober import Latin1Prober # windows-1252
from .mbcsgroupprober import MBCSGroupProber # multi-byte character sets
from .sbcsgroupprober import SBCSGroupProber # single-byte character sets
from .escprober import EscCharSetProber # ISO-2122, etc.
import re... |
from PySide import QtCore, QtGui
import dal
class DataPackModel(QtCore.QAbstractTableModel):
def __init__(self, parent = None):
super(DataPackModel, self).__init__(parent)
self.items = []
self.headers = [self.tr('Name' ),
self.tr('Language'),
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
CHOICES = (
(1, 'first'),
(2, 'second'),
)
@python_2_unicode_compatible
class Article(models.Model):
headline = models.CharField(max_length=100, defa... |
from __future__ import absolute_import
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api.labs import taskqueue
import logging
import os.path
import yaml
import time
import random
import re
import oauth
import buzz
... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'DocumentSet.header_image'
db.add_column(u'crowdataapp_documentset', 'header_image',
... |
"""Logging and Summary Operations."""
# pylint: disable=protected-access
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import gen_logging_... |
"""
hyperbola URL Configuration.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... |
import pytest
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selene import config
from selene.common.none_object import NoneObject
from selene.driver import SeleneDriver
from tests.acceptance.helpers.helper import get_test_driver
from tests.integration.helpers.givenpage imp... |
# -*- coding: utf-8 -*-
import multiscanner
def test_valid_reports_string():
reportlist = [([('file', 'result')], {'Name': 'Test', 'Type': 'Test'})]
r = multiscanner.parse_reports(reportlist, python=False)
assert r == '{"file":{"Test":"result"}}'
def test_valid_reports_python():
reportlist = [([('fi... |
#!/usr/bin/env python
import logging
import os
import sys
from django.core.management import execute_from_command_line
if 'DJANGO_SETTINGS_MODULE' not in os.environ:
if len(sys.argv) > 1 and sys.argv[1] == 'test':
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings_test'
else:
os.environ.setdefau... |
import os
import re
import threading
import time
import traceback
import socket
import struct
import azurelinuxagent.common.conf as conf
import azurelinuxagent.common.logger as logger
import azurelinuxagent.common.utils.textutil as textutil
from azurelinuxagent.common.exception import HttpError, ResourceGoneError, In... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
import re
# Import module snippets.
from ansible.module_utils.basic import AnsibleM... |
"""
Allows for playback and queue control
"""
__all__ = ['adapters', 'gst', 'queue', 'PLAYER', 'QUEUE']
import os
from xl import xdg
from . import player
from . import queue
PLAYER = player.ExailePlayer('player')
QUEUE = queue.PlayQueue(
PLAYER, 'queue', location=os.path.join(xdg.get_data_dir(), 'queue.sta... |
"""Unit tests for WebMessage."""
__revision__ = \
"$Id$"
from invenio.base.wrappers import lazy_import
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
webmessage_mailutils = lazy_import('invenio.utils.mail')
class TestQuotingMessage(InvenioTestCase):
"""Test for quoting messa... |
"""
Belgium-specific Form helpers
"""
from __future__ import absolute_import
from django.contrib.localflavor.be.be_provinces import PROVINCE_CHOICES
from django.contrib.localflavor.be.be_regions import REGION_CHOICES
from django.forms.fields import RegexField, Select
from django.utils.translation import ugettext_lazy... |
"""
Helper routines for catkin. These are distributed inside of rosdep2
to protect catkin against future rosdep2 API updatese. These helper
routines are assumed to run in an interactive mode with an end-user
and thus return end-user oriented error messages.
Errors are returned as arguments to raised :exc:`Validation... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.