content stringlengths 4 20k |
|---|
"""I am the support module for creating mail servers with twistd
"""
import os
import sys
from twisted.mail import mail
from twisted.mail import maildir
from twisted.mail import relay
from twisted.mail import relaymanager
from twisted.mail import alias
from twisted.python import usage
from twisted.cred import check... |
"""
Middleware to check for obedience to the WSGI specification.
Some of the things this checks:
* Signature of the application and start_response (including that
keyword arguments are not used).
* Environment checks:
- Environment is a dictionary (and not a subclass).
- That all the required keys are in the... |
# -*- coding: utf-8 -*-
'''
Spider campaign message models.
'''
# This file is part of spider.
# Distributed under the terms of the last AGPL License.
# The full license is in the file LICENCE, distributed as part of this software.
__author__ = 'Team Machine'
import uuid
from schematics import models
from sch... |
"""Base model class."""
__author__ = 'Sean Lip'
from core.platform import models
transaction_services = models.Registry.import_transaction_services()
import feconf
import utils
from google.appengine.datastore import datastore_query
from google.appengine.ext import ndb
class BaseModel(ndb.Model):
"""Base model ... |
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework import authentication
from rest_framework import filters
from rest_framework import permissions
from rest_framework import viewsets
from user_api.models import UserPreference
from user_api.serializers import UserSerializer,... |
"""
Some signal functions implemented using mpmath.
"""
from __future__ import division
try:
import mpmath
except ImportError:
mpmath = None
def _prod(seq):
"""Returns the product of the elements in the sequence `seq`."""
p = 1
for elem in seq:
p *= elem
return p
def _relative_degr... |
"""
Generator that produces an externs file for the Closure Compiler.
Note: This is a work in progress, and generated externs may require tweaking.
See https://developers.google.com/closure/compiler/docs/api-tutorial3#externs
"""
from code import Code
from js_util import JsUtil
from model import *
from schema_util im... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2013 sqlmap developers (http://sqlmap.org/)
See the file 'doc/COPYING' for copying permission
"""
from lib.core.common import Backend
from lib.core.common import randomInt
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
from hypothesis import given
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python.hypot... |
'''Thread-safe version of Tkinter.
Copyright (c) 2009, Allen B. Taylor
This module is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... |
from mod_pywebsocket import handshake
def web_socket_do_extra_handshake(request):
pass
def web_socket_transfer_data(request):
raise handshake.AbortedByUserException(
"Aborted in web_socket_transfer_data")
# vi:sts=4 sw=4 et |
"""
Directives for figures and simple images.
"""
__docformat__ = 'reStructuredText'
import sys
import urllib.request, urllib.parse, urllib.error
from docutils import nodes, utils
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.nodes import fully_normalize... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import collections,string
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class Lexer(object):
"""
Simple Lexer base class. Provides basic lexer framework and
helper functionality (read/peek/pu... |
import sys, time
from django.db.backends.creation import BaseDatabaseCreation
TEST_DATABASE_PREFIX = 'test_'
PASSWORD = 'Im_a_lumberjack'
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated Oracle column
# types, as strings. Column-type strings can contain fo... |
"""Common functions and exceptions used by WebSocket opening handshake
processors.
"""
from mod_pywebsocket import common
from mod_pywebsocket import http_header_util
class AbortedByUserException(Exception):
"""Exception for aborting a connection intentionally.
If this exception is raised in do_extra_hands... |
import theano, theano.tensor as T
import numpy as np
import theano_lstm
from out_to_in_op import OutputFormToInputFormOp
from theano_lstm import Embedding, LSTM, RNN, StackedCells, Layer, create_optimization_updates, masked_loss, MultiDropout
def has_hidden(layer):
"""
Whether a layer has a trainable
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from lxml import etree
from pythonic_testcase import PythonicTestCase
from .. import xsd
__all__ = ['SimpleTypeTestCase']
class SimpleTypeTestCase(PythonicTestCase):
xsd_type = None
# --- custom assertions ------------------... |
"""
tl;dr: all code code is licensed under simplified BSD, unless stated otherwise.
Unless stated otherwise in the source files, all code is copyright 2010 David
Wolever <<EMAIL>>. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the fol... |
from django.template.defaultfilters import dictsortreversed
from django.test import SimpleTestCase
class FunctionTests(SimpleTestCase):
def test_sort(self):
sorted_dicts = dictsortreversed(
[{'age': 23, 'name': 'Barbara-Ann'},
{'age': 63, 'name': 'Ra Ra Rasputin'},
{... |
import numpy as np
import copy
__all__ = ['SGD', 'Momentum', 'NesterovMomentum', 'AdaGrad', 'RMSProp',
'AdaDelta', 'Adam', 'Adamax', 'create_opt']
def create_opt(opt2copy, learning_rate=None):
opt = copy.copy(opt2copy) # Shallow copy
if learning_rate:
opt.learning_rate = learning_rate
... |
# -*- coding: utf-8 -*-
"""
py_vollib.ref_python.black.implied_volatility
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A library for option pricing, implied volatility, and
greek calculation. py_vollib is based on lets_be_rational,
a Python wrapper for LetsBeRational by Peter Jaeckel as
described below.
:copyright... |
import os
import atexit
from tempfile import mktemp
from numpy import *
from libtiff import TIFF
from libtiff import TIFFfile, TIFFimage
def test_write_read():
for compression in [None, 'lzw']:
for itype in [uint8, uint16, uint32, uint64,
int8, int16, int32, int64,
... |
#! /usr/bin/python
#! coding: utf-8
"""
Performs sequential coclustering.
Given a matrix,theta (column threshold), and phi (row threshold),
produces a set of clusterings (row clusters and column clusters)
"""
import sys, math, re, getopt
sys.path.append("../..")
from MLIB.cluster.matrix import MATRIX
from MLIB.utils.... |
from django.forms.models import inlineformset_factory
from django.test import TestCase
from regressiontests.inline_formsets.models import Poet, Poem, School, Parent, Child
class DeletionTests(TestCase):
def test_deletion(self):
PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True)
poe... |
from __future__ import print_function
import types
import inspect
import os
import warnings
import itkConfig
from itkTypes import itkCType
def itkFormatWarning(msg, *a):
""""Format the warnings issued by itk to display only the message.
This will ignore the filename and the linenumber where the warning was
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
OgrAlgorithm.py
---------------------
Date : November 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
************************... |
''' unit test template for ONTAP Ansible module '''
from __future__ import print_function
import json
import pytest
from units.compat import unittest
from units.compat.mock import patch, Mock
from ansible.module_utils import basic
from ansible.module_utils._text import to_bytes
import ansible.module_utils.netapp as n... |
#!/usr/bin/env python3
"""Send the contents of a directory as a MIME message."""
import os
import sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes
from argparse import ArgumentParser
from email import encoders
from email.message import Message
from email.mime.audio import MI... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
from openedx.core.djangoapps.xmodule_django.models import CourseKeyField
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(setti... |
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
import json
from urllib import urlencode
import httplib2
import os
CLIENT_ID = open(os.environ['HOME'] + "/.freebase_client_id").read()
CLIENT_SECRET = open(os.environ['HOME'] + "/.freebase_cli... |
from __future__ import absolute_import, division, print_function
__all__ = ['Permissions', 'GRANT_ALL_PERMISSIONS', 'DENY_ALL_PERMISSIONS']
class Permissions:
"""Permissions that can control/limit the behavior of MPI clients."""
add_agent = False
remove_agent = False
remove_client = False
set_active = Fals... |
import aiohttp_jinja2
from aiohttp import web
async def handle_404(request, response):
response = aiohttp_jinja2.render_template('404.html',
request,
{})
return response
async def handle_500(request, response):
r... |
from webkitpy.port import builders
from webkitpy.tool.commands.rebaseline import AbstractRebaseliningCommand
from webkitpy.tool.servers.gardeningserver import GardeningHTTPServer
class GardenOMatic(AbstractRebaseliningCommand):
name = "garden-o-matic"
help_text = "Command for gardening the WebKit tree."
... |
import subprocess
import fcntl
import os
import tempfile
import signal
from gi.repository import GLib, GObject, Gio
import commander.commands as commands
import commander.commands.exceptions
import commander.commands.result
__commander_module__ = True
__root__ = ['!', '!!', '!&']
class Process:
def __init__(self... |
"""Tests for validate-modules regexes."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
from validate_modules.main import TYPE_REGEX
@pytest.mark.parametrize('cstring,cexpected', [
['if type(foo) is Bar', True],
['if Bar is type(foo)', True],
['if ... |
from openerp import models, fields, api, _
from openerp.exceptions import ValidationError
from dateutil.relativedelta import relativedelta
import math
class HrHolidays(models.Model):
_inherit = 'hr.holidays'
@api.model
def _check_date_helper(self, employee_id, date):
status_id = self.holiday_stat... |
"""Classes for reading/writing binary data (such as TLS records)."""
from compat import *
class Writer:
def __init__(self, length=0):
#If length is zero, then this is just a "trial run" to determine length
self.index = 0
self.bytes = createByteArrayZeros(length)
def add(self, x, lengt... |
import Queue
import eventlet
from kombu import Connection
from oslo_config import cfg
from st2common import log as logging
from st2common.constants.action import (LIVEACTION_STATUS_SUCCEEDED, LIVEACTION_STATUS_FAILED,
LIVEACTION_STATUS_CANCELED)
from st2common.models.api.execut... |
#!/usr/bin/env python3
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
import sys, os, inspect, shutil, platform, textwrap, py_compile, site
from python_paths import py_ver, py_lib, py_exe, py_inc, py_dest,... |
from unstuck import *
class ExposedCall:
def __init__(self, func):
self.call = func
def __call__(self, *args, **kwargs):
raise(NotImplementedError)
class ExposedObject:
exposedMethods = {}
def __call__(self, *args, **kwargs):
raise(NotImplementedError)
class BoundMethod:
def __init__(self, instance, p... |
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use... |
text = """
#define FUNC$numR(m_r,m_func,$argt)\\
virtual m_r m_func($argtp) { \\
if (Thread::get_caller_ID()!=server_thread) {\\
m_r ret;\\
command_queue.push_and_ret( visual_server, &VisualServer::m_func,$argp,&ret);\\
return ret;\\
} else {\\
return visual_server->m_func($argp);\\
}\\
}
#define F... |
from __future__ import absolute_import, division, unicode_literals
import sys
import os
import json
import re
import html5lib
from . import support
from . import test_tokenizer
p = html5lib.HTMLParser()
unnamespaceExpected = re.compile(r"^(\|\s*)<html ([^>]+)>", re.M).sub
def main(out_path):
if not os.path.ex... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
from __future__ import print_function
import os
import sys
GREEN = '\033[32m'
YELLOW = '\033[33m'
RED = '\033[31m'
EXIT = '\033[0m'
INFO = 'info'
WARNING = 'warning'
ERROR = 'error'
LEVEL_COLOR_MAP = {
INFO: GREEN,
WARNING: YELLOW,
ERROR: RED
}
class Sender(object):
def __init__(self, prefix=None)... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from translate.convert import po2prop, test_convert
from translate.misc import wStringIO
from translate.storage import po
class TestPO2Prop:
def po2prop(self, posource):
"""helper that converts po source to .properties source without requiring files"""
... |
from setuptools import setup, find_packages
from collections import defaultdict
extra_packages = defaultdict(list)
def _is_requirement(line):
"""Returns whether the line is a valid package requirement."""
line = line.strip()
return line and not (line.startswith("-r") or line.startswith("#"))
def _read... |
__all__ = ['Parser']
import struct
import re
import stat
import os
import logging
from exceptions import ParseError
import core
# get logging object
log = logging.getLogger(__name__)
PACKET_TYPE_HEADER = 0x01
PACKED_TYPE_METADATA = 0x03
PACKED_TYPE_SETUP = 0x05
PACKET_TYPE_BITS = 0x07
PACKET_IS_SYNCPOINT = 0x08
#VO... |
# coding: utf-8
from __future__ import unicode_literals
import datetime
import re
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse_urlencode,
compat_urlparse,
)
from ..utils import (
parse_iso8601,
str_to_int,
)
class CamdemyIE(InfoExtractor):
_VALID_URL = r'https?://... |
"""Synchronize information from music player libraries
"""
from __future__ import division, absolute_import, print_function
from abc import abstractmethod, ABCMeta
from importlib import import_module
from beets.util.confit import ConfigValueError
from beets import ui
from beets.plugins import BeetsPlugin
import six
... |
"""
============================
Univariate Feature Selection
============================
An example showing univariate feature selection.
Noisy (non informative) features are added to the iris data and
univariate feature selection is applied. For each feature, we plot the
p-values for the univariate feature selecti... |
"""Tests for browser.network.schemehandler."""
import pytest
from qutebrowser.browser.webkit.network import schemehandler
def test_init():
handler = schemehandler.SchemeHandler(0)
assert handler._win_id == 0
def test_create_request():
handler = schemehandler.SchemeHandler(0)
with pytest.raises(Not... |
from zmq import *
# A way to access original zmq
import zmq as _zmq
import gevent.event
import gevent.core
import sys
class Context(_zmq.Context):
def socket(self, socket_type):
if self.closed:
raise _zmq.ZMQError(_zmq.ENOTSUP)
return Socket(self, socket_type)
class Socket(_zmq.Soc... |
"""Tests for emulated_roku library bindings."""
from unittest.mock import Mock, patch
from homeassistant.components.emulated_roku.binding import EmulatedRoku, \
EVENT_ROKU_COMMAND, \
ATTR_SOURCE_NAME, ATTR_COMMAND_TYPE, ATTR_KEY, ATTR_APP_ID, \
ROKU_COMMAND_KEYPRESS, ROKU_COMMAND_KEYDOWN, \
ROKU_COMMAN... |
import argparse
import logging
import numpy as np
from modshogun import (LibSVMFile, MulticlassLabels, MulticlassAccuracy)
from utils import get_features_and_labels
LOGGER = logging.getLogger(__file__)
def parse_arguments():
parser = argparse.ArgumentParser(description="Evaluate predicted \
labels againsy bare ... |
#coding=utf-8
#!/usr/bin/env python
import threading
import time
condition = threading.Condition()
products = 0
class Producer(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global condition, products
while Tr... |
# -*- coding: utf-8 -*-
"""
sphinx.directives.other
~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2007-2013 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from docutils.parsers.rst.directive... |
import logging
import copy
try:
from zabbix_api import ZabbixAPI, ZabbixAPISubClass
HAS_ZABBIX_API = True
except ImportError:
HAS_ZABBIX_API = False
# Extend the ZabbixAPI
# Since the zabbix-api python module too old (version 1.0, no higher version so far).
class ZabbixAPIExtends(ZabbixAPI):
def __i... |
from RunApp import RunApp
class RunException(RunApp):
@staticmethod
def validParams():
params = RunApp.validParams()
params.addParam('expect_err', "A regular expression that must occur in the ouput. (Test may terminiate unexpectedly and be considered passing)")
params.addParam('expect_assert', "DEBUG... |
try:
from functools import lru_cache
except ImportError:
# backport of Python's 3.3 lru_cache, written by Raymond Hettinger and
# licensed under MIT license, from:
# <http://code.activestate.com/recipes/578078-py26-and-py30-backport-of-python-33s-lru-cache/>
# Should be removed when Django only sup... |
"""Base stream class.
"""
# Note: request.connection.write/read are used in this module, even though
# mod_python document says that they should be used only in connection
# handlers. Unfortunately, we have no other options. For example,
# request.write/read are not suitable because they don't allow direct raw bytes
... |
import typing
import inspect
from json import JSONDecodeError
from urllib.parse import urlparse
from httpx import HTTPError, HTTPStatusError
from searx.exceptions import (SearxXPathSyntaxException, SearxEngineXPathException, SearxEngineAPIException,
SearxEngineAccessDeniedException)
from s... |
"""
This encapsulates the logic for displaying filters in the Django admin.
Filters are specified in models with the "list_filter" option.
Each filter subclass knows how to display a filter for a field that passes a
certain test -- e.g. being a DateField or ForeignKey.
"""
import datetime
from django.contrib.admin.op... |
"""Registration facilities for DOM. This module should not be used
directly. Instead, the functions getDOMImplementation and
registerDOMImplementation should be imported from xml.dom."""
from xml.dom.minicompat import * # isinstance, StringTypes
# This is a list of well-known implementations. Well-known names
# sho... |
"""Extract strings from command files and externalize into translation files.
Expects to be run from the root directory of the repository.
Usage:
extract.py pkg/kubectl/cmd/apply.go
"""
import fileinput
import sys
import re
class MatchHandler(object):
""" Simple holder for a regular expression and a function
... |
"""Data types composed of primitive data types."""
# stdlib imports
from operator import itemgetter
from collections import OrderedDict
from ctypes import (
LittleEndianStructure, BigEndianStructure, c_uint8
)
# local imports
from lf.dtypes.base import Primitive
from lf.dtypes.consts import BIG_ENDIAN, LITTLE_END... |
"""
Copyright (c) 2016, 2019 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import absolute_import, print_function, unicode_literals
import koji
import atomic_reactor.utils.koji as koji_util
fr... |
from Converter import Converter
from Poll import Poll
from enigma import iPlayableService
from Components.Element import cached, ElementError
class ServicePosition(Poll, Converter, object):
TYPE_LENGTH = 0
TYPE_POSITION = 1
TYPE_REMAINING = 2
TYPE_GAUGE = 3
def __init__(self, type):
Poll.__init__(self)
Conve... |
from __future__ import unicode_literals
from django.db import connection
from django.test import TestCase
from .models import A01, A02, B01, B02, C01, C02, Managed1, Unmanaged2
class SimpleTests(TestCase):
def test_simple(self):
"""
The main test here is that the all the models can be created w... |
from django.core.urlresolvers import reverse
from django import http
from mox3.mox import IgnoreArg # noqa
from mox3.mox import IsA # noqa
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
INDEX_URL = reverse('horizon:admin:info:index')
class SystemInfoViewTests(test.BaseAdm... |
import time
from openerp.osv import fields, osv
class yearly_salary_detail(osv.osv_memory):
_name ='yearly.salary.detail'
_description = 'Hr Salary Employee By Category Report'
_columns = {
'employee_ids': fields.many2many('hr.employee', 'payroll_emp_rel', 'payroll_id', 'employee_id', 'Employees', r... |
from consumer import Url_Id_Consumer
from db_control import Db_Controller
import Queue
import time
def main():
#name of threads
threadList = []
#list of consumers threads
threads = []
#max number of threads
MAX_NUM_T = 27
#queue of new TFBS to explore
TFBSQ = Queue.LifoQueue()
#... |
# -*- coding: utf-8 -*-
__author__ = 'anewbigging'
import unittest
import httpretty
from click.testing import CliRunner
from rwslib.extras.rwscmd import rwscmd
class TestRWSCMD(unittest.TestCase):
def setUp(self):
self.runner = CliRunner()
@httpretty.activate
def test_version(self):
h... |
"""## Placeholders
TensorFlow provides a placeholder operation that must be fed with data
on execution. For more info, see the section on [Feeding
data](../../how_tos/reading_data/index.md#feeding).
@@placeholder
@@placeholder_with_default
For feeding `SparseTensor`s which are composite type,
there is a convenience... |
#!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <<EMAIL>>'
__docformat__ = 'restructuredtext en'
import sys, os, shlex, sub... |
import gtk
import gobject
import gtk.glade
import threading
import urllib2
import os
import contextlib
from bb.ui.crumbs.buildmanager import BuildManager, BuildConfiguration
from bb.ui.crumbs.buildmanager import BuildManagerTreeView
from bb.ui.crumbs.runningbuild import RunningBuild, RunningBuildTreeView
# The metad... |
#!/usr/bin/python
"""convert .po to .js file."""
import json
import optparse
import os
import polib
import re
import sys
parser = optparse.OptionParser(usage="usage: %prog [options] pofile...")
parser.add_option("--callback", default="_.setTranslation", dest="callback",
help="callback function to ca... |
import numpy as np
import theano
import theano.tensor as T
import lasagne as nn
import data
import load
import nn_plankton
import dihedral
import tmp_dnn
import tta
features = [
# "hu",
# "tutorial",
"haralick",
# "aaronmoments",
# "lbp",
# "pftas",
# "zernike_moments",
# "image_siz... |
import os, sys
cmd = "doxygen_xml2qbk"
cmd = cmd + " --xml xml/%s.xml"
cmd = cmd + " --start_include boost/"
cmd = cmd + " --output_style alt"
cmd = cmd + " > generated/%s.qbk"
os.system("doxygen Doxyfile")
os.system(cmd % ("classboost_1_1geometry_1_1index_1_1rtree", "rtree"))
os.system(cmd % ("group__rtree__function... |
import itertools, math
# Start by defining the coordinate system in a convenient way. The position and scale of the diagram don't
# matter because we only care about the ratio of areas, not the absolute areas. So, let the bottom left
# of the diagram be the origin (x = 0, y = 0), and let each circle to have a radius ... |
#!/usr/bin/env python
import argparse
import cPickle
import traceback
import logging
import time
import sys
import numpy
import experiments.nmt
from experiments.nmt import\
RNNEncoderDecoder,\
prototype_state,\
parse_input
from experiments.nmt.numpy_compat import argpartition
logger = logging.getLogger... |
from tempest.api.compute import base
from tempest.common.utils import data_utils
from tempest import exceptions
from tempest import test
class ServerMetadataV3NegativeTest(base.BaseV3ComputeTest):
@classmethod
def setUpClass(cls):
super(ServerMetadataV3NegativeTest, cls).setUpClass()
cls.clie... |
from Kamaelia.UI.Tk.TkWindow import TkWindow
from Kamaelia.Support.Tk.Scrolling import ScrollingMenu
from Axon.Ipc import producerFinished, shutdownMicroprocess
import Tkinter
import pprint
class ArgumentsPanel(Tkinter.Frame):
def __init__(self, parent, theclass):
Tkinter.Frame.__init__(self, parent)
... |
''' A collection of functions used to compare Vcf objects.'''
import re
def common_variants(vcf1, vcf2):
''' Find common variants between two VCF objects
and return common variants in a list.
Args:
vcf1: first VCF object
vcf2: second VCF object
Notes:
this could be replaced ... |
'''
Compare images for similarity using the scikit-image structural similarity test
'''
import os
import sys
from skssim.ssim import structural_similarity as ssim
from skssim.dtype import img_as_float
import numpy as np
import Image, ImageMath
import ImageChops
import math
fname1 = "imageA.jpeg"
fname2 = "imageB.j... |
{
'name': "Web Widget Color",
'category': "web",
'version': "1.0",
"author": "Savoir-faire Linux, "
"Anybox, "
"Taktik SA, "
"Odoo Community Association (OCA)",
'depends': ['base', 'web'],
'data': [
'view/web_widget_color_view.xml'
],
'qw... |
import urllib
import json
# RequestHandler takes care of encoding the request body into format given by options
class RequestHandler():
@staticmethod
def renderKey(parents):
depth, new = 0, ''
for x in parents:
old = "[%s]" if depth > 0 else "%s"
new += old % x
depth += 1
return new
@staticmethod... |
# -*- coding: utf-8 -*-
"""
Sphinx Interface
~~~~~~~~~~~~~~~~
.. autofunction:: setup
.. autofunction:: init_bibtex_cache
.. autofunction:: purge_bibtex_cache
.. autofunction:: process_citations
.. autofunction:: process_citation_references
.. autofunction:: check_duplicate_labels
"""
... |
import os
import commands
_xend_autorestart = {
"NetBSD": True,
"Linux": True,
"SunOS": False,
}
_vif_script = {
"SunOS": "vif-vnic"
}
_tapif_script = {
"Linux": "no",
}
PROC_XEN_BALLOON = '/proc/xen/balloon'
SYSFS_XEN_MEMORY = '/sys/devices/system/xen_memory/xen_memory0'
def _linux_balloon_sta... |
"""Download handlers for different schemes"""
from scrapy.exceptions import NotSupported, NotConfigured
from scrapy.utils.httpobj import urlparse_cached
from scrapy.conf import settings
from scrapy.utils.misc import load_object
class DownloadHandlers(object):
def __init__(self):
self._handlers = {}
... |
"""Define names for all type symbols known in the standard interpreter.
Types that are part of optional modules (e.g. array) are not listed.
"""
import sys
# Iterators in Python aren't a matter of type but of protocol. A large
# and changing number of builtin types implement *some* flavor of
# iterator. Don... |
from test_framework.test_framework import DigiByteTestFramework
from test_framework.util import (
assert_equal,
assert_raises_rpc_error,
)
import json
import os
TESTSDIR = os.path.dirname(os.path.realpath(__file__))
class GetblockstatsTest(DigiByteTestFramework):
start_height = 101
max_stat_pos = 2
... |
# coding: utf8
from logging import getLogger
from string import strip as string_strip
log = getLogger("jsonrpc.connectors.redis")
def connect_redis(config, section="session:args:"):
"""
helper function for connecting to redis storage
Host server where redis is running
Port port... |
# -*- coding: utf-8 -*-
from six import text_type
from zerver.lib.test_helpers import WebhookTestCase
class StashHookTests(WebhookTestCase):
STREAM_NAME = 'stash'
URL_TEMPLATE = u"/api/v1/external/stash?stream={stream}"
def test_stash_message(self):
# type: () -> None
"""
Messages ... |
import base64
import hashlib
import httplib
import json
import os
import subprocess
import tempfile
import threading
import traceback
import urlparse
import uuid
from collections import defaultdict
from mozprocess import ProcessHandler
from .base import (ExecutorException,
Protocol,
... |
from extensions_paths import PRIVATE_TEMPLATES
from file_system import FileNotFoundError
class TableOfContentsRenderer(object):
'''Renders a table of contents pulled from a list of DocumentSections
returned from document_parser.ParseDocument.
This performs key functionality of DocumentRenderer, pulled into its... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
float_or_none,
int_or_none,
)
class DotsubIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?dotsub\.com/view/(?P<id>[^/]+)'
_TESTS = [{
'url': 'https://dotsub.com/view/9c63db2a-fa95-4838-8e6e-13... |
import wx
import json
from pprint import pprint
from autobahn.twisted.websocket import WebSocketClientProtocol, \
WebSocketClientFactory
class MyFrame(wx.Frame):
"""
Our UI frame to show.
This is taken from http://www.wxpython.org/test7.py.html and modified
for sending events via WebSocket.
... |
# -*- coding: utf-8 -*-
import argparse
import sys
from cms.db import SessionGen, Task, Contest, Participation, User, engine, Dataset, Testcase, \
Statement, Attachment, Manager, SubmissionFormatElement
from cmsocial.db import SocialTask, SocialContest, SocialParticipation, SocialUser, Lesson, \
Lesson... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
import time
from copy import deepcopy
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.nxos.nxos import load_config, run_commands
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.