content stringlengths 4 20k |
|---|
import simuPOP as sim
pop = sim.Population(1000, loci=[20])
pop.evolve(
initOps=[
sim.InitSex(),
sim.InitGenotype(freq=[0.8, 0.2])
],
preOps=[
sim.PyEval(r"'At the beginning of gen %d: allele Freq: %.2f\n' % (gen, alleleFreq[0][0])",
at = [-10, -1])
],
matingSchem... |
# -*- coding: utf-8 -*-
"""
RED Plugin
Copyright (C) 2014-2015 Matthias Bolte <<EMAIL>>
Copyright (C) 2014 Olaf Lüke <<EMAIL>>
program_page_shell.py: Program Wizard Shell Page
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the ... |
# Tests command line execution of scripts
import contextlib
import unittest
import os
import os.path
import test.test_support
from test.script_helper import (run_python,
temp_dir, make_script, compile_script,
assert_python_failure, make_pkg,
... |
# -*- coding: utf-8 -*-
from collections import OrderedDict
from io import BytesIO
from mock import patch
import pytest
from requests_toolbelt import MultipartEncoder
from requests.exceptions import HTTPError
from onecodex.exceptions import OneCodexException, UploadException
from onecodex.lib.upload import (
_choo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='EmailUser',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '1.1.4'
__author__ = 'Liao Xuefeng (<EMAIL>)'
'''
Python client SDK for sina weibo API using OAuth 2.
'''
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import gzip, time, json, hmac, base64, hashlib, urllib, ... |
# -*- coding: utf-8 -*-
"""Examples of non-linear functions for non-parametric regression
Created on Sat Jan 05 20:21:22 2013
Author: Josef Perktold
"""
import numpy as np
## Functions
def fg1(x):
'''Fan and Gijbels example function 1
'''
return x + 2 * np.exp(-16 * x**2)
def fg1eu(x):
'''Eubank ... |
from sets import Set
from oslo import messaging
from trove.common.context import TroveContext
from oslo.utils import importutils
from trove.backup.models import Backup
import trove.common.cfg as cfg
from trove.common.i18n import _
import trove.common.rpc.version as rpc_version
from trove.common import exception
from... |
import random
from twisted.trial.unittest import TestCase
from axiom.store import Store
from axiom.item import Item
from axiom.attributes import integer
from axiom.queryutil import overlapping, AttributeTuple
class Segment(Item):
typeName = 'test_overlap_segment'
schemaVersion = 1
x = integer()
y =... |
"""Utility script to install APKs from the command line quickly."""
import multiprocessing
import optparse
import os
import sys
from pylib import android_commands
from pylib import constants
from pylib.utils import apk_helper
from pylib.utils import test_options_parser
def AddInstallAPKOption(option_parser):
"""A... |
import os
import errno
import signal
import subprocess
import sys
import time
# Since we execute this script directly as part of the unit tests, we need to ensure
# that Tools/Scripts is in sys.path for the next imports to work correctly.
script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.... |
'''Vector
======
The :class:`Vector` represents a 2D vector (x, y).
Our implementation is built on top of a Python list.
An example of constructing a Vector::
>>> # Construct a point at 82,34
>>> v = Vector(82, 34)
>>> v[0]
82
>>> v.x
82
>>> v[1]
34
>>> v.y
34
>>> # Cons... |
"""API test cases."""
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework.test import APIClient
from . import factories
from . import models
class InstanceViewSetTestCase(TestCase):
"""TestCase for InstanceViewSet."""
@classmethod
def setUpTestData(cls):
... |
import BoostBuild
def test_basic():
t = BoostBuild.Tester(use_test_config=False)
t.write("jamroot.jam", "")
t.write("d1/a.cpp", "int main() {}\n")
t.write("d1/jamfile.jam", "exe a : [ glob *.cpp ] ../d2/d//l ;")
t.write("d2/d/l.cpp", """\
#if defined(_WIN32)
__declspec(dllexport)
void force_impor... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def cloud_block_storage_attachments(module, state, volume, server, device,
... |
"""Tests for google.protobuf.proto_builder."""
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict #PY26
try:
import unittest2 as unittest
except ImportError:
import unittest
from google.protobuf import descriptor_pb2
from google.protobuf import descriptor_poo... |
from couchpotato.core.event import addEvent, fireEvent
from couchpotato.core.helpers.encoding import simplifyString
from couchpotato.core.helpers.variable import getImdb, md5
from couchpotato.core.logger import CPLog
from couchpotato.core.plugins.base import Plugin
from urlparse import urlparse
log = CPLog(__name__)
... |
"""Tests for templates module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gast
from tensorflow.python.autograph.pyct import anno
from tensorflow.python.autograph.pyct import parser
from tensorflow.python.autograph.pyct import transformer
fro... |
import os, struct, sys, time
from serial import Serial
from serial import SerialException
import ispBase, intelHex
class Stk500v2(ispBase.IspBase):
def __init__(self):
self.serial = None
self.seq = 1
self.lastAddr = -1
self.progressCallback = None
def connect(self, port = 'COM22', speed = 115200):
if s... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.six.moves im... |
from numpy import *
def denoise(im,U_init,tolerance=0.1,tau=0.125,tv_weight=100):
""" An implementation of the Rudin-Osher-Fatemi (ROF) denoising model
using the numerical procedure presented in Eq. (11) of A. Chambolle
(2005). Implemented using periodic boundary conditions.
Input... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
r_colors.py
-----------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
************************************... |
import datetime
def max_partition(
table, schema="default", field=None, filter=None,
metastore_conn_id='metastore_default'):
'''
Gets the max partition for a table.
:param schema: The hive schema the table lives in
:type schema: string
:param table: The hive table you are interest... |
import decorator
from collections import Callable
def decorator_apply(dec, func, args, kwargs):
"""
Decorate a function by preserving the signature even if dec
is not a signature-preserving decorator.
"""
return decorator.FunctionMaker.create(
func, 'return decorated(%(signature)s)',
... |
"""This is the Bokeh charts testing interface.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this... |
from boto.regioninfo import RegionInfo, get_regions
def regions():
"""
Get all available regions for the Amazon Glacier service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
from boto.glacier.layer2 import Layer2
return get_regions('glacier', connection_cls=Laye... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.cloudstack import (
AnsibleCloudStack,
cs_argument_spec,
cs_required_together
)
... |
from direct.directnotify import DirectNotifyGlobal
from direct.interval.IntervalGlobal import *
import random
import BattleParticles
from BattleProps import *
from BattleSounds import *
import HealJokes
import MovieCamera
import MovieUtil
from toontown.chat.ChatGlobals import *
from toontown.pets import Pet, PetTricks... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import re
import time
HAS_PB_SDK = True
try:
from profitbricks.client import ProfitBri... |
import hashlib
from abc import ABCMeta, abstractmethod
from itertools import islice
from random import Random
from tqdm import tqdm
from .item_list import ItemList
from .logging import logger
__all__ = ['SeedGenerator', 'TohuBaseGenerator']
class TohuBaseGenerator(metaclass=ABCMeta):
"""
Base class for all... |
import os
import imp
from nupic.encoders import (LogEncoder,
DateEncoder,
MultiEncoder,
CategoryEncoder,
SDRCategoryEncoder,
ScalarEncoder)
from nupic.data.file_record_stream import File... |
import locust
import runners
import gevent
import sys
import os
import signal
import inspect
import logging
import socket
from optparse import OptionParser
import web
from log import setup_logging, console_logger
from stats import stats_printer, print_percentile_stats, print_error_report, print_stats
from inspectlocu... |
{
'name': 'Journal Payment Subtype',
'version': '1.0',
'category': 'Account',
'summary': 'Adds payment subtype field to cash and bank journals',
'description': """
Journal Payment Subtype
=======================
Adds payment subtype field to cash and bank journals.
This addon is used by addons tha... |
"""Tests for the gradient of `tf.sparse_tensor_dense_matmul()`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
class SparseTensorDenseMatMulGradientTest(tf.test.TestCase):
def _sparsify(self, x):
x[x < ... |
from __future__ import unicode_literals
import datetime
from unittest import skipIf
from django.test import TestCase, override_settings
from django.utils import timezone
from .models import Article, Category, Comment
try:
import pytz
except ImportError:
pytz = None
class DateTimesTests(TestCase):
def ... |
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
class hr_contract_be(osv.osv):
_inherit = 'hr.contract'
_columns = {
'travel_reimbursement_amount': fields.float('Reimbursement of travel expenses', digits_compute=dp.get_precision('Payroll')),
'car_company_amou... |
__author__ = "Cyril Jaquier"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL"
import os
import shlex
from .configreader import DefinitionInitConfigReader
from ..server.action import CommandAction
from ..helpers import getLogger
# Gets the instance of the logger.
logSys = getLogger(__name__)
c... |
import unittest
import nest
class TestHelperFunctions(unittest.TestCase):
def test_get_verbosity(self):
verbosity = nest.get_verbosity()
self.assertTrue(isinstance(verbosity, int))
def test_set_verbosity(self):
levels = [('M_ALL', 0),
('M_DEBUG', 5),
... |
import time
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.report import report_sxw
from common_report_header import common_report_header
from openerp import SUPERUSER_ID
class third_party_ledger(report_sxw.rml_parse, common_report_header):
def __init__(self, cr, uid, name, context... |
"""
Regression testing.
"""
__docformat__ = 'epytext en'
import unittest, doctest, epydoc, os, os.path, re, sys
def main():
try:
doctest.register_optionflag
except:
print ("\n"
"The regression test suite requires a more recent version of\n"
"doctest (e.g., the version t... |
"""Volume v1 Volume action implementations"""
import argparse
import logging
import six
from cliff import command
from cliff import lister
from cliff import show
from openstackclient.common import parseractions
from openstackclient.common import utils
class CreateVolume(show.ShowOne):
"""Create new volume"""
... |
import os
import logging
class SequencingRun(object):
def __init__(self, metadata = None, sample_list = None, sample_sheet = None):
self._sample_list = sample_list
self._metadata = metadata
if sample_sheet is None:
raise ValueError("Sample sheet cannot be None!")
self.... |
#!/usr/bin/env python
'''Test that mouse button events work correctly.
Expected behaviour:
One window will be opened. Click within this window and check the console
output for mouse events.
- Buttons 1, 2, 4 correspond to left, middle, right, respectively.
- No events for scroll wheel
- Modi... |
from sphinx.domains import Domain, ObjType
from sphinx.roles import XRefRole
from sphinx.domains.std import GenericObject, StandardDomain
from sphinx.directives import ObjectDescription
from sphinx.util.nodes import clean_astext, make_refnode
from sphinx.util import ws_re
from sphinx import addnodes
from sphinx.util.do... |
import numpy as np
from ..base import TransformerMixin
from ..externals import six
from ..utils import safe_mask, check_array
from ..utils.validation import NotFittedError, check_is_fitted
class _LearntSelectorMixin(TransformerMixin):
# Note because of the extra threshold parameter in transform, this does
# ... |
#! /usr/bin/env python
"""
Group fMRI analysis frontend for Lyman ecosystem.
"""
import os
import sys
import time
import shutil
import os.path as op
from textwrap import dedent
import argparse
import matplotlib as mpl
mpl.use("Agg")
import nipype
from nipype import Node, MapNode, SelectFiles, DataSink, IdentityInter... |
import voc
import argparse
from .transpiler import transpile
def main():
parser = argparse.ArgumentParser(
prog='voc',
description='Transpiles Python code to Java class files.'
)
parser.add_argument(
'-o', '--output',
help='The directory where class files should be output... |
"""Package Keysmith."""
import codecs
import os.path
import setuptools # type: ignore
import keysmith # This project only depends on the standard library.
def read(*parts):
"""Read a file in this repository."""
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, *pa... |
import glob
import os
import re
import tempfile
try:
import apt
import apt_pkg
import aptsources.distro as aptsources_distro
distro = aptsources_distro.get_distro()
HAVE_PYTHON_APT = True
except ImportError:
distro = None
HAVE_PYTHON_APT = False
VALID_SOURCE_TYPES = ('deb', 'deb-src')
de... |
import re
from collections import namedtuple
from django.db.backends.base.introspection import (
BaseDatabaseIntrospection, FieldInfo, TableInfo,
)
field_size_re = re.compile(r'^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$')
FieldInfo = namedtuple('FieldInfo', FieldInfo._fields + ('default',))
def get_field_size(name)... |
"""This module contains code from
Think Python by Allen B. Downey
http://thinkpython.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import random
class Card(object):
"""Represents a standard playing card.
Attributes:
suit: integer 0-3
rank: i... |
"""
Module for checking git scm data.
"""
import logging
from iris.etl.scm import MAPPING
from iris.etl.scm import ROLES
from iris.etl.parser import parse_blocks, parse_user
# pylint: disable=C0103,W0603
# C0103: 30,0: Invalid name "logger"
# W0603: 39,4:error: Using the global statement
logger = logging.getLogger(_... |
"""Helpers for monkey-patching Python code."""
__all__ = [
'MonkeyPatcher',
'patch',
]
class MonkeyPatcher(object):
"""A set of monkey-patches that can be applied and removed all together.
Use this to cover up attributes with new objects. Particularly useful for
testing difficult code.
"... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import unittest
from unittest import skipUnless
from django.conf import settings
from django.contrib.gis.geoip2 import HAS_GEOIP2
from django.contrib.gis.geos import HAS_GEOS, GEOSGeometry
from django.test import mock
from django.utils import s... |
"""Test processing of unrequested blocks.
Setup: two nodes, node0+node1, not connected to each other. Node1 will have
nMinimumChainWork set to 0x10, so it won't process low-work unrequested blocks.
We have one P2PInterface connection to node0 called test_node, and one to node1
called min_work_node.
The test:
1. Gene... |
import six
import sys
import test_helper
import unittest
if six.PY3:
from unittest.mock import MagicMock
else:
from mock import MagicMock
from authy import AuthyException, AuthyFormatException
from authy.api import AuthyApiClient
from authy.api.resources import Phones
from authy.api.resources import Phone
c... |
from trove.common.db import models
from trove.common.i18n import _
class MongoDBSchema(models.DatastoreSchema):
"""Represents a MongoDB database and its associated properties."""
@property
def _max_schema_name_length(self):
return 64
def _is_valid_schema_name(self, value):
# check ag... |
import re
from ert_gui.ide.keywords.definitions import ArgumentDefinition
class ProperNameFormatArgument(ArgumentDefinition):
NOT_A_VALID_NAME_FORMAT = "The argument must be a valid string containing a %d and only characters of these types:" \
"<ul>" \
"<li>Letters: ... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
int_or_none,
float_or_none,
qualities,
ExtractorError,
)
class GfycatIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?gfycat\.com/(?:ifr/)?(?P<id>[^/?#]+)'
_TESTS = [{
'... |
import json
import os
import unittest
from functools import partial
import cwltool.pack
import cwltool.workflow
from cwltool.load_tool import fetch_document, validate_document
from cwltool.main import makeRelative
from cwltool.pathmapper import adjustFileObjs, adjustDirObjs
from .util import get_data
class TestPack(u... |
from weboob.tools.test import BackendTest
from weboob.tools.browser import BrowserUnavailable
__all__ = ['AuMTest']
class AuMTest(BackendTest):
BACKEND = 'aum'
def test_new_messages(self):
try:
for message in self.backend.iter_unread_messages():
pass
except Brows... |
# coding: utf-8
from setuptools import setup
requires_list = [
"PyYAML>=3.09"
]
import os.path
def read(fname):
with open(os.path.join(os.path.dirname(__file__), fname)) as inf:
return "\n" + inf.read().replace("\r\n", "\n")
setup(
name='yamlish',
version="0.17.0",
description='Python imp... |
#!/usr/bin/env python3
"""PyPlate : a simple Python-based templating program
PyPlate parses a file and replaces directives (in double square brackets [[ ... ]])
by various means using a given dictionary of variables. Arbitrary Python code
can be run inside many of the directives, making this system highly flexible.
... |
"""Module with utility function for dumping the Hamiltonian to file in FCIDUMP format."""
import numpy as np
from psi4.driver import psifiles as psif
from psi4.driver.p4util.testing import compare_integers, compare_values, compare_recursive
from psi4.driver.procrouting.proc_util import check_iwl_file_from_scf_type
f... |
#!/usr/bin/python
import numpy as np
import matplotlib.pyplot as plt
import sys
pressure = sys.argv[1]
def load(fname):
''' load file using std open '''
f = open(fname, 'r')
data = []
for line in f.readlines():
data.append(line.replace('\n','').replace(',', ' ').strip(' ').split(' '))
f... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
import shade
from shade import meta
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
from distutils.version import StrictVersion
def _get_floating_i... |
"""
Module to read intel hex files into binary data blobs.
IntelHex files are commonly used to distribute firmware
See: http://en.wikipedia.org/wiki/Intel_HEX
This is a python 3 conversion of the code created by David Braam for the Cura project.
"""
import io
from UM.Logger import Logger
def readHex(filename):
"""... |
from xscontainer import api_helper
from xscontainer import util
from xscontainer.util import log
import os
import XenAPI
XSCONTAINER_TLS_CLIENT_CERT = 'xscontainer-tls-client-cert'
XSCONTAINER_TLS_CLIENT_KEY = 'xscontainer-tls-client-key'
XSCONTAINER_TLS_CA_CERT = 'xscontainer-tls-ca-cert'
XSCONTAINER_TLS_KEYS = [XSC... |
from django.test import TransactionTestCase
from restclients_core.exceptions import DataFailureException
from sis_provisioner.dao.hrp import get_worker
from sis_provisioner.dao.pws import get_person
from sis_provisioner.models import UwAccount, get_now
from sis_provisioner.account_managers.bridge_worker import BridgeWo... |
from functools import partial
from typing import Optional, List
import base58
from plenum.common.messages.internal_messages import NewViewCheckpointsApplied
from plenum.common.messages.node_messages import PrePrepare, Checkpoint
from plenum.server.consensus.view_change_service import ViewChangeService
from plenum.ser... |
import boto
from tests.compat import unittest
class DirectConnectTest(unittest.TestCase):
"""
A very basic test to make sure signatures and
basic calls work.
"""
def test_basic(self):
conn = boto.connect_directconnect()
response = conn.describe_connections()
self.assertT... |
import json
from cherrymusicserver import log
from cherrymusicserver import configuration as cfg
from cherrymusicserver import database as db
from cherrymusicserver.database.connect import BoundConnector
DBNAME = 'useroptions'
class UserOptionDB:
def __init__(self, connector=None):
"""user configuratio... |
"""Test the invalidateblock RPC."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class InvalidateTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 3
def setup_network(s... |
from django.utils.translation import ugettext_noop as _
WEEKLY_SUMMARY_XMLNS = 'http://openrosa.org/formdesigner/7EFB54F1-337B-42A7-9C6A-460AE8B0CDD8'
HF_MONTHLY_REPORT = [
{
'section': _('mc_section_home_visits'),
'total_column': _('home_visits_total'),
'columns': [
_('home_vi... |
from i18n import _
import changelog, byterange, url, error
import localrepo, manifest, util, scmutil, store
import urllib, urllib2, errno, os
class httprangereader(object):
def __init__(self, url, opener):
# we assume opener has HTTPRangeHandler
self.url = url
self.pos = 0
self.open... |
from LogAnalyzer import Test,TestResult
import DataflashLog
import math
class TestCompass(Test):
'''test for compass offsets and throttle interference'''
def __init__(self):
Test.__init__(self)
self.name = "Compass"
def run(self, logdata, verbose):
self.result = TestResult()
... |
"""Tests of the Stepper CLI Backend."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.client import session
from tensorflow.python.debug... |
import json
from django.template.loader import render_to_string
from django.utils.html import escapejs
from allauth.account.models import EmailAddress
from allauth.socialaccount.providers.base import Provider, ProviderAccount
class PersonaAccount(ProviderAccount):
def to_str(self):
return self.account.u... |
"""Test with CertificateRequest"""
from __future__ import print_function
import traceback
import sys
import getopt
import re
from itertools import chain
from tlsfuzzer.runner import Runner
from tlsfuzzer.messages import Connect, ClientHelloGenerator, \
ClientKeyExchangeGenerator, ChangeCipherSpecGenerator, \
... |
"""Support for controlling projector via the PJLink protocol."""
import logging
import voluptuous as vol
from homeassistant.components.media_player import (
MediaPlayerDevice, PLATFORM_SCHEMA)
from homeassistant.components.media_player.const import (
SUPPORT_SELECT_SOURCE, SUPPORT_TURN_OFF, SUPPORT_TURN_ON,
... |
from .sql import (
alias,
and_,
asc,
between,
bindparam,
case,
cast,
collate,
delete,
desc,
distinct,
except_,
except_all,
exists,
extract,
false,
func,
insert,
intersect,
intersect_all,
join,
literal,
literal_column,
modifi... |
"""Tests for ModelAverageOptimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import portpicker
from tensorflow.contrib.opt.python.training import model_average_optimizer
from tensorflow.python.framework import constant_op
from tensorflow.python.fr... |
"""Tests for google.protobuf.descriptor_database."""
__author__ = '<EMAIL> (Matt Toia)'
import unittest
from google.protobuf import descriptor_pb2
from google.protobuf.internal import factory_test2_pb2
from google.protobuf import descriptor_database
class DescriptorDatabaseTest(unittest.TestCase):
def testAdd(se... |
"""
Betweenness centrality measures for subsets of nodes.
"""
# Copyright (C) 2004-2015 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
__author__ = """Aric Hagberg (<EMAIL>)"""
__all__ = ['betweenness_centrality_subset',
'... |
from .bases import _StandardStemmer
from whoosh.compat import u
class GermanStemmer(_StandardStemmer):
"""
The German Snowball stemmer.
:cvar __vowels: The German vowels.
:type __vowels: unicode
:cvar __s_ending: Letters that may directly appear before a word final 's'.
:type __s_ending: un... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
VMWARE external inventory script
=================================
shamelessly copied from existing inventory scripts.
This script and it's ini can be used more than once,
i.e vmware.py/vmware_colo.ini vmware_idf.py/vmware_idf.ini
(script can be link)
so if you don'... |
import os
import sys
from telemetry import benchmark
from telemetry.internal.browser import browser_finder
sys.path.append(os.path.join(os.path.dirname(__file__), '..',
'..', 'variations'))
import fieldtrial_util # pylint: disable=import-error
class PerfBenchmark(benchmark.Benchmark):
""" Super class for all ... |
"""
The nxos lacp_interfaces fact class
It is in this file the configuration is collected from the device
for a given resource, parsed, and the facts tree is populated
based on the configuration.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import re
from copy import deepco... |
from tests import ResTest
from res.test import ErtTestContext
from ecl.util.util import BoolVector
from res.enkf import NodeId
from res.enkf import ESUpdate
from res.enkf import ErtRunContext
from res.enkf import EnkfNode
class ESUpdateTest(ResTest):
def test_create(self):
config = self.createTestPath("... |
from importlib import abc
from importlib import machinery
import inspect
import unittest
class InheritanceTests:
"""Test that the specified class is a subclass/superclass of the expected
classes."""
subclasses = []
superclasses = []
def __init__(self, *args, **kwargs):
super().__init__(... |
""" Test functions for matrix module
"""
from numpy.testing import *
from numpy import ( arange, rot90, add, fliplr, flipud, zeros, ones, eye,
array, diag, histogram2d, tri, mask_indices, triu_indices,
triu_indices_from, tril_indices, tril_indices_from )
import numpy as np
fr... |
from base64 import b64encode
from hashlib import sha1
import os
def FormatKey(key):
'''Normalize a key by making sure it has a .html extension, and convert any
'.'s to '_'s.
'''
if key.endswith('.html'):
key = key[:-len('.html')]
safe_key = key.replace('.', '_')
return '%s.html' % safe_key
def Sanitiz... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_wireless_controller_hotspot20_h2qp_osu_p... |
import time
from PyQt5 import QtGui as QG
from PyQt5 import QtWidgets as QW
from PyQt5 import QtCore as QC
import numpy as n
from lsjuicer.inout.db.sqlbase import dbmaster
from lsjuicer.resources import cm
class FramePlayer(QW.QWidget):
def __init__(self, frame_get_func, frame_set_func, frame_max_func, paren... |
from mako import compat, util
_cache_plugins = util.PluginLoader("mako.cache")
register_plugin = _cache_plugins.register
register_plugin("beaker", "mako.ext.beaker_cache", "BeakerCacheImpl")
class Cache(object):
"""Represents a data content cache made available to the module
space of a specific :class:`.Tem... |
import sys
import os
import json
import datetime
SECTION_SEPARATOR = "\n.P \n"
MANPAGE_EXTENSION = ".1"
# For now this is a magic number
# See https://www.debian.org/doc/manuals/maint-guide/dother.en.html#manpage
SECTION_NUMBER = 1
def generate_man_pages(doc_path, output_dir):
with open(doc_path) as doc_file:
... |
"""Example of Estimator for DNN-based text classification with DBpedia data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np
import pandas
from sklearn import metrics
import tensorflow as tf
from tensorflow.contrib im... |
from airflow import utils
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from datetime import datetime, timedelta
now = datetime.now()
now_to_the_hour = (now - timedelta(0, 0, 0, 0, 0, 3)).replace(minute=0, second=0, microsecond=0)
START_DATE = now_to_the_hour
DAG_NAME = 'test_dag_... |
from gnuradio import gr, gru, eng_notation, optfir
from gnuradio import audio
from gnuradio import usrp
from gnuradio import blks2
from gnuradio.eng_option import eng_option
from gnuradio.wxgui import slider, powermate
from gnuradio.wxgui import stdgui2, fftsink2, form
from optparse import OptionParser
from usrpm impor... |
from test.json_tests import PyTest, CTest
# Fri Dec 30 18:57:26 2005
JSONDOCS = [
# http://json.org/JSON_checker/test/fail1.json
'"A JSON payload should be an object or array, not a string."',
# http://json.org/JSON_checker/test/fail2.json
'["Unclosed array"',
# http://json.org/JSON_checker/test/fa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.