content string |
|---|
from importlib import machinery
from .. import abc
from . import util
import unittest
class FinderTests(abc.FinderTests):
"""Test the finder for extension modules."""
def find_module(self, fullname):
importer = machinery.FileFinder(util.PATH,
(machinery.Extens... |
#
#
# w/ additions by Travis Oliphant, March 2002
__all__ = ['solve', 'solve_triangular', 'solveh_banded', 'solve_banded',
'inv', 'det', 'lstsq', 'pinv', 'pinv2']
from numpy import asarray, zeros, sum, conjugate, dot, transpose, \
asarray_chkfinite, single
import numpy
from flinalg import get_fl... |
from gi.repository import Gtk
from gi.repository import Gdk
from sugar3.graphics.icon import Icon
class OverlayWidget(Gtk.Window):
def __init__(self, widget_to_overlay):
Gtk.Window.__init__(self)
self._box = Gtk.VBox()
self._widget_to_overlay = widget_to_overlay
self.set_decorate... |
'''Functions for PKCS#1 version 1.5 encryption and signing
This module implements certain functionality from PKCS#1 version 1.5. For a
very clear example, read http://www.di-mgt.com.au/rsa_alg.html#pkcs1schemes
At least 8 bytes of random padding is used when encrypting a message. This makes
these methods much more se... |
"""
Unit tests for the gradient clipping cost
"""
import unittest
import numpy as np
from theano import function
from pylearn2.costs.mlp import Default
from pylearn2.models.mlp import MLP, Linear
from pylearn2.sandbox.rnn.costs.gradient_clipping import GradientClipping
class TestGradientClipping(unittest.TestCase):... |
from openerp.osv import fields, orm
from openerp.tools.translate import _
class travel_car_rental(orm.Model):
"""Car Rentals for travel"""
_name = 'travel.rental.car'
_description = _(__doc__)
@staticmethod
def _check_dep_arr_dates(start, end):
return not start or not end or start <= end
... |
import os
from textwrap import dedent
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from babel.messages.catalog import Catalog
from babel.messages.extract import extract_from_file
from babel.messages.pofile import write_po
from bab... |
# $HeadURL: $
''' BaseAction
Base class for Actions.
'''
from DIRAC import gLogger
__RCSID__ = '$Id: $'
class BaseAction( object ):
'''
Base class for all actions. It defines a constructor an a run main method.
'''
def __init__( self, name, decisionParams, enforcementResult, singlePolicyResults, cl... |
"""
Single page performance tests for LMS.
"""
from bok_choy.web_app_test import WebAppTest, with_cache
from ..pages.lms.auto_auth import AutoAuthPage
from ..pages.lms.courseware import CoursewarePage
from ..pages.lms.dashboard import DashboardPage
from ..pages.lms.course_info import CourseInfoPage
from ..pages.lms.log... |
"""Tests for certbot_apache.obj."""
import unittest
class VirtualHostTest(unittest.TestCase):
"""Test the VirtualHost class."""
def setUp(self):
from certbot_apache.obj import Addr
from certbot_apache.obj import VirtualHost
self.addr1 = Addr.fromstring("127.0.0.1")
self.addr2... |
import unittest
import py3kcompat as py3k
from PySide2.QtCore import QSizeF, QTimer
from PySide2.QtGui import QTextFormat, QTextCharFormat, QPyTextObject
from PySide2.QtWidgets import QTextEdit
from helper import UsesQApplication
class Foo(QPyTextObject):
called = False
def intrinsicSize(self, doc, posInDocu... |
import os
import sys
TEST_CTX = 'rosgraph_msgs'
def get_test_dir():
return os.path.abspath(os.path.join(os.path.dirname(__file__), 'md5tests'))
def get_test_msg_dir():
return os.path.abspath(os.path.join(os.path.dirname(__file__), 'files'))
def get_search_path():
test_dir = get_test_msg_dir()
... |
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import sys
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='See README')
parser.add_argument('-c', '--count', default=3, type=int,
help='with how man... |
"""Tests for SparsemaxLossOp."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.sparsemax import sparsemax, sparsemax_loss
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import arra... |
from pymongo import MongoClient
import logging, Quandl, random, os
import datetime, glob, pandas as pd
from pandas_datareader import data, wb
import numpy as np, sys
from memo import *
MONGO_STAT = "C:\\Progra~1\\MongoDB\\Server\\3.2\\bin\\mongostat.exe /rowcount:1"
@memo # so that we dont constantly read the .quand... |
import io
import sys
import textwrap
from test import support
import traceback
import unittest
class Test_TestResult(unittest.TestCase):
# Note: there are not separate tests for TestResult.wasSuccessful(),
# TestResult.errors, TestResult.failures, TestResult.testsRun or
# TestResult.shouldStop because t... |
from south.db import db
from django.db import models
from frontend.models import *
class Migration:
def forwards(self, orm):
# Adding model 'Message'
db.create_table('frontend_message', (
('id', orm['frontend.message:id']),
('text', orm['frontend.message:text']... |
import re
from .protocols.base import BaseProtocol
from .exceptions import WebSocketError
class WebSocketApplication(object):
protocol_class = BaseProtocol
def __init__(self, ws):
self.protocol = self.protocol_class(self)
self.ws = ws
def handle(self):
self.protocol.on_open()
... |
"""Utilities for extracting common archive formats"""
__all__ = [
"unpack_archive", "unpack_zipfile", "unpack_tarfile", "default_filter",
"UnrecognizedFormat", "extraction_drivers", "unpack_directory",
]
import zipfile, tarfile, os, shutil, posixpath
from pkg_resources import ensure_directory
from distutils.... |
def insort_left(a, x, key=None, lo=0, hi=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted.
:param a: sorted list
:type a: list
:param x: item to insert into the list
:type x: object
:param key: Function to use to compare items in the list
:type key: function
:r... |
"""create orchestration
Revision ID: 2a280aba7701
Revises: 579f359e6e30
Create Date: 2016-04-12 18:25:17.910876
"""
# revision identifiers, used by Alembic.
revision = '2a280aba7701'
down_revision = '579f359e6e30'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class project_configuration(osv.osv_memory):
_name = 'project.config.settings'
_inherit = 'res.config.settings'
_columns = {
'module_project_mrp': fields.boolean('Generate tasks from sale orders',
help='This feat... |
"""RAPI client utilities.
"""
from ganeti import constants
from ganeti import cli
from ganeti.rapi import client
# Local constant to avoid importing ganeti.http
HTTP_NOT_FOUND = 404
class RapiJobPollCb(cli.JobPollCbBase):
def __init__(self, cl):
"""Initializes this class.
@param cl: RAPI client instanc... |
import atexit
import os
import sys
import select
import signal
import shlex
import shutil
import socket
import platform
import tempfile
import time
from subprocess import Popen, PIPE
if sys.version >= '3':
xrange = range
from py4j.java_gateway import java_import, JavaGateway, JavaObject, GatewayParameters
from py... |
import os, sys
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
raise RuntimeErro... |
"""SQL Lexer"""
# This code is based on the SqlLexer in pygments.
# http://pygments.org/
# It's separated from the rest of pygments to increase performance
# and to allow some customizations.
import re
from debug_toolbar.utils.sqlparse import tokens
from debug_toolbar.utils.sqlparse.keywords import KEYWORDS, KEYWORD... |
"""
Helper module for systemd service readiness notification.
"""
import os
import socket
import sys
from designate.openstack.common import log as logging
LOG = logging.getLogger(__name__)
def _abstractify(socket_name):
if socket_name.startswith('@'):
# abstract namespace socket
socket_name = ... |
from .charsetgroupprober import CharSetGroupProber
from .utf8prober import UTF8Prober
from .sjisprober import SJISProber
from .eucjpprober import EUCJPProber
from .gb2312prober import GB2312Prober
from .euckrprober import EUCKRProber
from .cp949prober import CP949Prober
from .big5prober import Big5Prober
from .euctwpro... |
import os
import sys
from setuptools.command import easy_install
from ryu import version
# Global variables in this module doesn't work as we expect
# because, during the setup procedure, this module seems to be
# copied (as a file) and can be loaded multiple times.
# We save them into __main__ module instead.
def _m... |
from django.conf import settings
from django.core.management.base import BaseCommand
from iati.models import Activity
from iati.transaction.models import Transaction
class Command(BaseCommand):
def update_searchable_activities(self):
"""
Set all activities to searchable if the reporting org is i... |
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
''' Fail with custom message '''
TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=dict()):
msg = 'Failed as requested from task'
if self._task.args and 'msg' in self._task.args:
msg = self.... |
"""
Github Enterprise OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/github_enterprise.html
"""
from six.moves.urllib.parse import urljoin
from social.utils import append_slash
from social.backends.github import GithubOAuth2, GithubOrganizationOAuth2, \
GithubTeamOAuth2
class GithubEnter... |
#!/usr/bin/env python
"""Survey PyX12 Segment Definitions.
Read ALL pyx12 message definitions, accumulate all Segment definitions.
"""
from __future__ import print_function
import xml.dom.minidom as DOM
import os, glob
segmentTypes= {}
segmentUse= {}
def getDef( aFile ):
"""Get the Segment Definitions from an XM... |
from collections import UserDict
from datetime import date, datetime
from speaklater import _LazyString
try:
import simplejson as _json
except ImportError:
import json as _json
class IndicoJSONEncoder(_json.JSONEncoder):
"""Custom JSON encoder that supports more types.
* datetime objects
"""
... |
"""
.. dialect:: drizzle+mysqldb
:name: MySQL-Python
:dbapi: mysqldb
:connectstring: drizzle+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
:url: http://sourceforge.net/projects/mysql-python
"""
from sqlalchemy.dialects.drizzle.base import (
DrizzleDialect,
DrizzleExecutionContext,
... |
from optparse import make_option
import os
import re
import sys
import socket
from django.core.management.base import BaseCommand, CommandError
from django.core.handlers.wsgi import WSGIHandler
from django.core.servers.basehttp import AdminMediaHandler, run, WSGIServerException
from django.utils import autoreload
nai... |
# coding: utf-8
import re
from django.core.serializers import SerializerDoesNotExist
from django.conf import settings
from rest_framework.settings import api_settings
from richard.videos.models import Category
from .serializers import CategorySerializer, VideoSerializer
from .utils import force_path
from .exceptions ... |
"""Config Drive v2 helper."""
import os
import shutil
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import strutils
from oslo_utils import units
from nova import exception
from nova.i18n import _LW
from nova.openstack.common import fileutils
from nova import utils
from nova import v... |
# encoding: utf-8
"""
Readbility url shortner api implementation
Located at: https://readability.com/developers/api/shortener
Doesnt' need anything from the app
"""
from .base import BaseShortener
from ..exceptions import ShorteningErrorException, ExpandingErrorException
class ReadabilityShortener(BaseShortener):
... |
import mock
from neutron.agent.l3 import agent as l3_agent
from neutron.agent.linux import dhcp
from neutron.agent.linux import ip_lib
from neutron.cmd import netns_cleanup
from neutron.tests.common import net_helpers
from neutron.tests.functional import base
GET_NAMESPACES = 'neutron.agent.linux.ip_lib.IPWrapper.get... |
from .PollConstants import PollConstants
import select
class PollSelectAdapter(object):
"""
Use select to emulate a poll object, for
systems that don't support poll().
"""
def __init__(self):
self._registered = {}
self._select_args = [[], [], []]
def register(self, fd, *args):
"""
Only POLLIN is curre... |
"""define MapReduce as subclass of Service"""
# -*- python -*-
import os, copy, time
from service import *
from hodlib.Hod.nodePool import *
from hodlib.Common.desc import CommandDesc
from hodlib.Common.util import get_exception_string, parseEquals
class MapReduceExternal(MasterSlave):
"""dummy proxy to external ... |
import os
from Node import Node
from Search import Search
from Data import Data
from Utils import Utils
cities = Data.cities()
situations = Data.cfg()
def Main():
option = 0
option1 = 0
start = None
finisht = None
while True:
os.system('cls')
if(option == 0):
option=0
... |
""" Python training exercise
Random list
Below is a list of random numbers between 0 and 100. Using built-in funcions
and the list sub-functions, can you?:
(a) Sort the list?
HINT: Use the sorted() built-in function.
(b) What are the smallest and largest numbers?
HINT: There are two ways to do t... |
from django.test import TestCase
from django.core.exceptions import FieldError
from models import Author, Article
def pks(objects):
""" Return pks to be able to compare lists"""
return [o.pk for o in objects]
class CustomColumnRegression(TestCase):
def assertRaisesMessage(self, exc, msg, func, *args, **... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from ckeditor.models import HTML5FragmentField
class WikiHTMLField(HTML5FragmentField):
allowed_elements = [
'p', 'br', 'a', 'em', 'strong', 'u', 'img', 'h1', 'h2', 'h3',
'h4', 'h5', 'h6', 'hr', 'ul', 'ol', 'li', 'p... |
"""
test.py contains unit tests for tmdbsimple.py
Fill in Global Variables below before running tests.
Created by Celia Oakley on 2013-11-05
"""
import unittest
import sys
from tmdb_api import TMDB
#
# Global Variables (fill in or put in keys.py)
#
TMDB_API_KEY = 'edc5f123313769de83a71e157758030b'
try:
from k... |
import re
from django.template.defaultfilters import stringfilter
from google.appengine.ext import webapp
register = webapp.template.create_template_register()
bug_regexp = re.compile(r"bug (?P<bug_id>\d+)")
patch_regexp = re.compile(r"patch (?P<patch_id>\d+)")
@register.filter
@stringfilter
def webkit_linkify(val... |
from __future__ import unicode_literals
import uuid
from django.conf import settings
from django.db.backends.base.operations import BaseDatabaseOperations
from django.utils import six, timezone
from django.utils.encoding import force_text
class DatabaseOperations(BaseDatabaseOperations):
compiler_module = "djan... |
import unittest
from unittest.mock import MagicMock, patch
from airflow.providers.amazon.aws.operators.emr_terminate_job_flow import EmrTerminateJobFlowOperator
TERMINATE_SUCCESS_RETURN = {'ResponseMetadata': {'HTTPStatusCode': 200}}
class TestEmrTerminateJobFlowOperator(unittest.TestCase):
def setUp(self):
... |
r'''>>> import pickle2_ext
>>> import pickle
>>> pickle2_ext.world.__module__
'pickle2_ext'
>>> pickle2_ext.world.__safe_for_unpickling__
1
>>> pickle2_ext.world.__name__
'world'
>>> pickle2_ext.world('Hello').__reduce__()
(<class 'pickle2_ext.world'>, ('Hello',), (0,))
>>> for n... |
import stat, os, sys
from twisted.internet import interfaces, reactor, protocol, error, address, defer, utils
from twisted.python import components, lockfile, failure
from twisted.protocols import loopback
from twisted.trial import unittest, assertions
from twisted.trial.util import spinWhile, spinUntil, wait
class ... |
"""Backport of importlib.import_module from 3.x."""
# While not critical (and in no way guaranteed!), it would be nice to keep this
# code compatible with Python 2.3.
import sys
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, ... |
"""Various utility functions."""
__unittest = True
_MAX_LENGTH = 80
def safe_repr(obj, short=False):
try:
result = repr(obj)
except Exception:
result = object.__repr__(obj)
if not short or len(result) < _MAX_LENGTH:
return result
return result[:_MAX_LENGTH] + ' [truncated]...'... |
from pytest import raises
from imageio.testing import run_tests_if_main, get_test_dir
import os
import gc
import shutil
import numpy as np
import imageio
from imageio.core import Format, FormatManager, Request
from imageio.core import get_remote_file
test_dir = get_test_dir()
def setup_module():
imageio.form... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import types
class seq_with_cursor (object):
__slots__ = [ 'items', 'index' ]
def __init__ (self, items, initial_index = None, initial_value = None):
assert len (items) > 0, "seq_with_curso... |
"""
This module implements a class for handling URLs.
"""
from six.moves.urllib.parse import quote, unquote, urlencode
import cgi
from paste import request
import six
# Imported lazily from FormEncode:
variabledecode = None
__all__ = ["URL", "Image"]
def html_quote(v):
if v is None:
return ''
return ... |
from p2pool.util import math, pack
def reads_nothing(f):
return None, f
def protoPUSH(length):
return lambda f: pack.read(f, length)
def protoPUSHDATA(size_len):
def _(f):
length_str, f = pack.read(f, size_len)
length = math.string_to_natural(length_str[::-1].lstrip(chr(0)))
data, f... |
from django.core.exceptions import ImproperlyConfigured
from django.core.management import call_command, CommandError
from django.core.management.base import BaseCommand
from django.conf import settings
from django.db.models import loading
from django.test import simple
from south.migration import Migrations
from sout... |
from gpu_test_expectations import GpuTestExpectations
# See the GpuTestExpectations class for documentation.
class WebGLConformanceExpectations(GpuTestExpectations):
def SetExpectations(self):
# Fails on all platforms
self.Fail('conformance/glsl/misc/shaders-with-invariance.html',
bug=421710)
se... |
# imports and basic notebook setup
from cStringIO import StringIO
import numpy as np
import scipy.ndimage as nd
import PIL.Image
# from IPython.display import clear_output, Image, display
from google.protobuf import text_format
import caffe
import cbaas
try:
caffe.set_gpu_mode()
except:
print "CPU mode
caffe_roo... |
__all__ = [
'LXMLTreeBuilderForXML',
'LXMLTreeBuilder',
]
from StringIO import StringIO
import collections
from lxml import etree
from bs4.element import Comment, Doctype, NamespacedAttribute
from bs4.builder import (
FAST,
HTML,
HTMLTreeBuilder,
PERMISSIVE,
TreeBuilder,
XML)
from b... |
"""some generic utilities for dealing with classes, urls, and serialization
Authors:
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the ... |
import re
DEFAULT_COMMENT = 'configured by junos_config'
def diff_config(candidate, config):
updates = set()
for line in candidate:
parts = line.split()
action = parts[0]
cfgline = ' '.join(parts[1:])
if action not in ['set', 'delete']:
module.fail_json(msg='line... |
"""
Copyright (c) 2008-2015, Jesus Cea Avion <<EMAIL>>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of cond... |
import yaml
import pyshark
import time
import os
import re
import pyshark
from robot.api import logger
from robot.libraries.BuiltIn import BuiltIn
from collections import OrderedDict
from sip_message_validation import SipMessageValida... |
import unittest
from unittest import skipUnless
from django.contrib.gis.geos import (
HAS_GEOS, LinearRing, LineString, MultiPoint, Point, Polygon, fromstr,
)
def api_get_distance(x):
return x.distance(Point(-200, -200))
def api_get_buffer(x):
return x.buffer(10)
def api_get_geom_typeid(x):
retur... |
"""
Show module information for a given database or from the file-system.
"""
import os
import sys
import textwrap
from . import common
# TODO provide a --rpc flag to use XML-RPC (with a specific username) instead
# of server-side library.
def run(args):
assert args.database
import openerp
config = opene... |
#!/usr/bin/python
import numpy
# based on the vicar2png module by Jessica McKellar (jesstess at mit.edu)
# substantial modifications have been made to the code. However for
# thoroughness, I am including her Copyright under the MIT License below:
'''
The MIT License (MIT)
Copyright (c) 2012-2013 Jessica McKellar
... |
from mpl_toolkits.axes_grid1 import make_axes_locatable
from mpl_toolkits.axes_grid1.axes_divider import make_axes_area_auto_adjustable
if __name__ == "__main__":
import matplotlib.pyplot as plt
def ex1():
plt.figure(1)
ax = plt.axes([0,0,1,1])
# ax = plt.subplot(111)
ax... |
#! /usr/bin/env python
# Hi There!
# You may be wondering what this giant blob of binary data here is, you might
# even be worried that we're up to something nefarious (good for you for being
# paranoid!). This is a base64 encoding of a zip file, this zip file contains
# a fully functional basic pytest script.
#
# Pyt... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
import json
from ansible.errors import AnsibleConnectionFailure
from ansible.module_utils._text import to_text, to_bytes
from ansible.plugins.terminal import TerminalBase
class TerminalModule(TerminalBase):
termin... |
# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
import scrapy
import functools
import requests
def _link_is_http(l):
return l.startswith('https://') or l.startswith('http://')
def _link_is_archive(l):
... |
ADS_ATTR_CLEAR = ( 1 )
ADS_ATTR_UPDATE = ( 2 )
ADS_ATTR_APPEND = ( 3 )
ADS_ATTR_DELETE = ( 4 )
ADS_EXT_MINEXTDISPID = ( 1 )
ADS_EXT_MAXEXTDISPID = ( 16777215 )
ADS_EXT_INITCREDENTIALS = ( 1 )
ADS_EXT_INITIALIZE_COMPLETE = ( 2 )
ADS_SEARCHPREF_ASYNCHRONOUS = 0
ADS_SEARCHPREF_DEREF_ALIASES = 1
ADS_SEARCHPREF_SIZE... |
import hashlib
import json
import subprocess
import traceback
from tempfile import NamedTemporaryFile
import httplib2
from celery.canvas import chain
from django.conf import settings
from google.cloud import storage
from google.cloud.exceptions import Forbidden, NotFound
from google.cloud.storage import Blob
from goog... |
"""
My own variation on function-specific inspect-like features.
"""
# Copyright (c) 2009 Gael Varoquaux
# License: BSD Style, 3 clauses.
from itertools import islice
import inspect
import warnings
import re
import os
from ._compat import _basestring
from .logger import pformat
from ._memory_helpers import open_py_s... |
from django import forms
from openflow.optin_manager.flowspace.utils import dotted_ip_to_int, mac_to_int
from django.forms.util import ErrorList
import re
from openflow.optin_manager.opts.models import AdminFlowSpace
class MACAddressForm(forms.Field):
def clean(self, value):
pattern = re.compile(r"^([0... |
"""empty message
Revision ID: 4517f9cbe1f9
Revises: 42ef4a834d23
Create Date: 2016-04-13 22:34:37.727821
"""
# revision identifiers, used by Alembic.
revision = '4517f9cbe1f9'
down_revision = '42ef4a834d23'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - ... |
from enum import Enum
class Relaytype(Enum):
net_tcp = "NetTcp"
http = "Http"
class SkuTier(Enum):
standard = "Standard"
class ProvisioningStateEnum(Enum):
created = "Created"
succeeded = "Succeeded"
deleted = "Deleted"
failed = "Failed"
updating = "Updating"
unknown = "Unkn... |
"""
Syndication feed generation library -- used for generating RSS, etc.
Sample usage:
>>> from django.utils import feedgenerator
>>> feed = feedgenerator.Rss201rev2Feed(
... title="Poynter E-Media Tidbits",
... link="http://www.poynter.org/column.asp?id=31",
... description="A group Weblog by the sharpes... |
from starcluster import completion
from starcluster.logger import log
from base import CmdBase
class Completer(CmdBase):
"""
Base class for all completer classes
"""
@property
def completer(self):
return self._completer()
class ClusterCompleter(Completer):
"""
Returns a list of... |
import urlparse
from abc import ABCMeta, abstractmethod, abstractproperty
item_types = ["testharness", "reftest", "manual", "stub", "wdspec"]
def get_source_file(source_files, tests_root, manifest, path):
def make_new():
from sourcefile import SourceFile
return SourceFile(tests_root, path, manife... |
"""
Module that tracks analytics events by sending them to different
configurable backends.
The backends can be configured using Django settings as the example
below::
TRACKING_BACKENDS = {
'tracker_name': {
'ENGINE': 'class.name.for.backend',
'OPTIONS': {
'host': ... ,
... |
"""
Test lldb command aliases.
"""
from __future__ import print_function
import unittest2
import os
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class LaunchInTerminalTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
... |
import unittest
from webkitpy.common.checkout.commitinfo import CommitInfo
from webkitpy.common.config.committers import CommitterList, Committer, Reviewer
class CommitInfoTest(unittest.TestCase):
def test_commit_info_creation(self):
author = Committer("Author", "<EMAIL>")
committer = Committer("... |
EVENTS = {}
def make_name(FROM):
USERNAME = FROM.get('username', '')
FIRST = FROM.get('first_name', '')
LAST = FROM.get('last_name', '')
NAME = ' '.join(t for t in [FIRST, LAST] if t)
if NAME and USERNAME:
return '%s [@%s]' % (NAME, USERNAME)
elif USERNAME:
return '@%s' % USERNAME
elif NAME:
r... |
from django.db import models
from django.urls import NoReverseMatch
from olympia import activity, amo
from olympia.amo.fields import PositiveAutoField
from olympia.amo.models import ManagerBase, ModelBase
from olympia.amo.urlresolvers import reverse
class TagManager(ManagerBase):
def not_denied(self):
"... |
from wedo2.bluetooth import bluetooth_helper
from wedo2.bluetooth.connect_info import ConnectInfo
from wedo2.services.lego_service_factory import LegoServiceFactory
HUB_CHARACTERISTIC_ATTACHED_IO = "0x1527"
class ServiceManager:
def __init__(self, io):
self.io = io
self.services = set()
... |
"""
CONTEXT structure for i386.
"""
__revision__ = "$Id$"
from winappdbg.win32.defines import *
from winappdbg.win32.version import ARCH_I386
#==============================================================================
# This is used later on to calculate the list of exported symbols.
_all = None
_all = set(vars(... |
from app.config.cplog import CPLog
from app.lib.provider.yarr.base import torrentBase
from imdb.parser.http.bsouplxml._bsoup import SoupStrainer, BeautifulSoup
from urllib import quote_plus
from urllib2 import URLError
import time
import urllib
import urllib2
log = CPLog(__name__)
class x264(torrentBase):
"""Prov... |
"""
***************************************************************************
ProcessingWorkflowPlugin.py
-------------------------------------
Copyright (C) 2014 TIGER-NET (www.tiger-net.org)
***************************************************************************
* This plugin is part of the Water Observ... |
''' Provide a collection of general utilities useful for implementing Bokeh
functionality.
.. _bokeh.util.browser:
``bokeh.util.browser``
----------------------
.. automodule:: bokeh.util.browser
:members:
.. _bokeh.util.callback_manager:
``bokeh.util.callback_manager``
-------------------------------
.. automo... |
import constants
# 255: Control characters that usually does not exist in any text
# 254: Carriage/Return
# 253: symbol (punctuation) that does not belong to word
# 252: 0 - 9
# Character Mapping Table:
# this table is modified base on win1251BulgarianCharToOrderMap, so
# only number <64 is sure valid
Latin5_Bulgar... |
from django.test import TestCase
class MetadataXSLTest(TestCase):
"""
Tests geonode.contrib.metadataxsl app/module
"""
def setUp(self):
self.adm_un = "admin"
self.adm_pw = "admin"
# create_models(type="layer") |
import time
import datetime
try:
import boto.ec2
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# Find the most recent snapshot
def _get_snapshot_starttime(snap):
return datetime.datetime.strptime(snap.start_time, '%Y-%m-%dT%H:%M:%S.000Z')
def _get_most_recent_snapshot(snapshots, max_snapshot... |
from datetime import date
from django.test.utils import override_settings
from .base import SitemapTestsBase
class HTTPSSitemapTests(SitemapTestsBase):
protocol = 'https'
urls = 'django.contrib.sitemaps.tests.urls.https'
def test_secure_sitemap_index(self):
"A secure sitemap index can be rendere... |
#!/usr/bin/env python
'''
ansible module for zabbix triggerprototypes
'''
# vim: expandtab:tabstop=4:shiftwidth=4
#
# Zabbix triggerprototypes ansible module
#
#
# Copyright 2015 Red Hat Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wit... |
from datetime import date
from dateutil.relativedelta import relativedelta
from openerp import fields
from openerp.exceptions import ValidationError
from .test_partner_relation_common import TestPartnerRelationCommon
class TestPartnerRelation(TestPartnerRelationCommon):
def test_selection_name_search(self):
... |
from measurements import timeline_controller
from metrics import timeline
from telemetry.core.platform import tracing_category_filter
from telemetry.page import page_test
class ThreadTimes(page_test.PageTest):
def __init__(self):
super(ThreadTimes, self).__init__('RunSmoothness')
self._timeline_controller = ... |
from __future__ import unicode_literals
import datetime
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.test import TestCase
from django.test.utils import override_settings
from ..models import Article, Author, UrlArticle
@override_settings(ROOT_URLCONF='view_te... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.