content string |
|---|
__all__ = ['BaseResolver', 'Resolver']
from error import *
from nodes import *
import re
class ResolverError(YAMLError):
pass
class BaseResolver(object):
DEFAULT_SCALAR_TAG = u'tag:yaml.org,2002:str'
DEFAULT_SEQUENCE_TAG = u'tag:yaml.org,2002:seq'
DEFAULT_MAPPING_TAG = u'tag:yaml.org,2002:map'
... |
import xml.sax
from boto import handler
from boto.emr import emrobject
from boto.resultset import ResultSet
from tests.compat import unittest
JOB_FLOW_EXAMPLE = b"""
<DescribeJobFlowsResponse
xmlns="http://elasticmapreduce.amazonaws.com/doc/2009-01-15">
<DescribeJobFlowsResult>
<JobFlows>
<member>
... |
"""Tests for data input for speech commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.examples.speech_commands import freeze
from tensorflow.python.platform import test
class FreezeTest(test.TestCase):
def testCreateInferenceG... |
import unittest
from jobpip3 import Record
class TestRecord(unittest.TestCase):
"""Record() tests"""
def test_dict(self):
"""a Record() mimics a dict. Test that here"""
# create a record
a = Record()
# __setattr__
a['foo'] = 2.5
self.assertEqual(a['foo'], 2... |
"""Unit test utilities for Google C++ Testing Framework."""
__author__ = '<EMAIL> (Zhanyong Wan)'
import atexit
import os
import shutil
import sys
import tempfile
import unittest
_test_module = unittest
# Suppresses the 'Import not at the top of the file' lint complaint.
# pylint: disable-msg=C6204
try:
import sub... |
import sys
from ast import literal_eval
import os
infile = open(os.path.join(os.path.dirname(__file__), 'prime_pairs.txt'))
PRIME_PAIRS = literal_eval(infile.read())
for key in PRIME_PAIRS.keys():
PRIME_PAIRS[key] = set(PRIME_PAIRS[key]) # literal_eval doesn't support sets, hence we convert here
infile.close()
... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import strip_or_none
class SkySportsIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?skysports\.com/watch/video/(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.skysports.com/watch/video/10328419/ba... |
from __future__ import absolute_import, print_function
import os
import sys
import tempfile
import numpy
from numpy.testing import TestCase, assert_, run_module_suite
from scipy.weave import inline_tools, ext_tools
from scipy.weave.build_tools import msvc_exists, gcc_exists
from scipy.weave.catalog import unique_fil... |
from __future__ import print_function, unicode_literals
from weblab.translator.translators import StoresEverythingExceptForFilesTranslator
import test.unit.configuration as configuration_module
import unittest
import voodoo.configuration as ConfigurationManager
class StoresEverythingExceptForFilesTranslatorTestCase(... |
"""Route Entity."""
import geom
import util
import errors
from entity import Entity
class Route(Entity):
"""Transitland Route Entity."""
onestop_type = 'r'
def geohash(self):
"""Return 10 characters of geohash."""
return geom.geohash_features(self.stops())
def add_tags_gtfs(self, gtfs_entity):
ke... |
from grpc._adapter import _types as type_interfaces
from grpc._cython import cygrpc
class ClientCredentials(object):
def __init__(self):
raise NotImplementedError()
@staticmethod
def google_default():
raise NotImplementedError()
@staticmethod
def ssl():
raise NotImplementedError()
@staticme... |
from oslo_config import cfg
from nova.tests.functional.v3 import test_servers
CONF = cfg.CONF
CONF.import_opt('manager', 'nova.cells.opts', group='cells')
class AvailabilityZoneJsonTest(test_servers.ServersSampleBase):
ADMIN_API = True
extension_name = "os-availability-zone"
def _setup_services(self):
... |
"""Tests for nets.inception_v2."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.framework.python.ops import arg_scope
from tensorflow.contrib.framework.python.ops import variables as variables_lib
from tensorfl... |
from ctypes import c_char_p, c_double, c_int, c_void_p, POINTER
from django.contrib.gis.gdal.envelope import OGREnvelope
from django.contrib.gis.gdal.libgdal import lgdal
from django.contrib.gis.gdal.prototypes.errcheck import check_bool, check_envelope
from django.contrib.gis.gdal.prototypes.generation import (const_s... |
"""A `Transform` that computes the sum of two `Series`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.learn.python.learn.dataframe import series
from tensorflow.contrib.learn.python.learn.dataframe import transform
from tensorfl... |
import errno
import os
from borg.helpers import truncate_and_unlink
"""
platform base module
====================
Contains platform API implementations based on what Python itself provides. More specific
APIs are stubs in this module.
When functions in this module use platform APIs themselves they access the public... |
# coding: utf-8
# # Test pyIAST for match with competitive Langmuir model
# In the case that the pure-component isotherms $N_{i,pure}(P)$ follow the Langmuir model with the same saturation loading $M$:
#
# $N_{i,pure} = M \frac{K_iP}{1+K_iP},$
#
# The mixed gas adsorption isotherm follows the competitive Langmuir iso... |
import sys
from java.lang import Thread, Runnable
from robot.errors import TimeoutError
class Timeout(object):
def __init__(self, timeout, error):
self._timeout = timeout
self._error = error
def execute(self, runnable):
runner = Runner(runnable)
thread = Thread(runner, name... |
from yowsup.structs import ProtocolTreeNode
from .notification_contact import ContactNotificationProtocolEntity
class RemoveContactNotificationProtocolEntity(ContactNotificationProtocolEntity):
'''
<notification offline="0" id="{{NOTIFICATION_ID}}" notify="{{NOTIFY_NAME}}" type="contacts"
t="{{TIME... |
# Useful unit conversions
def secsToDays(s):
'''Assume s is time in seconds and a positive integer or float.
Return time in days'''
days = s / (60 * 60 * 24)
return days
def daysToSecs(d):
'''Assume d is time in days and a positive integer or float.
Return time in seconds'''
secs = (60 * ... |
from __future__ import unicode_literals
import frappe
import unittest
from frappe.desk.doctype.desktop_icon.desktop_icon import (get_desktop_icons, add_user_icon,
set_hidden_list, set_order, clear_desktop_icons_cache)
# test_records = frappe.get_test_records('Desktop Icon')
class TestDesktopIcon(unittest.TestCase)... |
from cx_Oracle import CLOB
from django.contrib.gis.db.backends.base.adapter import WKTAdapter
from django.contrib.gis.geos import GeometryCollection, Polygon
from django.utils.six.moves import range
class OracleSpatialAdapter(WKTAdapter):
input_size = CLOB
def __init__(self, geom):
"""
Oracl... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
from ansible.module_utils.aws.core import AnsibleAWSModule, is_boto3_error_code
from ansible.module_utils.ec2 import ansible_dict_to_boto3_filter_list, boto3_tag_list_to_ansible_di... |
import os
from distutils import log
import itertools
from setuptools.extern.six.moves import map
flatten = itertools.chain.from_iterable
class Installer:
nspkg_ext = '-nspkg.pth'
def install_namespaces(self):
nsp = self._get_all_ns_packages()
if not nsp:
return
filenam... |
__version__ = '0.0.1'
"""Reading and executing SQL"""
from os import path
class Table(object):
"""Given a table name and a `sqlite3.Cursor`, execute `CREATE TABLE` and
`INSERT INTO`.
"""
SQL_PATH = path.abspath(path.join(path.dirname(__file__), 'sql'))
def __init__(self, name):
self.... |
# -*- coding: utf-8 -*-
__doc__ = """
malibu.design.borgish
---------------------
Borgish was designed as a more extended implementation of Alex Martelli's
Borg design pattern, which aims to provide state consistency similar to
a singleton design, but without the terribleness of singletons.
"""
class SharedState(ob... |
# -*- coding: UTF-8 -*-
"""
.. code-block:: gherkin
Given I setup the current values for active tags with:
| category | value |
| foo | xxx |
Then the following active tag combinations are enabled:
| tags | enabled? |
| @active.with_foo=xxx ... |
"""Load an md.Topology from AMBER PRMTOP files
"""
# Written by: TJ Lane <<EMAIL>> 2/25/14
# This code was mostly stolen/stripped down from OpenMM code, specifically
# the files amber_file_parser.py and amberprmtopfile.py
##############################################################################
# Imports
######... |
words=[
'counterintelligence',
'interdenominational',
'nonrepresentational',
'characteristically',
'chlorofluorocarbon',
'disproportionately',
'electrocardiograph',
'oversimplification',
'telecommunications',
'transubstantiation',
'commercialization',
'comprehensiveness',
'conscientiousness',
'constitutionality',
'cont... |
"""Unit tests for VectorEncoder."""
CL_VERBOSITY = 0
import unittest2 as unittest
from nupic.encoders.vector import VectorEncoder, VectorEncoderOPF, SimpleVectorEncoder
from nupic.encoders.scalar import ScalarEncoder
class VectorEncoderTest(unittest.TestCase):
"""Unit tests for VectorEncoder class."""
def se... |
"""Common tags used for graphs in SavedModel.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.util.tf_export import tf_export
# Tag for the `serving` graph.
SERVING = "serve"
tf_export("saved_model.tag_constants.SERVING").export... |
import copy
import mock
import testtools
from stackalytics.processor import default_data_processor
from stackalytics.processor import normalizer
from tests.unit import test_data
class TestDefaultDataProcessor(testtools.TestCase):
def setUp(self):
super(TestDefaultDataProcessor, self).setUp()
se... |
"""
Convert numbers from base 10 integers to base X strings and back again.
Sample usage::
>>> base20 = BaseConverter('0123456789abcdefghij')
>>> base20.encode(1234)
'31e'
>>> base20.decode('31e')
1234
>>> base20.encode(-1234)
'-31e'
>>> base20.decode('-31e')
-1234
>>> base11 = BaseConverter('0123... |
import numpy as np
import skimage
from skimage.transform import rescale
def split_tiles(image, shape, overlap=16):
""" Rescale and split the input images to get several overlapping images of a given shape.
*** The inpput must be CHANNELS FIRST ***
The input image is rescaled so that height matches the o... |
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, flt, has_common, comma_or
from frappe import session, _
from erpnext.utilities.transaction_base import TransactionBase
class AuthorizationControl(TransactionBase):
def get_appr_user_role(self, det, doctype_name, total, based_on, cond... |
from sqlalchemy.test.testing import eq_, assert_raises, \
assert_raises_message
from sqlalchemy import exc as sa_exc, util, Integer, String, ForeignKey
from sqlalchemy.orm import exc as orm_exc, mapper, relationship, \
sessionmaker
from sqlalchemy.test import testing, profiling
from test.orm import _base
from s... |
#### ## ## ######## ####### ######## ######## ######
## ### ### ## ## ## ## ## ## ## ## ##
## #### #### ## ## ## ## ## ## ## ##
## ## ### ## ######## ## ## ######## ## ######
## ## ## ## ## ## ## ## ## ##
## ## #... |
# ~*~ coding: utf-8 ~*~
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
class Skill(models.Model):
"""
A skill has a name and a skill level.
"""
name = models.CharField(max_length=30)
skill_level = models.IntegerField(validators=[MinValueValidat... |
from setuptools import setup
setup(name='remind',
version='0.17.0',
description='Remind Python library',
long_description=open('README.rst').read(),
author='Jochen Sprickerhof',
author_email='<EMAIL>',
license='GPLv3+',
url='https://github.com/jspricke/python-remind',
ke... |
from __future__ import unicode_literals
from .common import InfoExtractor
class KetnetIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ketnet\.be/(?:[^/]+/)*(?P<id>[^/?#&]+)'
_TESTS = [{
'url': 'https://www.ketnet.be/kijken/zomerse-filmpjes',
'md5': 'd907f7b1814ef0fa285c0475d9994ed7',
... |
import csv
import os
import shutil
from nupic.data.file_record_stream import FileRecordStream
from nupic.frameworks.opf.experiment_runner import runExperiment
from nupic.support import initLogging
from nupic.support.unittesthelpers.testcasebase import (
unittest, TestCaseBase as HelperTestCaseBase)
_EXPERIMENT_BA... |
"""
Copyright (c) 2012-2020 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... |
# ASN.1 "character string" types
from pyasn1.type import univ, tag
class NumericString(univ.OctetString):
tagSet = univ.OctetString.tagSet.tagImplicitly(
tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 18)
)
class PrintableString(univ.OctetString):
tagSet = univ.OctetString.tagSet.tagImpli... |
from ryu.lib import stringify
from lxml import objectify
import lxml.etree as ET
_ns_of111 = 'urn:onf:of111:config:yang'
_ns_netconf = 'urn:ietf:params:xml:ns:netconf:base:1.0'
_nsmap = {
'of111': _ns_of111,
'nc': _ns_netconf,
}
def _pythonify(name):
return name.replace('-', '_')
class _e(object):
... |
import gdbm
import unittest
import os
from test.test_support import verbose, TESTFN, run_unittest, unlink
filename = TESTFN
class TestGdbm(unittest.TestCase):
def setUp(self):
self.g = None
def tearDown(self):
if self.g is not None:
self.g.close()
unlink(filename)
d... |
#!/usr/bin/python
import sys
import simplejson
def usage():
return '''
constructs adjacency_graphs.coffee from QWERTY and DVORAK keyboard layouts
usage:
%s adjacency_graphs.coffee
''' % sys.argv[0]
qwerty = r'''
`~ 1! 2@ 3# 4$ 5% 6^ 7& 8* 9( 0) -_ =+
qQ wW eE rR tT yY uU iI oO pP [{ ]} \|
aA sS dD fF gG... |
"""
Nagios NDO external inventory script.
========================================
Returns hosts and hostgroups from Nagios NDO.
Configuration is read from `nagios_ndo.ini`.
"""
import os
import argparse
import sys
try:
import configparser
except ImportError:
import ConfigParser
configparser = ConfigPars... |
""" cat bin asccii
Examples:
"""
"""
todo:
__doc__
test examples
"""
import argparse
import fileinput
import os
import re
import sys
import binascii
def main(args):
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('files', nargs='*', help='files to be processed')
ap.add_argument('... |
"""
Utility methods for the Shopping Cart app
"""
from django.conf import settings
from microsite_configuration import microsite
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDF... |
"""
Set of "markup" template filters for Django. These filters transform plain text
markup syntaxes to HTML; currently there is support for:
* Textile, which requires the PyTextile library available at
http://dealmeida.net/projects/textile/
* Markdown, which requires the Python-markdown library from
... |
from __future__ import print_function
from __future__ import absolute_import
# ###################################################################
# Import packages
# ###################################################################
from magpy.stream import DataStream, KEYLIST, NUMKEYLIST, subtractStreams
import st... |
# coding: utf-8
from django.contrib.auth.models import User, Permission
from django.urls import reverse
from django.utils import timezone
from rest_framework import status
from kpi.constants import ASSET_TYPE_COLLECTION
from kpi.models import Asset, ObjectPermission
from kpi.models.object_permission import get_anonymo... |
"""Tests for the user_input module."""
from absl.testing import absltest
from dm_control.viewer import user_input
import mock
class InputMapTests(absltest.TestCase):
def setUp(self):
super().setUp()
self.mouse = mock.MagicMock()
self.keyboard = mock.MagicMock()
self.input_map = user_input.InputMa... |
from __future__ import unicode_literals
from PyObjCTools.TestSupport import *
import objc
import copy
from PyObjCTest.fnd import *
objc.registerMetaDataForSelector(
b"NSObject", b"validateValue:forKey:error:",
dict(
arguments={
2: dict(type_modifier=objc._C_INOUT),
... |
"""Tests for distutils.cmd."""
import unittest
import os
from test.test_support import captured_stdout, run_unittest
from distutils.cmd import Command
from distutils.dist import Distribution
from distutils.errors import DistutilsOptionError
from distutils import debug
class MyCmd(Command):
def initialize_options(... |
"""Tests for google3.third_party.tensorflow_models.slim.nets.mobilenet.mobilenet_v3."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from nets.mobilenet import mobilenet_v3
from google3.testing.pybase import parameteriz... |
"""
Testing for export functions of decision trees (sklearn.tree.export).
"""
from numpy.testing import assert_equal
from nose.tools import assert_raises
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.tree import export_graphviz
from sklearn.externals.six import StringIO
# toy sa... |
# -*- coding: utf-8 -*-
import os
import re
from module.plugins.internal.Hoster import Hoster
from module.network.XDCCRequest import XDCCRequest
from module.plugins.internal.misc import parse_name, safejoin
class XDCC(Hoster):
__name__ = "XDCC"
__type__ = "hoster"
__version__ = "99"
__status__ ... |
from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
# url(r'^retirement-api/admin/', include(admin.site.urls)),
url(r'^retirement... |
"""
Rename the PS name of the input font.
OpenType fonts (*.otf) are not currently supported. They are copied to the destination without renaming.
XML files are also copied in case they are passed there by mistake.
Usage: build_font_single.py /path/to/input_font.ttf /path/to/output_font.ttf
"""
import glob
import o... |
import unittest
from smoke_itest_support import SmokeIntegrationTestSupport
class SetupSmokeTest(SmokeIntegrationTestSupport):
PROJECT_FILES = list(SmokeIntegrationTestSupport.PROJECT_FILES) + ["setup.py"]
def test_smoke_setup_install(self):
self.smoke_test_module("pip", "-vvvvvvvvvvvvvv", "install"... |
apiAttachAvailable = u'API jest dost\u0119pne'
apiAttachNotAvailable = u'Niedost\u0119pny'
apiAttachPendingAuthorization = u'Autoryzacja w toku'
apiAttachRefused = u'Odmowa'
apiAttachSuccess = u'Sukces'
apiAttachUnknown = u'Nieznany'
budDeletedFriend = u'Usuni\u0119ty z listy znajomych'
budFriend = u'Znajomy'
b... |
"""
Stub implementation of catalog service for acceptance tests
"""
# pylint: disable=invalid-name, missing-docstring
import re
import urlparse
from .http import StubHttpRequestHandler, StubHttpService
class StubCatalogServiceHandler(StubHttpRequestHandler):
def do_GET(self):
pattern_handlers = {
... |
from __future__ import absolute_import, print_function, unicode_literals
from collections import defaultdict
import os
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
SubCommand,
)
from mozbuild.base import MachCommandBase
import mozpack.path as mozpath
class InvalidPathExc... |
# SVI for a GMM
# Modified from
# https://github.com/brendanhasz/svi-gaussian-mixture-model/blob/master/BayesianGaussianMixtureModel.ipynb
#pip install tf-nightly
#pip install --upgrade tfp-nightly -q
# Imports
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
import ten... |
__author__ = 'Brian Quinlan (<EMAIL>)'
import collections
import logging
import threading
import time
FIRST_COMPLETED = 'FIRST_COMPLETED'
FIRST_EXCEPTION = 'FIRST_EXCEPTION'
ALL_COMPLETED = 'ALL_COMPLETED'
_AS_COMPLETED = '_AS_COMPLETED'
# Possible future states (for internal use by the futures package).
PENDING = '... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from units.modules.utils import set_module_args, exit_json, fail_json, AnsibleExitJson
from ansible.module_utils import basic
from ansible.modules.network.check_point import cp_mgmt_host_facts
OBJECT = {
"from": 1... |
# -*- coding: utf-8 -*-
import argparse
import aikif.config as cfg
def search(search_string):
"""
main function to search using indexes
"""
print('Searching for ' + search_string)
ndxFiles = cfg.params['index_files']
numResults = 0
totLines = 0
for fname in ndxFiles:
print("Se... |
"""
@author: AAron Walters
@license: GNU General Public License 2.0
@contact: <EMAIL>
@organization: Volatility Foundation
"""
import volatility.debug as debug
import volatility.registry as registry
import volatility.addrspace as addrspace
import volatility.constants as constants
import volatility.conf... |
# encoding: utf-8
"""
Step implementations for table-related features
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from behave import given, then, when
from docx import Document
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_TABLE_DIRECTION
from docx.shared impo... |
from __future__ import unicode_literals
from markupsafe import Markup
from indico.util.i18n import _
from indico.util.placeholders import Placeholder
from indico.web.flask.util import url_for
class FirstNamePlaceholder(Placeholder):
name = 'first_name'
description = _("First name of the person")
@class... |
from Source import Source
from Components.Element import cached
from enigma import eTimer
# a small warning:
# you can use that boolean well to express screen-private
# conditional expressions.
#
# however, if you think that there is ANY interest that another
# screen could use your expression, please put your calcula... |
from docutils import nodes
from docutils.parsers.rst import Directive, directives
from nikola.plugin_categories import RestExtension
class Plugin(RestExtension):
name = "link_figure"
def set_site(self, site):
self.site = site
directives.register_directive('link_figure', LinkFigure)
... |
#!/usr/bin/env python
import unittest
from pycoin import encoding
from pycoin.serialize import h2b
class EncodingTestCase(unittest.TestCase):
def test_to_from_long(self):
def do_test(as_int, prefix, as_rep, base):
self.assertEqual((as_int, prefix), encoding.to_long(base, encoding.byte_to_int... |
"""Locate *_test modules and run the tests in them."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pkgutil
import re
import subprocess
import sys
import glazier
FAILED_RE = re.compile(r'FAILED\s*\(errors=(\d*)\)')
def main():
results = {'co... |
from decorator import decorator
from inspect import getargspec
import lru
import logging
logger = logging.getLogger(__name__)
class ormcache(object):
""" LRU cache decorator for orm methods. """
def __init__(self, skiparg=2, size=8192, multi=None, timeout=None):
self.skiparg = skiparg
self.... |
"""Tests for fan platforms."""
import unittest
from homeassistant.components.fan import FanEntity
import pytest
class BaseFan(FanEntity):
"""Implementation of the abstract FanEntity."""
def __init__(self):
"""Initialize the fan."""
pass
class TestFanEntity(unittest.TestCase):
"""Test ... |
from django.core.management.base import BaseCommand, CommandError
from main.models import Project, Person
import csv
# This file is part of https://github.com/cpina/science-cruise-data-management
#
# This project was programmed in a hurry without any prior Django experience,
# while circumnavigating the Antarctic on t... |
import time
from openerp.osv import fields, osv
from openerp.tools.translate import _
class account_use_model(osv.osv_memory):
_name = 'account.use.model'
_description = 'Use model'
_columns = {
'model': fields.many2many('account.model', 'account_use_model_relation', 'account_id', 'model_id', 'Ac... |
"""utilities for analyzing expressions and blocks of Python
code, as well as generating Python from AST nodes"""
from mako import exceptions, pyparser, compat
import re
class PythonCode(object):
"""represents information about a string containing Python code"""
def __init__(self, code, **exception_kwargs):
... |
"""Test reproduce state for Input datetime."""
from homeassistant.core import State
from tests.common import async_mock_service
async def test_reproducing_states(hass, caplog):
"""Test reproducing Input datetime states."""
hass.states.async_set(
"input_datetime.entity_datetime",
"2010-10-10 0... |
from tkinter import *
from idlelib.EditorWindow import EditorWindow
import re
import tkinter.messagebox as tkMessageBox
from idlelib import IOBinding
class OutputWindow(EditorWindow):
"""An editor window that can serve as an output file.
Also the future base class for the Python shell window.
This class ... |
#!/usr/bin/env python3
import argparse
import os
import random
import sys
import mageec
gcc_flags = [
#'-faggressive-loop-optimizations', # Not supported in 4.5
'-falign-functions',
'-falign-jumps',
'-falign-labels',
'-falign-loops',
'-fbranch-count-reg',
'-fbranch-target-load-optimize',
... |
"""CounterManager for Mac OSX"""
import subprocess
from cmanager import CounterManager
import sys
def GetProcessData(pid):
"""Runs a ps on the process identified by pid and returns the output line
as a list (pid, vsz, rss)
"""
command = ['ps -o pid,vsize,rss -p'+str(pid)]
try:
handle = ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import sys
import copy
from ansible import constants as C
from ansible.plugins.action.network import ActionModule as ActionNetworkModule
from ansible.module_utils.network.cnos.cnos import cnos_provider_spec
from ansible.module_uti... |
"""
Tests for class dashboard (Metrics tab in instructor dashboard)
"""
import json
from django.test.client import RequestFactory
from mock import patch
from nose.plugins.attrib import attr
from xmodule.modulestore.tests.factories import CourseFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestC... |
__all__ = ['normal', 'uniform', 'poisson']
from ..defmatrix import *
# Special object used internally to specify the placeholder which will be replaced by output ID
# This helps to provide dml containing output ID in constructSamplingNode
OUTPUT_ID = '$$OutputID$$'
def constructSamplingNode(inputs, dml):
"""
... |
"""
This module contains multithread-safe cache implementations.
All Caches have
getorbuild(key, builder)
delentry(key)
methods and allow configuration when instantiating the cache class.
"""
from time import time as gettime
class BasicCache(object):
def __init__(self, maxentries=128):
self.maxe... |
from __future__ import absolute_import
from __future__ import unicode_literals
from haystack import indexes
from wiki import models
class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
created = indexes.DateTimeField(model_attr='created')
m... |
#!/usr/bin/env python3
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import numpy as np
np.set_printoptions(threshold=np.nan)
import tensorflow as tf
import time
from PIL import Image as im
def convolve_inner_layers(x, W, b):
y = tf.nn.conv2d(x, W, strides = [1,1,1,1], padding='SAME')
y = tf.nn.bias_add(y, ... |
from sympy import Function, sympify, diff, Eq, S, Symbol, Derivative
from sympy.core.compatibility import (
combinations_with_replacement, iterable, range)
def euler_equations(L, funcs=(), vars=()):
r"""
Find the Euler-Lagrange equations [1]_ for a given Lagrangian.
Parameters
==========
L :... |
"""
SQL functions reference lists:
http://www.gaia-gis.it/spatialite-3.0.0-BETA/spatialite-sql-3.0.0.html
https://web.archive.org/web/20130407175746/http://www.gaia-gis.it/gaia-sins/spatialite-sql-4.0.0.html
http://www.gaia-gis.it/gaia-sins/spatialite-sql-4.2.1.html
"""
import re
import sys
from django.contrib.gis.db.... |
from __future__ import print_function
# Copyright (c) 2015 Intel Corporation.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights ... |
from __future__ import (absolute_import, division, print_function)
from ansible.module_utils.six import string_types, integer_types
__metaclass__ = type
import datetime
try:
from pymongo import ASCENDING, DESCENDING
from pymongo.errors import ConnectionFailure
from pymongo import MongoClient
except Import... |
import gtk
from resistencia import xdg
from resistencia.nls import gettext as _
def _draw_string(string, color):
return '<span foreground="' + color + '"><b>' + string + '</b></span>'
class roundResults:
def add_column(self, list_view, title, columnId):
column = gtk.TreeViewColumn(title, gtk.CellRend... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'community'}
RETURNS = '''
aos_session:
description: Authenticated session information
returned: always
type: dict
sample: { 'url': <str>, 'headers': {...} }
'''
from ansible.modul... |
__author__ = 'wwxiang'
#coding=utf-8
import os
import re
work = os.getcwd()
resxml = work + os.path.sep + 'blogcn.opml'
workmd = work + os.path.sep + 'README.md'
def handler():
isblock = True
handlerData = []
lineNo = 0
try:
with open(workmd,'rb') as linefs:
lineCout = len(linefs... |
from math import ceil
from boto.compat import json, map, six
import requests
SIMPLE = 'simple'
STRUCTURED = 'structured'
LUCENE = 'lucene'
DISMAX = 'dismax'
class SearchServiceException(Exception):
pass
class SearchResults(object):
def __init__(self, **attrs):
self.rid = attrs['status']['rid']
... |
from CodernityDB.tree_index import TreeBasedIndex
import struct
import os
import inspect
from functools import wraps
import json
class DebugTreeBasedIndex(TreeBasedIndex):
def __init__(self, *args, **kwargs):
super(DebugTreeBasedIndex, self).__init__(*args, **kwargs)
def print_tree(self):
p... |
# Test wheel.
# The file has the following contents:
# hello.pyd
# hello/hello.py
# hello/__init__.py
# test-1.0.data/data/hello.dat
# test-1.0.data/headers/hello.dat
# test-1.0.data/scripts/hello.sh
# test-1.0.dist-info/WHEEL
# test-1.0.dist-info/METADATA
# test-1.0.dist-info/RECORD
# The ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.