content stringlengths 4 20k |
|---|
#!/usr/bin/env ipython3
##
# @file
# calculate surface mass density falloff of circular rings around center of mass
# calculate velocity dispersion of 2D rings from an observed dwarf dataset
# calculate 4th order velocity moment (kurtosis) of 2D rings
# do this consistently with always the same sets of particles per b... |
'''Unit tests for grit.tool.rc2grd'''
import os
import sys
if __name__ == '__main__':
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
import re
import StringIO
import unittest
from grit.node import base
from grit.tool import rc2grd
from grit.gather import rc
from grit import grd_reader
class... |
"""
This config file runs the simplest dev environment using sqlite, and db-based
sessions. Assumes structure:
/envroot/
/db # This is where it'll write the database file
/edx-platform # The location of this repo
/log # Where we're going to write log files
"""
# We intentionally define lot... |
import requests
from unittest import SkipTest
from ....tests.base import NBViewerTestCase, FormatHTMLMixin
class GitHubTestCase(NBViewerTestCase):
def ipython_example(self, *parts, **kwargs):
ref = kwargs.get('ref', 'rel-2.0.0')
return self.url('github/ipython/ipython/blob/%s/examples' % ref, *pa... |
import pyfits,scipy
import sys,os
import wcs
from scipy import stats,ndimage
def make_fringe(frames,bias,flat):
#
# Define the good area of the chip. Only read in rows and columns
# defined by x and y below
#
y = slice(150,1950,1)
x = slice(150,2020,1)
#
# Define an area of the chi... |
import argparse
import random
def main(nvertices):
vertices = [(random.random(), random.random(), ) for _ in range(nvertices)]
print(len(vertices))
for x, y in vertices:
print(x, y)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--nvertices', '-v', ty... |
from polyphony import testbench
from polyphony import unroll
from polyphony.typing import List
def shift_full(xs:list, x):
for j in unroll(range(len(xs) - 1)):
jj = (len(xs) - 1) - j
xs[jj] = xs[jj - 1]
xs[0] = x
def shift_2(xs:list, x):
for j in unroll(range(len(xs) - 1), 2):
jj... |
from uuid import uuid4
from django.utils.html import escape
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.django import modulestore
from licenses.models import CourseSoftware, UserLicense
from opaque_keys.edx.locations import SlashSeparatedCourseKey
class Command(BaseCo... |
import subprocess, sys
BUILD_MSBUILD_LIBS = False
VCVARSALL_PATH = '"C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\vcvarsall.bat"'
MSBUILD_PATH = '"C:\\program files (x86)\\msbuild\\14.0\\bin\\msbuild.exe"'
THIRDPARTY_PATH = '..\\3rdparty\\'
LIBJPEG_PROJ = '..\\3rdparty\\libjpeg\\build\\libjpegWin10\\lib... |
import ansible
from ansible import utils
from ansible.runner.return_data import ReturnData
class ActionModule(object):
''' Fail with custom message '''
TRANSFERS_FILES = False
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, module_name, module_args, inject, complex... |
from datetime import datetime
import actstream.actions
import django_filters
import json
from django.db.models import Q
from rest_framework import serializers, viewsets, permissions, filters, status
from rest_framework.decorators import action
from rest_framework.response import Response
from taggit.models import Tag
... |
import random
from data import MOVE_CORRECTIONS, NAME_CORRECTIONS, load_data, correct_name, correct_move
from data import correct_mega
class MovePredictor(object):
def __init__(self, poke, pokedata):
self.pokedata = pokedata
self.poke = poke
def get_moves(self, poke, known_moves):
rais... |
import unittest2
class TestConnection(unittest2.TestCase):
def _getTargetClass(self):
from gcloud.storage.connection import Connection
return Connection
def _makeOne(self, *args, **kw):
return self._getTargetClass()(*args, **kw)
def test_build_api_url_no_extra_query_params(self)... |
from tables import openFile
from pylab import imshow, axis, show, cm
from numpy import histogram, nonzero, zeros, linspace
def readH5file(filename):
"""
Reads data from an H5 file.
Syntax:
data = readH5file(filename)
where filename is the name of the H5 file and data is a vector of
dictionaries that stores t... |
"""
A simple tutorial that shows some features of the Temporal Memory.
The following program has the purpose of presenting some
basic properties of the Temporal Memory, in particular when it comes
to how it handles high-order sequences.
"""
import numpy as np
import random
import matplotlib
matplotlib.use('Agg')
impo... |
#!/usr/bin/env python3
# −*− coding: UTF−8 −*−
import sys
from argparse import ArgumentParser
class dhondt():
"""Class to calculate d'Hondt statistics
:Authors: Pedro Ferrer, Silvia Fuentes
:Date: 2015-07-20
:version: 1.1
The minimum data to be providen is:
+ The number of seats [nseats]
... |
"""
Steps specific to the rpm format.
"""
from buildbot.steps.package.rpm.mock import MockBuildSRPM
from buildbot.steps.package.rpm.mock import MockRebuild
from buildbot.steps.package.rpm.rpmbuild import RpmBuild
from buildbot.steps.package.rpm.rpmlint import RpmLint
__all__ = ['RpmBuild', 'RpmLint', 'MockBuildSRPM',... |
import debian, re, textwrap
class SortedDict(dict):
__slots__ = '_list',
def __init__(self, entries = None):
super(SortedDict, self).__init__()
self._list = []
if entries is not None:
for key, value in entries:
self[key] = value
def __delitem__(self, ke... |
from ctypes import byref, c_int
from datetime import date, datetime, time
from django.contrib.gis.gdal.base import GDALBase
from django.contrib.gis.gdal.error import OGRException
from django.contrib.gis.gdal.prototypes import ds as capi
from django.utils.encoding import force_text
# For more information, see the OGR ... |
from collections import OrderedDict
from django import forms
from django.core.exceptions import PermissionDenied
from django.db import router
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from django.template.response import TemplateResponse
from django.utils.encoding imp... |
from b2ginstance import B2GInstance
import datetime
from errors import *
from mozdevice import devicemanagerADB, DMError
from mozprocess import ProcessHandlerMixin
import os
import re
import platform
import shutil
import socket
import subprocess
import sys
from telnetlib import Telnet
import tempfile
import time
import... |
from synthicity.urbansim import interaction, mnl
import numpy as np, pandas as pd
import time
GPU = 0
EMTOL = 1e-02
MAXITER = 10000
def prep_cm_data(cmdata,numclasses):
numobs, numvars = cmdata.shape
newcmdata = np.zeros((numobs*numclasses,numvars*(numclasses-1)))
for i in range(cmdata.shape[0]):
for j in ... |
"""Administrator interface to score_mgr."""
from django.contrib import admin
from apps.managers.challenge_mgr import challenge_mgr
from apps.widgets.participation.models import ParticipationSetting, TeamParticipation
from apps.admin.admin import challenge_designer_site, challenge_manager_site, developer_site
class Pa... |
# coding=utf-8
"""
Fetches arguments from optparse-based Django (< 1.8)
"""
__author__ = 'Ilya.Kazakevich'
from django_manage_commands_provider._parser import _utils
# noinspection PyUnusedLocal
# Parser here by contract
def process_command(dumper, command, parser):
"""
Fetches arguments and options from comm... |
"""
General helpers for L{twisted.web} unit tests.
"""
from twisted.internet.defer import succeed
from twisted.web import server
from twisted.trial.unittest import TestCase
from twisted.python.failure import Failure
from twisted.web._flatten import flattenString
from twisted.web.error import FlattenerError
def _rend... |
from test import test_support
import unittest
import dummy_threading as _threading
import time
class DummyThreadingTestCase(unittest.TestCase):
class TestThread(_threading.Thread):
def run(self):
global running
global sema
global mutex
# Uncomment if testin... |
# This module re-creates the RNG interface from Numeric
# Replace import RNG with import numpy.oldnumeric.rng as RNG
#
# It is for backwards compatibility only.
__all__ = ['CreateGenerator','ExponentialDistribution','LogNormalDistribution',
'NormalDistribution', 'UniformDistribution', 'error', 'ranf',
... |
"""
Plot dialog.
@author: Chris Scott
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import sys
import traceback
import logging
from PySide2 import QtGui, QtCore, QtWidgets
import matplotlib
from six.moves import zip
matplotlib.use("Qt5Agg")
from matplotlib.backends.backend_qt5ag... |
from rtorrent.compat import xmlrpclib
HTTPServerProxy = xmlrpclib.ServerProxy |
"""
Tracks devices by sending a ICMP echo request (ping).
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.ping/
"""
import logging
import subprocess
import sys
from datetime import timedelta
import voluptuous as vol
import homeassistant.h... |
from spack import *
class Systemtap(AutotoolsPackage):
"""SystemTap provides free software (GPL) infrastructure to
simplify the gathering of information about the running
Linux system. This assists diagnosis of a performance or
functional problem. SystemTap eliminates the need for the
developer to... |
import abc
from oslo_config import cfg
from oslo_db import api as db_api
from cloudkitty.i18n import _
_BACKEND_MAPPING = {
'sqlalchemy': 'cloudkitty.rating.pyscripts.db.sqlalchemy.api'}
IMPL = db_api.DBAPI.from_config(cfg.CONF,
backend_mapping=_BACKEND_MAPPING,
... |
from __future__ import unicode_literals
from .common import InfoExtractor
from .ooyala import OoyalaIE
from ..utils import ExtractorError
class ViceIE(InfoExtractor):
_VALID_URL = r'https?://(?:.+?\.)?vice\.com/(?:[^/]+/)+(?P<id>.+)'
_TESTS = [
{
'url': 'http://www.vice.com/Fringes/cowbo... |
from __future__ import unicode_literals
import frappe
from frappe.utils import nowdate, cstr, flt, now, getdate, add_months
from frappe import throw, _
from frappe.utils import formatdate
import frappe.desk.reportview
class FiscalYearError(frappe.ValidationError): pass
class BudgetError(frappe.ValidationError): pass
... |
"""Runs Browsermark CSS, DOM, WebGL, JS, resize and page load benchmarks.
Browsermark benchmark suite have five test groups:
a) CSS group: measures your browsers 2D and 3D performance, and finally executes
CSS Crunch test
b) DOM group: measures variety of areas, like how well your browser traverse in
Document Obje... |
"""
Support for Frontier Silicon Devices (Medion, Hama, Auna,...).
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/media_player.frontier_silicon/
"""
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
SUPPORT... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon.utils import memoized
from openstack_dashboard import api
from openstack_dashboard.dashboards.admin.networks.agents \
import forms as project_... |
from __future__ import absolute_import, division, print_function, unicode_literals
from future.utils import binary_type, text_type
from pants.engine.addressable import addressable, addressable_list
from pants.engine.objects import Serializable, SerializableFactory, Validatable, ValidationError
from pants.util.collect... |
import smtplib
import time
from pell.assistant.text_to_speech import talk, listen
import sys
import os
class EmailAction:
def __init__(self, command, subject=None, message=None, receiver=None):
self.command = command
self.subject = subject
self.message = message
self.receiver = re... |
"""Pin select client library functions. Find implementation details in LPC17xx
CMSIS-Compliant Standard Peripheral Firmware Driver Library documentation.
"""
from internals import robocaller, cstruct
__author__ = "Neil MacMunn"
__credits__ = ["Neil MacMunn", "NXP MCU SW Application Team"]
__maintainer__ = ... |
"""Miscellaneous utility functions and classes.
This module is used internally by Tornado. It is not necessarily expected
that the functions and classes defined here will be useful to other
applications, but they are documented here in case they are.
The one public-facing part of this module is the `Configurable` cl... |
"""TLS Lite + SocketServer."""
from gdata.tlslite.TLSConnection import TLSConnection
class TLSSocketServerMixIn:
"""
This class can be mixed in with any L{SocketServer.TCPServer} to
add TLS support.
To use this class, define a new class that inherits from it and
some L{SocketServer.TCPServer} (wi... |
import sys
import os
import gc
import threading
import numpy as np
from numpy.testing import assert_equal, assert_, assert_allclose
from scipy.sparse import (_sparsetools, coo_matrix, csr_matrix, csc_matrix,
bsr_matrix, dia_matrix)
from scipy.sparse.sputils import supported_dtypes, matrix
fro... |
from include import *
from math import sqrt
def get_significance(mean_1, mean_2, std_1, std_2, n):
significance = ""
ste_1 = std_1 / sqrt(n)
ste_2 = std_2 / sqrt(n)
t = (mean_1 - mean_2) / sqrt(ste_1 ** 2 + ste_2 ** 2)
#print t
if mean_1 > mean_2: # treatment is worse than baseline
# ... |
from jinja2 import Markup
from flask_admin._compat import string_types
from flask_admin import helpers
class BaseRule(object):
"""
Base form rule. All form formatting rules should derive from `BaseRule`.
"""
def __init__(self):
self.parent = None
self.rule_set = None
def conf... |
from grpc._cython import cygrpc
def _call(call_credentialses):
call_credentials_iterator = iter(call_credentialses)
composition = next(call_credentials_iterator)
for additional_call_credentials in call_credentials_iterator:
composition = cygrpc.call_credentials_composite(
composition, additional_cal... |
"""provides the Lexer class for parsing template strings into parse trees."""
import re, codecs
from mako import parsetree, exceptions, util
from mako.pygen import adjust_whitespace
_regexp_cache = {}
class Lexer(object):
def __init__(self, text, filename=None,
disable_unicode=False,
... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
__init__.py
---------------------
Date : January 2016
Copyright : (C) 2016 by Victor Olaya
Email : volayaf at gmail dot com
*****************************... |
import espressomd
import unittest as ut
import numpy as np
from espressomd.electrostatics import EwaldGpu
class ewald_GPU_test(ut.TestCase):
es=espressomd.System()
test_params={}
test_params["bjerrum_length"]=2
test_params["num_kx"]=2
test_params["num_ky"]=2
test_params["num_kz"]=2
test_par... |
from __future__ import absolute_import, division, print_function, unicode_literals
from botocore.exceptions import ClientError
from c7n.actions import Action, ActionRegistry
from .common import BaseTest
class ActionTest(BaseTest):
def test_process_unimplemented(self):
self.assertRaises(NotImplementedErr... |
"""
tests for the models
"""
import ddt
import json
from datetime import datetime, timedelta
from nose.plugins.attrib import attr
from pytz import utc
from student.roles import CourseCcxCoachRole
from student.tests.factories import (
AdminFactory,
)
from xmodule.modulestore.tests.django_utils import (
ModuleSto... |
""" Handlers for OpenID Connect provider. """
from django.conf import settings
from django.core.cache import cache
from courseware.access import has_access
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
from openedx.core.djangoapps.user_api.models import UserPreference
from student... |
import re
import inspect
import textwrap
import pydoc
import sphinx
from docscrape import NumpyDocString, FunctionDoc, ClassDoc
class SphinxDocString(NumpyDocString):
def __init__(self, docstring, config={}):
self.use_plots = config.get('use_plots', False)
NumpyDocString.__init__(self, docstring, ... |
from tests import TestCase
from io import BytesIO
from quodlibet.util.picklehelper import pickle_load, pickle_loads, \
pickle_dumps, pickle_dump, PicklingError, UnpicklingError
class A(dict):
pass
class B(dict):
pass
class Tpickle_load(TestCase):
def test_pickle_load(self):
data = {b"foo... |
"""Command for listing target SSL proxies."""
from apitools.base.py import list_pager
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.calliope import base
from googlecloudsdk.core import log
from googlecloudsdk.core import properties
from googlecloudsdk.core import resources
class List(ba... |
"""
A poll() based implementation of the twisted main loop.
To install the event loop (and you should do this before any connections,
listeners or connectors are added)::
from twisted.internet import pollreactor
pollreactor.install()
"""
from __future__ import division, absolute_import
# System imports
impo... |
import datetime
import sentiment_analysis
import GunningFog
# sources come in a list, type is a single variable, topic is the tags, category is business, etc.
#def time(sources, topic, types, category, information):
# 'start' time to base bin separation on
# now = datetime.datetime.now()
# bins = {}
# count = 0
# se... |
from __future__ import print_function, division
from sympy import Basic, Q
from sympy.functions import adjoint, conjugate
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices import MatrixBase
class Transpose(MatrixExpr):
"""
The transpose of a matrix expression.
This is a symbo... |
from oslo_config import cfg
import requests
from requests import exceptions
import six
from heat.common import urlfetch
from heat.tests import common
class Response(object):
def __init__(self, buf=''):
self.buf = buf
def iter_content(self, chunk_size=1):
while self.buf:
yield sel... |
# -*- coding: utf-8 -*-
"""
pygments.style
~~~~~~~~~~~~~~
Basic style object.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.token import Token, STANDARD_TYPES
class StyleMeta(type):
def __new__(mcs, name, bases,... |
"""
Testing for the base module (sklearn.ensemble.base).
"""
# Authors: Gilles Louppe
# License: BSD 3 clause
from numpy.testing import assert_equal
from nose.tools import assert_true
from sklearn.utils.testing import assert_raise_message
from sklearn.datasets import load_iris
from sklearn.ensemble import BaggingCla... |
import six
from webob import exc
from nova.api.openstack import common
from nova.api.openstack.compute.schemas import image_metadata
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.api import validation
from nova import exception
from nova.i18n import _
import nova.image
ALIAS ... |
#!/usr/bin/python -u
# -*- coding: ISO-8859-1 -*-
import sys
import libxml2
# Memory debug specific
libxml2.debugMemory(1)
ctxt = None
class callback:
def __init__(self, startd, starte, ende, delta, endd):
self.startd = startd
self.starte = starte
self.ende = ende
self.endd = endd... |
import os
import numpy as np
from matplotlib import pylab
from mpl_toolkits.mplot3d import Axes3D
from sklearn import linear_model, manifold, decomposition, datasets
logistic = linear_model.LogisticRegression()
from utils import CHART_DIR
np.random.seed(3)
# all examples will have three classes in this file
colors... |
"""Sparsemax op."""
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 array_ops
from tensorflow.python.ops import math_ops
from tensor... |
import urllib, urllib2
import json
import re
import socket
import xbmc
import xbmcgui
import XbmcHelpers
common = XbmcHelpers
from videohosts import tools
socket.setdefaulttimeout(120)
QUALITY_TYPES = ("1.LQ", "2.HQ")
PLAYLIST_DOMAIN = "vidozzz.com"
HEADERS = {
"Host": PLAYLIST_DOMAIN,
"Referer": "http://yoh... |
#!/usr/bin/env python
'''
generate a MAVLink test suite
Copyright Andrew Tridgell 2011
Released under GNU GPL version 3 or later
'''
import sys, textwrap
from optparse import OptionParser
import mavparse
def gen_value(f, i, language):
'''generate a test value for the ith field of a message'''
t... |
from __future__ import absolute_import, unicode_literals
from django.test import TestCase
from .models import A, B, C, D, DataPoint, RelatedPoint
class SimpleTest(TestCase):
def setUp(self):
self.a1 = A.objects.create()
self.a2 = A.objects.create()
for x in range(20):
B.objec... |
import logging
from models import Image
from models import Status
MIGRATIONS = {}
def register(migration):
""" Register a migratin with the runner """
MIGRATIONS[migration.__name__] = migration
def find(migration_name):
""" Return the migration for a given class name
If no migration found, returns... |
from setuptools import setup, find_packages
from hueversion import VERSION
setup(
name = "metastore",
version = VERSION,
author = "Hue",
url = 'http://github.com/cloudera/hue',
description = "Metastore browser",
packages = find_packages('src'),
package_dir = {'': 'src'},
... |
class ModuleDocFragment(object):
# inventory cache
DOCUMENTATION = """
options:
aws_profile:
description: The AWS profile
aliases: ['boto_profile']
env:
- name: AWS_PROFILE
- name: AWS_DEFAULT_PROFILE
aws_access_key:
description: The AWS access key to use.
env:
- name:... |
# 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 model 'StoreImage'
db.create_table('stores_storeimage', (
('id', self.gf('django.db.m... |
"""
Make sure binary is relinked when manifest settings are changed.
"""
import TestGyp
import os
import sys
if sys.platform == 'win32':
import pywintypes
import win32api
import winerror
RT_MANIFEST = 24
class LoadLibrary(object):
"""Context manager for loading and releasing binaries in Windows.
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
#!/usr/bin/env python
import sys
import getpass
import os
import shutil
import time
import tempfile
from binascii import unhexlify
from binascii import hexlify
from nose.plugins.skip import SkipTest
from ansible.compat.tests impor... |
"""Tests for CandidateSamplerOp."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tenso... |
from blur.Stone import *
from blur.Classes import *
from blur.Burner import *
from PyQt4.QtCore import *
from PyQt4.QtSql import *
import re, traceback
class RealFlowBurner(JobBurner):
def __init__(self,job,slave):
JobBurner.__init__(self,job,slave)
self.Job = job
self.Slave = slave
self.RenderStarted = False... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
js_to_json,
smuggle_url,
)
class CBCIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?cbc\.ca/(?!player/)(?:[^/]+/)+(?P<id>[^/?#]+)'
_TESTS = [{
# with mediaId
... |
from matplotlib.path import Path
from matplotlib.patches import PathPatch
'''Module to control of the visualisation of beamline, beamrep and ...'''
from matplotlib.patches import Rectangle
import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate
class Visualize(object) :
def __init__(sel... |
import dns.exception
import dns.inet
import dns.rdata
import dns.tokenizer
class AAAA(dns.rdata.Rdata):
"""AAAA record.
@ivar address: an IPv6 address
@type address: string (in the standard IPv6 format)"""
__slots__ = ['address']
def __init__(self, rdclass, rdtype, address):
super(AAAA, ... |
import unittest
from nagare import database, i18n, security, component
from nagare.namespaces import xhtml5
from sqlalchemy import MetaData
from kansha.board import comp as board_module
from kansha.board import boardsmanager
from . import helpers
from kansha.security import Unauthorized
from elixir import metadata as _... |
def test_includepath_to_dict():
from genmsg.command_line import includepath_to_dict
assert {} == includepath_to_dict([])
assert {'std_msgs': [ 'foo' ]} == includepath_to_dict(['std_msgs:foo'])
assert {'std_msgs': [ 'foo' ], 'bar_msgs': [ 'baz:colon' ]} == includepath_to_dict(['std_msgs:foo', 'bar_msgs:b... |
"""List field tests
$Id: test_listfield.py 69144 2006-07-16 15:10:16Z jim $
"""
from unittest import main, makeSuite
from zope.interface import implements
from zope.schema import Field, List, Int
from zope.schema.interfaces import IField
from zope.schema.interfaces import ICollection, ISequence, IList
from zope.schem... |
"""
The base class for all the handler plugins
"""
class BaseHandler(object):
""" Base handler class"""
def __init__(self, config_dir, target, logger_instance=None, verbose=True):
"""
BaseHandler Constructor
"""
pass
def authenticate(self):
"""
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from munch import unmunchify
HAS_MUNCH = True
except ImportError:
HAS_MUNC... |
class BinHeap:
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def percUp(self,i):
while i // 2 > 0:
if self.heapList[i] < self.heapList[i // 2]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heap... |
"""Cache lines from files.
This is intended to read lines from modules imported -- hence if a filename
is not found, it will look down the module search path for a file by
that name.
"""
import sys
import os
__all__ = ["getline", "clearcache", "checkcache"]
def getline(filename, lineno, module_globals=None):
li... |
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_of_struct,
ovirt_full_argument_spec,
)
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
... |
"""
This module contains the following classes:
* :class:`~aeneas.diagnostics.Diagnostics`,
checking whether the setup of ``aeneas`` was successful.
This module can be executed from command line with::
python -m aeneas.diagnostics
.. versionadded:: 1.4.1
"""
from __future__ import absolute_import
from __futu... |
import json
import html5lib
def parse(path="html5ents.xml"):
return html5lib.parse(open(path), treebuilder="lxml")
def entity_table(tree):
return dict((entity_name("".join(tr[0].xpath(".//text()"))),
entity_characters(tr[1].text))
for tr in tree.xpath("//h:tbody/h:tr",
... |
import json
class Hive(dict):
def __init__(self, rpc):
dict.__init__(self)
self['root'] = 'http://{hostname}:{port}'
self['objects'] = {}
self['endpoints'] = {'SingleEndpoint': {'path':'/jsonrpc','methods':['POST']}}
self['variable_settings'] = {
'default_type':... |
"""Utilities for determining application-specific dirs.
See <http://github.com/ActiveState/appdirs> for details and usage.
"""
# Dev Notes:
# - MSDN on where to store app data files:
# http://support.microsoft.com/default.aspx?scid=kb;en-us;310294#XSLTH3194121123120121120120
# - Mac OS X: http://developer.apple.com/... |
"""Tests for stochastic graphs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib import distributions
from tensorflow.contrib.bayesflow.python.ops import stochastic_gradient_estimators
from tensorflow.contrib.bay... |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, with_statement
import contextlib
import datetime
import functools
import socket
import sys
import threading
import time
from tornado import gen
from tornado.ioloop import IOLoop, TimeoutError
from tornado.stack_context import Exc... |
"""Tests for the rasterization_backend."""
from tensorflow_graphics.rendering import rasterization_backend
from tensorflow_graphics.rendering.tests import rasterization_backend_test_base
from tensorflow_graphics.util import test_case
class CPURasterizationBackendTest(
rasterization_backend_test_base.Rasterizatio... |
from os import environ
try:
import asyncio
except ImportError:
# Trollius >= 0.3 was renamed
import trollius as asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
class Component(ApplicationSession):
"""
An application component that publishes an event every second.
... |
import unittest
from test import test_support as support
import io # C implementation.
import _pyio as pyio # Python implementation.
# Simple test to ensure that optimizations in the IO library deliver the
# expected results. For best testing, run this under a debug-build Python too
# (to exercise asserts in the C c... |
# -*- coding: utf-8 -*-
"""
pygments.plugin
~~~~~~~~~~~~~~~
Pygments setuptools plugin interface. The methods defined
here also work if setuptools isn't installed but they just
return nothing.
lexer plugins::
[pygments.lexers]
yourlexer = yourmodule:YourLexer
formatter pl... |
"""
DE-specific Form helpers
"""
from __future__ import absolute_import
import re
from django.contrib.localflavor.de.de_states import STATE_CHOICES
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, RegexField, Select
from django.utils.tran... |
"""empty message
Revision ID: b5d826fbeb95
Revises: 25743fc519b2
Create Date: 2017-01-29 22:50:26.051735
"""
# revision identifiers, used by Alembic.
revision = 'b5d826fbeb95'
down_revision = '25743fc519b2'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... |
"""
Test the autocomplete mode
"""
from pyqode.core.api import TextHelper
from pyqode.qt import QtCore, QtWidgets
from pyqode.qt.QtTest import QTest
from pyqode.python import modes as pymodes
from test.helpers import editor_open
def get_mode(editor):
return editor.modes.get(pymodes.GoToAssignmentsMode)
@editor_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.