content stringlengths 4 20k |
|---|
"""Tests for async util methods from Python source."""
import asyncio
import time
from unittest.mock import MagicMock, Mock, patch
import pytest
from homeassistant.util import async_ as hasync
@patch("asyncio.coroutines.iscoroutine")
@patch("concurrent.futures.Future")
@patch("threading.get_ident")
def test_fire_co... |
import json
import logging
import restkit
from base import Base
logger = logging.getLogger(__name__)
class Rest(Base):
def connect(self, uri):
self.uri = uri
self.resource = restkit.Resource(self.uri)
def list(self, resource):
return self.find(resource)
def find(self, resource... |
class WebKitFinder(object):
def __init__(self, filesystem):
self._filesystem = filesystem
self._webkit_base = None
def webkit_base(self):
"""Returns the absolute path to the top of the WebKit tree.
Raises an AssertionError if the top dir can't be determined."""
# Note: ... |
"""Utils for writing tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.platform import test
from tensorflow.python.training import coordinator
from tensorflow.python.training import queue_runner_impl
class Base(test.TestCase... |
"""
Django settings for hiren project.
Generated by 'django-admin startproject' using Django 1.9.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
impo... |
from p2pool.util import math, memoize
class SkipList(object):
def __init__(self, p=0.5):
self.p = p
self.skips = {}
def forget_item(self, item):
self.skips.pop(item, None)
@memoize.memoize_with_backing(memoize.LRUDict(5))
def __call__(self, start, *args):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_selenium_astride
----------------------------------
Tests for `selenium_astride` module.
"""
from flask import Flask, render_template, redirect, url_for, request, session, flash
from flask.ext.testing import LiveServerTestCase
from selenium import webdriver
imp... |
from django.http import HttpResponse
from django.shortcuts import render
from django_nose.tools import (
assert_equal,
assert_code,
)
from mock import patch
from pontoon.base.tests import (
ProjectFactory,
ResourceFactory,
TranslationFactory,
)
from pontoon.base.tests.test_views import ViewTestC... |
from django.test import TestCase
from django.core.urlresolvers import reverse_lazy
from django.conf import settings
from django.core import mail
from django.http.response import HttpResponseRedirect
from uuid import uuid4
from bs4 import BeautifulSoup
import json
class BaseCase(TestCase, dict):
def __init__(sel... |
"""
This module contains the spatial lookup types, and the `get_geo_where_clause`
routine for Oracle Spatial.
Please note that WKT support is broken on the XE version, and thus
this backend will not work on such platforms. Specifically, XE lacks
support for an internal JVM, and Java libraries are required to use... |
import time
from st2actions.runners.pythonrunner import Action
from orionsdk import SwisClient
class OrionBaseAction(Action):
def __init__(self, config):
super(OrionBaseAction, self).__init__(config)
self.client = None
if "orion" not in self.config:
raise ValueError("Orion h... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
import time
class crm_phonecall2phonecall(osv.osv_memory):
_name = 'crm.phonecall2phonecall'
_description = 'Phonecall To Phonecall'
_columns = {
'name' : fields.char('Call summary', required=True, select=1),
'user_... |
"""
Set operations for 1D numeric arrays based on sorting.
:Contains:
ediff1d,
unique,
intersect1d,
setxor1d,
in1d,
union1d,
setdiff1d
:Notes:
For floating point arrays, inaccurate results may appear due to usual round-off
and floating point comparison issues.
Speed could be gained in some operations ... |
import volatility.obj as obj
class _KPCROnx86(obj.CType):
"""KPCR for 32bit windows"""
def idt_entries(self):
for i, entry in enumerate(self.IDT.dereference()):
yield i, entry
def gdt_entries(self):
for i, entry in enumerate(self.GDT.dereference()):
yield i, entry
... |
from keystoneclient import auth as ks_auth
from keystoneclient.auth.identity import v2 as v2_auth
from keystoneclient import session as ks_session
from novaclient import client as nova_client
from novaclient import exceptions as nova_exceptions
from oslo_config import cfg
from oslo_log import log as logging
from oslo_u... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.parsing.quoting import unquote
import pytest
UNQUOTE_DATA = (
(u'1', u'1'),
(u'\'1\'', u'1'),
(u'"1"', u'1'),
(u'"1 \'2\'"', u'1 \'2\''),
(u'\'1 "2"\'', u'1 "2"'),
(u'\'1 \'2\'\'', u'1 \'2\'')... |
import time
import pytest
from datetime import datetime
from osf_tests.factories import (
PreprintFactory,
AuthUserFactory
)
from osf.metrics import PreprintDownload
from api.base.settings import API_PRIVATE_BASE as API_BASE
@pytest.fixture()
def preprint():
return PreprintFactory()
@pytest.fixture()
d... |
import StringIO
from datetime import datetime
import smtplib
import traceback
from scrapy import signals
from scrapy import log
from nrc import settings
class FailLogger(object):
@classmethod
def from_crawler(cls, crawler):
ext = cls()
crawler.signals.connect(ext.spider_error, signal=signal... |
import sublime, sublime_plugin
STATUS = False
MOD = False
LASTKEY = ''
class SaveOnModifiedListener(sublime_plugin.EventListener):
def on_modified(self, view):
global STATUS
global MOD
if not STATUS:
return
if not MOD:
view.run_command('startime')
MOD = False
class StartimeCom... |
"""The Poisson distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.distributions.python.ops import distribution
from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.python.frame... |
import datetime
import unittest
import django
from django.test.utils import setup_test_environment
from django.test.runner import DiscoverRunner
import scraper.items
from scraper.pipelines import UpdateDBPipeline
from core.models import Source, SourceLanguage, Genre, Manga
# Configure Django to run tests outside th... |
"""
API for submitting background tasks by an instructor for a course.
Also includes methods for getting information about tasks that have
already been submitted, filtered either by running state or input
arguments.
"""
import hashlib
from celery.states import READY_STATES
from xmodule.modulestore.django import mod... |
import sys
from collections import deque
from django.utils.datastructures import SortedDict
from django.db import models
from south import exceptions
class SortedSet(SortedDict):
def __init__(self, data=tuple()):
self.extend(data)
def __str__(self):
return "SortedSet(%s)" % list(self)
... |
{
'name': 'Web Support Website Doc - Client',
'version': '8.0.1.0.0',
'category': 'Support',
'sequence': 14,
'summary': '',
'description': """
Web Support Client with Website Documentation Integration
=========================================================
TODO: check if we need this module or... |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.linalg import inv
from numpy.testing import TestCase, rand, run_module_suite, assert_raises, \
assert_equal, assert_almost_equal, assert_array_almost_equal, assert_, \
assert_allclose
from scipy.linalg import solve... |
try:
from pygments import highlight
from pygments.console import ansiformat
from pygments.formatter import Formatter
from pygments.lexer import bygroups, RegexLexer
from pygments.token import *
import sys
except ImportError, e:
print e
MONKEY_COLORS = {
Token: '',
Whitesp... |
"""
In this test the QRC file is placed in a subfolder (qrc/icons.qrc). The
Qrc5() builder should correctly strip the leading path and set the "-name"
option for the RCC executable to "icons" only.
"""
import TestSCons
test = TestSCons.TestSCons()
test.dir_fixture("image")
test.file_fixture('../../qtenv.py')
test.fil... |
"""
This code generates pie chart out of cloc summary file
"""
from pylab import *
import re
import csv
# read cloc generated file
lineno = 0
# The slices will be ordered and plotted counter-clockwise.
labels = []
fracs = []
#labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
#fracs = [15, 30, 45, 10]
#explode=(0, 0.05, 0, 0)
i... |
import WebIDL
def WebIDLTest(parser, harness):
parser.parse("""
callback interface TestCallbackInterface {
attribute boolean bool;
};
""")
results = parser.finish()
iface = results[0]
harness.ok(iface.isCallback(), "Interface should be a callback")
parser = parser.... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_... |
# -*- coding: 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 'TechnologyTag'
db.create_table('tags_technologytag', (
('id', self.gf('django.db... |
"""
Does parsing of ETag-related headers: If-None-Matches, If-Matches
Also If-Range parsing
"""
from webob.datetime_utils import *
from webob.util import header_docstring, warn_deprecation
__all__ = ['AnyETag', 'NoETag', 'ETagMatcher', 'IfRange', 'NoIfRange', 'etag_property']
def etag_property(key, default, rfc_se... |
from sqlalchemy import Column, Integer, Boolean, String
from database import Base
""" Member of Parliament """
class MP(Base):
__tablename__ = 'mps'
id = Column(Integer, primary_key=True)
first_name = Column(String(150))
last_name = Column(String(150))
party = Column(String(150))
list_mp = Colu... |
import os
import os.path
from optparse import OptionParser
import shutil
import subprocess
VALID_DEB_DIALECTS = set([
"lucid",
"squeeze"
])
def package_rpm (opts):
print "This package script does not currently support generating RPMs."
def setup_deb_dialect(dialect):
if dialect not in VALID_DEB_DIALECTS:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import pytest
from pyphi import exceptions, macro, Network, Subsystem, validate
def test_validate_direction():
with pytest.raises(ValueError):
assert validate.direction("dogeeeee")
def test_validate_tpm_wrong_shape():
tpm = np.arang... |
#!/usr/bin/env python
"""Copyright 2009 Chris Davis
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in ... |
import getpass
import sys
import os
from vbench.api import Benchmark, BenchmarkRunner
from datetime import datetime
USERNAME = getpass.getuser()
if sys.platform == 'darwin':
HOME = '/Users/%s' % USERNAME
else:
HOME = '/home/%s' % USERNAME
try:
import ConfigParser
config = ConfigParser.ConfigParser()... |
''' Provide named exceptions having to do with handling Bokeh Protocol
messages.
'''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging # isort:skip
log = logging.getLogger(__name__)... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/stable/config
# -- Path setup ------------------------------------------------------------... |
"""
dogleg algorithm with rectangular trust regions for least-squares minimization.
The description of the algorithm can be found in [Voglis]_. The algorithm does
trust-region iterations, but the shape of trust regions is rectangular as
opposed to conventional elliptical. The intersection of a trust region and
an init... |
import math
from twisted.internet import reactor
from pyspades.constants import *
from pyspades.collision import distance_3d_vector
class BaseWeapon(object):
shoot = False
reloading = False
id = None
shoot_time = None
next_shot = None
start = None
def __init__(self, reload_callback):
... |
from django.db import models
# Since the test database doesn't have tablespaces, it's impossible for Django
# to create the tables for models where db_tablespace is set. To avoid this
# problem, we mark the models as unmanaged, and temporarily revert them to
# managed during each test. We also set them to use the sam... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'FormFieldOption.label'
db.alter_column(u'customforms_f... |
"""oslo.i18n integration module.
See http://docs.openstack.org/developer/oslo.i18n/usage.html
"""
import oslo_i18n
DOMAIN = 'ceilometer'
_translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels... |
## {{{ http://code.activestate.com/recipes/286134/ (r3) (modified)
import dis
_const_codes = map(dis.opmap.__getitem__, [
'POP_TOP','ROT_TWO','ROT_THREE','ROT_FOUR','DUP_TOP',
'BUILD_LIST','BUILD_MAP','BUILD_TUPLE',
'LOAD_CONST','RETURN_VALUE','STORE_SUBSCR'
])
_load_names = ['False', 'True', 'null',... |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**Numeric module test cases.**
Contact : <EMAIL>
.. note:: 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 Free Software Foundation; ... |
TEST_BUILDINGS = [
[2, 9, 10],
[3, 7, 15],
[5, 12, 12],
[15, 20, 10],
[19, 24, 8]
]
TEST_SKYLINE = [
(2, 10),
(3, 15),
(7, 12),
(12, 0),
(15, 10),
(20, 8),
(24, 0)
]
class Solution(object):
def getSkyline(self, buildings):
"""
:type buildings: List[... |
"""Port-specific entrypoints for the layout tests test infrastructure."""
import builders # Why is this in port?
from base import Port # It's possible we don't need to export this virtual baseclass outside the module.
from driver import Driver, DriverInput, DriverOutput
from factory import port_options |
from openerp import models, fields, api, exceptions, _
class MrpProduction(models.Model):
_inherit = 'mrp.production'
@api.multi
def calc_mrp_real_cost(self):
self.ensure_one()
return sum([-line.amount for line in
self.analytic_line_ids.filtered(lambda l: l.amount < 0... |
"""
`shcol` is a shell columnizer that works in a similar way as the Unix-tool `ls`
does when rendering directory contents.
Some examples:
>>> import shcol
>>> shcol.print_filenames() # print contents of current directory
bin LICENSE MANIFEST.in setup.py testsuite
build Makefile README.md shcol
>>> shcol... |
from .main import XBMC
def start():
return XBMC()
config = [{
'name': 'xbmc',
'groups': [
{
'tab': 'renamer',
'subtab': 'metadata',
'name': 'xbmc_metadata',
'label': 'XBMC',
'description': 'Enable metadata XBMC can understand',
... |
import unittest
import glob
import os
from rts2saf.config import Configuration
from rts2saf.analyze import SimpleAnalysis, CatalogAnalysis
from rts2saf.sextract import Sextract
from rts2saf.environ import Environment
import logging
if not os.path.isdir('/tmp/rts2saf_log'):
os.mkdir('/tmp/rts2saf_log')
logging... |
# Note that the dataset must be already downloaded for this script to work, do:
# $ cd data/
# $ python download_dataset.py
# quoc_trinh
import tensorflow as tf
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from sklearn import metrics
import os
import sys
import datetime
# get current... |
import base
from solar.core import resource
from solar.core import signals
class TestResource(base.BaseResourceTest):
def test_resource_args(self):
sample_meta_dir = self.make_resource_meta("""
id: sample
handler: ansible
version: 1.0.0
input:
value:
schema: int
value: 0
""")
s... |
import os
from xml.sax.saxutils import escape
from json import JSONEncoder
from lit.BooleanExpression import BooleanExpression
# Test result codes.
class ResultCode(object):
"""Test result codes."""
# We override __new__ and __getnewargs__ to ensure that pickling still
# provides unique ResultCode objec... |
from __future__ import absolute_import
import math
from mock import Mock
from sentry.utils.cursors import build_cursor, Cursor
def build_mock(**attrs):
obj = Mock()
for key, value in attrs.items():
setattr(obj, key, value)
obj.__repr__ = lambda x: repr(attrs)
return obj
def test_build_cur... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.request
import re
import csv
initial_url = 'http://www.mr-info.ru/12017-ministr-postavil-pyaterku-nash-gorod-poluchil-pochetnuyu-gramotu-za-surdlimpiadu.html'
pages_number = 1800
all_urls = []
all_urls.append(initial_url)
downloaded_urls = []
downloaded_pa... |
# encoding: utf-8
from __future__ import unicode_literals, print_function
__all__ = ['parse']
from collections import namedtuple
from src.vm import symbols, Push
Token = namedtuple('Token', 'tag value')
EOL, OPERATOR, INTEGER, OTHER = range(4)
def tokenize(line):
'''This was much more interesting when the langu... |
# -*- coding: utf-8 -*-
'''
Created on Apr 27, 2016
@author: Aaron Ponti
'''
from ch.systemsx.cisd.openbis.dss.etl.dto.api.impl import MaximumIntensityProjectionGenerationAlgorithm
class GenericTIFFSeriesMaximumIntensityProjectionGenerationAlgorithm(MaximumIntensityProjectionGenerationAlgorithm):
'''
Custo... |
{
'name': 'Bill Time on Tasks',
'version': '1.0',
'category': 'Project Management',
'description': """
Synchronization of project task work entries with timesheet entries.
====================================================================
This module lets you transfer the entries under tasks defined ... |
"""
An ARP utility that can learn and proxy ARPs, and can also answer queries
from a list of static entries.
This adds the "arp" object to the console, which you can use to look at
or modify the ARP table.
Add ARP entries on commandline like:
arp_responder --<IP>=<MAC> --<IP>=<MAC>
Leave MAC unspecified if you wan... |
"""Upgrader for Python scripts from 1.* to 2.0 TensorFlow using SAFETY mode."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.tools.compatibility import all_renames_v2
from tensorflow.tools.compatibility import ast_edits
from tensorflow.to... |
"""Internal utilities for managing I-Spy test results in Google Cloud Storage.
See the ispy.ispy_api module for the external API.
"""
import collections
import itertools
import json
import os
import sys
import image_tools
_INVALID_EXPECTATION_CHARS = ['/', '\\', ' ', '"', '\'']
def IsValidExpectationName(expecta... |
import re
from rbtools.api.errors import APIError
from rbtools.commands import Command, CommandError, Option
from rbtools.utils.filesystem import make_tempfile
# MARKDOWN_ESCAPED_CHARS comes from markdown.Markdown.ESCAPED_CHARS. We don't
# want to have a dependency on markdown for rbtools, so we just copy it into
# ... |
import unittest
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL
if HAS_GDAL:
from django.contrib.gis.gdal import Driver, OGRException
valid_drivers = ('ESRI Shapefile', 'MapInfo File', 'TIGER', 'S57', 'DGN',
'Memory', 'CSV', 'GML', 'KML')
invalid_drivers = ('Foo ba... |
"""
Test that environment variables are ignored when --ignore-environment is
specified.
"""
import os
import TestGyp
test = TestGyp.TestGyp(format='gypd')
os.environ['GYP_DEFINES'] = 'FOO=BAR'
os.environ['GYP_GENERATORS'] = 'foo'
os.environ['GYP_GENERATOR_FLAGS'] = 'genflag=foo'
os.environ['GYP_GENERATOR_OUTPUT'] =... |
def parse_location(location):
storage_url = "/".join(location.split('/')[:-2])
container_name = location.split('/')[-2]
object_name = location.split('/')[-1]
return storage_url, container_name, object_name
def _get_attr(original):
"""Get a friendly name from an object header key."""
key = orig... |
import pickle
import mwapi
from revscoring.datasources import revision_oriented as ro
from revscoring.extractors.api.datasources import (LastUserRevDoc,
PageCreationRevDoc,
PropertySuggestionDoc,
... |
import os
import time
# Global Variables
DEBUG = False
DEVICE_EXIST = True
# Default Sample Rate Variables
SAMPLE_RATE_32P25 = 32.25
SAMPLE_RATE_62O5 = 62.5
SAMPLE_RATE_125 = 125
SAMPLE_RATE_250 = 250
SAMPLE_RATES = []
# Scale Factor
SCALE_FACTOR = 31.25
# File Locations
LRADC_BASE_DEVICE_FILE = "/sys/bus... |
import pytest
boto = pytest.importorskip("boto")
import unittest
import ansible.modules.cloud.amazon.s3 as s3
from ansible.module_utils.six.moves.urllib.parse import urlparse
class TestUrlparse(unittest.TestCase):
def test_urlparse(self):
actual = urlparse("http://test.com/here")
self.assertEqual... |
import sys
sys.dont_write_bytecode = True
import string
from module_info import *
from module_scripts import *
from process_common import *
from process_operations import *
# Lav's export_dir tweak
export_dir = '%s/' % export_dir.replace('\\', '/').rstrip('/')
def save_scripts(variable_list,variable_... |
from ._compat import PY2, filename_to_ui, get_text_stderr
from .utils import echo
class ClickException(Exception):
"""An exception that Click can handle and show to the user."""
#: The exit code for this exception
exit_code = 1
def __init__(self, message):
if PY2:
if message is n... |
# -*- coding: utf-8 -*-
"""Tests for reading with parsing only a subset of samples"""
from vcfpy import Reader, Writer, Call, UnparsedCall
def test_reading_parse_subset(tmpdir, multisample_vcf_file):
# Perform record-wise copying, saving results in records
records = []
out_path = str(tmpdir.mkdir("output... |
# doc:slow-example
"""
================================
Compute ICA components on epochs
================================
ICA is fit to MEG raw data.
We assume that the non-stationary EOG artifacts have already been removed.
The sources matching the ECG are automatically found and displayed.
Subsequently, artefact det... |
"""
Afrikaans-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
'aandag': 'attention',
'versigtig': 'caution',
'gevaar': 'danger',
'fout': 'error',
'wenk': 'hint',
'belangrik': 'important',
'nota': 'n... |
from __future__ import unicode_literals, division, absolute_import
from tests import FlexGetBase
from nose.plugins.attrib import attr
class TestRottenTomatoesLookup(FlexGetBase):
__yaml__ = """
tasks:
test:
mock:
# tests search
- {title: 'Toy Story'}
... |
from openerp.osv import fields,osv
from openerp import tools
import openerp.addons.decimal_precision as dp
class mrp_workorder(osv.osv):
_name = "mrp.workorder"
_description = "Work Order Report"
_auto = False
_columns = {
'nbr': fields.integer('# of Lines', readonly=True), # TDE FIXME master:... |
import warnings
from django.utils.deprecation import RemovedInDjango110Warning
from . import engines
from .backends.django import DjangoTemplates
from .engine import (
_context_instance_undefined, _dictionary_undefined, _dirs_undefined,
)
from .exceptions import TemplateDoesNotExist
from .loaders import base
de... |
from xml.dom import minidom
from xml.etree.ElementTree import Element, SubElement
from xml.etree import ElementTree as Etree
from eatb.utils.datetime import current_timestamp
from eatb.xml.xmlutils import prettify
from taskbackend.taskconfig import TaskConfig
class IpState(object):
"""
TaskExecutionXml clas... |
from importlib import import_module
from django.core.management.base import CommandError
from django.core.management.templates import TemplateCommand
from django.utils.crypto import get_random_string
class Command(TemplateCommand):
help = ("Creates a Django project directory structure for the given "
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
# ==============================================================
import os
import tempf... |
"""
DBUS C++ binding generator
"""
import re
import string
import sys
import os
import xml
from Cheetah.Template import Template
from optparse import OptionParser
from xml.dom.minidom import parse
class NodeBase(object):
pass
class ArgNode(NodeBase):
def __init__(self, interface_node):
NodeBase.__i... |
"""A utility that reads pieman.yml from stdin and fetches the specified attribute from it. """
import sys
from argparse import ArgumentParser
from pieman import attrs
def fail(message):
"""Writes the specified message to stderr and exits with a non-zero exit
code. """
sys.stderr.write(message + '\n')
... |
#!/usr/bin/env python
"""
Read DNA FASTA from stdin and print AA FASTA to stdout. If a minimum
ORF length is given, only print AA sequences that have an ORF of at least
that length.
Note that start and stop codons will be present in the output. If you actually
want to just output all ORFs, use extract-ORFs.py direct... |
# -*- coding: utf-8 -*-
"""
flask_script._compat
~~~~~~~~~~~~~~~~~~~~
Some py2/py3 compatibility support based on a stripped down
version of six so we don't have to depend on a specific version
of it.
:copyright: (c) 2013 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
... |
"""
==============
Non-linear SVM
==============
Perform binary classification using non-linear SVC
with RBF kernel. The target to predict is a XOR of the
inputs.
The color map illustrates the decision function learned by the SVC.
"""
print(__doc__)
import numpy as np
import matplotlib.pyplot as plt
from sklearn imp... |
"""Horizontal sharding support.
Defines a rudimental 'horizontal sharding' system which allows a Session to
distribute queries and persistence operations across multiple databases.
For a usage example, see the :ref:`examples_sharding` example included in
the source distribution.
"""
from sqlalchemy import exc as sa... |
import cStringIO
import select
import sys
import time
import unittest
import dns.name
import dns.message
import dns.name
import dns.rdataclass
import dns.rdatatype
import dns.resolver
resolv_conf = """
/t/t
# comment 1
; comment 2
domain foo
nameserver 10.0.0.1
nameserver 10.0.0.2
"""
message_text = """id 1234
o... |
from sympy import sympify, Add, ImmutableMatrix as Matrix
from sympy.core.compatibility import u, unicode
from .printing import (VectorLatexPrinter, VectorPrettyPrinter,
VectorStrPrinter)
__all__ = ['Dyadic']
class Dyadic(object):
"""A Dyadic object.
See:
http://en.wikipedia.org/w... |
"""
Library for RGB / CIE1931 coversion.
Ported and extended from Bryan Johnson's JavaScript implementation:
https://github.com/bjohnso5/hue-hacking
Copyright (c) 2014 Benjamin Knight / MIT License.
"""
import math
import random
from collections import namedtuple
# Represents a CIE 1931 XY coordinate pair.
XYPoint =... |
"""
Runs small tests.
"""
import imp
import os
import sys
import unittest
import TestGyp
test = TestGyp.TestGyp()
# Add pylib to the import path (so tests can import their dependencies).
# This is consistant with the path.append done in the top file "gyp".
sys.path.append(os.path.join(test._cwd, 'pylib'))
# Add n... |
#!/usr/bin/env python
"""
Module containing function related to serialization.
"""
import json
from typing import Any, Dict, Union, cast
import numpy as np
Serializable = Union[np.ndarray, np.int32, np.int64, np.float32, np.float64,
np.float128, set]
# A type corresponding to the JSON represent... |
__author__ = "hidehiko" |
import re
class PathnameExcluder(object):
'''Decide which pathnames to exclude from a backup. '''
def __init__(self):
self._exclude_patterns = []
self._include_patterns = []
def exclude_regexp(self, regexp):
self._exclude_patterns.append((regexp, re.compile(regexp)))
def al... |
from oslo_db.sqlalchemy import orm
import sqlalchemy
from manila.common import constants
class Query(orm.Query):
def soft_delete(self, synchronize_session='evaluate', update_status=False,
status_field_name='status'):
if update_status:
setattr(self, status_field_name, const... |
__all__ = ['CBaseLoader', 'CSafeLoader', 'CLoader',
'CBaseDumper', 'CSafeDumper', 'CDumper']
from _yaml import CParser, CEmitter
from constructor import *
from serializer import *
from representer import *
from resolver import *
class CBaseLoader(CParser, BaseConstructor, BaseResolver):
def __init__(s... |
from optparse import SUPPRESS_HELP
import os
import re
import shutil
import socket
import subprocess
import sys
import time
import xmlrpclib
try:
import threading as _threading
except ImportError:
import dummy_threading as _threading
from git_command import GIT
from git_refs import R_HEADS
from project import HEA... |
from django.shortcuts import render
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
# from userauth.forms import UserForm, UserProfileForm, ForgotForm
from maps.models import Report, Route
from django.contrib.auth import authenticate, login, logout
from django.con... |
"""
Tests for transition markers.
"""
from __init__ import DocutilsTestSupport
def suite():
s = DocutilsTestSupport.ParserTestSuite()
s.generateTests(totest)
return s
totest = {}
# See DocutilsTestSupport.ParserTestSuite.generateTests for a
# description of the 'totest' data structure.
totest['transitio... |
# -*- coding: utf-8 -*-
from trytond.pool import Pool
from wizard import (
TestMagentoConnectionStart, ImportWebsitesStart,
ExportMagentoShipmentStatusStart,
ExportMagentoShipmentStatus, ConfigureMagento, ImportStoresStart,
FailureStart, UpdateMagentoCatalogStart, UpdateMagentoCatalog,
SuccessStart,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.