content stringlengths 4 20k |
|---|
"""Support for AquaLogic sensors."""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_MONITORED_CONDITIONS, TEMP_CELSIUS, TEMP_FAHRENHEIT
from homeassistant.core import callback
import homeassistant.helpers.config_validation as cv... |
#!/usr/bin/env python2
#
# (c) Daniel Bershatsky <<EMAIL>>, 2015
#
from __future__ import print_function
from numpy import array, arange, diag, abs, max
from scipy.sparse import diags
from mod import mod
def test_make_banded_matrix_real():
pass
def test_banded_matvec():
pass
def test_make_diff2_radial_re... |
class NotFoundServer(Exception):
pass
# Administrator's login failed
class AdminLoginError(Exception):
pass
# Unknown error
class UnknownError(Exception):
import traceback
errortrace = traceback.format_exc()
# Argument error
class ArgumentsError(Exception):
def __init__(self, msg=""):
sel... |
"""xarray specific universal functions
Handles unary and binary operations for the following types, in ascending
priority order:
- scalars
- numpy.ndarray
- dask.array.Array
- xarray.Variable
- xarray.DataArray
- xarray.Dataset
- xarray.core.groupby.GroupBy
Once NumPy 1.10 comes out with support for overriding ufuncs... |
import codecs
import os
import sys
import functools
from math import exp, log
# check for arguments
if len(sys.argv) < 3:
print('Error! Not enough arguments.')
exit()
candidate_path = sys.argv[1]
ref_path = sys.argv[2]
# check path existence
if not os.path.exists(candidate_path) or not os.path.exists(ref_pat... |
"""
Test that importing vispy subpackages do not pull
in any more vispy submodules than strictly necessary.
"""
import sys
import os
from vispy.testing import (assert_in, assert_not_in, requires_pyopengl,
run_tests_if_main, assert_equal)
from vispy.util import run_subprocess
import vispy
... |
from chainer.functions.connection import local_convolution_2d
from chainer import initializers
from chainer import link
from chainer import variable
def _pair(x):
if hasattr(x, '__getitem__'):
return x
return x, x
def _conv_output_length(input_length, filter_size, stride):
output_length = input_... |
# -*- coding: utf-8 -*-
"""PyBEL implements an internal domain-specific language (DSL).
This enables you to write BEL using Python scripts. Even better,
you can programatically generate BEL using Python. See the
Bio2BEL `paper <https://doi.org/10.1101/631812>`_ and `repository <https://github.com/bio2bel/bio2bel>`_
f... |
import errno
import re
import os
import sys
import subprocess
# Note that gcc uses unicode, which may depend on the locale. TODO:
# force LANG to be set to en_US.UTF-8 to get consistent warnings.
allowed_warnings = set([
"alignment.c:327",
"mmu.c:602",
"return_address.c:62",
])
# Capture the name of th... |
from __future__ import division, absolute_import, print_function
import os
from numpy.distutils.npy_pkg_config import read_config, parse_flags
from numpy.testing import TestCase, run_module_suite, temppath
simple = """\
[meta]
Name = foo
Description = foo lib
Version = 0.1
[default]
cflags = -I/usr/include
libs = -... |
from __future__ import print_function
import multiprocessing
import os
import hashlib
import argparse
import llnl.util.tty as tty
import ectl
import ectl.cmd
from ectl import pathutil,rundeck,rundir,xhash,launchers
from ectl.rundeck import legacy
import re
from ectl import iso8601
import sys
import shutil
from ectl imp... |
import httplib
import urlparse
import urllib
class Htlogr:
def __init__(self, url):
self.DIV_VALUE = "="
self.DIV_FIELD = ";"
self.url = url
self.parsed_url = urlparse.urlparse(url)
self.conn = httplib.HTTPConnection(self.parsed_url.hostname)
self.last_error = None... |
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
__email__ = "pylearn-dev@googlegroups"
from pylearn2.testing.skip import skip_if_no_gpu
skip_if_no_gpu()
import numpy as np
from theano ... |
config = dict(
endpoints={
# This is the output side of the relay to which all other
# services can listen.
"relay_outbound": [
"tcp://127.0.0.1:4001",
],
},
# This is the address of an active->passive relay. It is used for the
# fedmsg-logger command which ... |
from openerp import api, models, _
from openerp.exceptions import Warning
import urllib
import logging
_logger = logging.getLogger(__name__)
class smsclient(models.Model):
_inherit = "sms.smsclient"
@api.model
def get_method(self):
method = super(smsclient, self).get_method()
method.appen... |
"""Functions for slicing, joining, padding, packing. Most of the code is copied from the upcoming PyTorch release and
should be removed once the new version becomes available.
"""
import numpy as np
import torch
from torch.autograd import Variable
from torch.nn.utils.rnn import pack_padded_sequence
# PyTorch code. Sh... |
# encoding: UTF-8
"""
# Copyright (c) 2015, Translation Exchange, Inc.
# 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 to use, c... |
from helpers import unittest
import luigi
import luigi.interface
from luigi.mock import MockTarget
# Calculates Fibonacci numbers :)
class Fib(luigi.Task):
n = luigi.IntParameter(default=100)
def requires(self):
if self.n >= 2:
return [Fib(self.n - 1), Fib(self.n - 2)]
else:
... |
#!/usr/bin/env python
# ---------------------------------
# This is the configuration file used by the Syndicate observer.
# It is a well-formed Python file, and will be imported into the
# observer as a Python module. This means you can run any config-
# generation code here you like, but all of the following global... |
#! /usr/bin/env python
# per rosengren 2011
from os import sep, readlink
from waflib import Logs
from waflib.TaskGen import feature, after_method
from waflib.Task import Task, always_run
def options(opt):
grp = opt.add_option_group('Bjam Options')
grp.add_option('--bjam_src', default=None, help='You can find it in ... |
import openerp.tests.common as common
from openerp.exceptions import except_orm
from datetime import datetime
from psycopg2 import IntegrityError
DB = common.DB
ADMIN_USER_ID = common.ADMIN_USER_ID
def get_simple_account_move_values(self, period_id, journal_id):
sale_product_account_id = self.ref('account.a_sale... |
from django import forms
from meadery.models import Product
from inventory.models import Warehouse, Row, Shelf, Bin, Crate, Jar
class WarehouseAdminForm(forms.ModelForm):
class Meta:
model = Warehouse
exclude = ["slug"]
class RowAdminForm(forms.ModelForm):
warehouse = forms.ModelChoiceField(... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import itertools
import tempfile
from django.core.files.storage import FileSystemStorage
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
callable_default_counter = itertools.count()
def callab... |
def remove_adjacent(nums):
# +++your code here+++
order = []
for i in nums:
if i not in order:
order.append(i)
return order
# E. Given two lists sorted in increasing order, create and return a merged
# list of all the elements in sorted order. You may modify the passed in lists.
# Ide... |
# race.py
# python3
# Ronald L. Rivest
# 2014-06-13
""" Prototype code implementing a race in split-value voting method
This code is meant to be pedagogic and illustrative of main concepts;
many details would need adjustment or filling in for a final implementation.
"""
# MIT open-source license.
# (See https... |
from zmeyka_db_models.base_db_models import *
#from zmeyka_db_models.alexey_logging import write_to_log
#from zmeyka_db_models.base_db_models import delete_users_by_page_id_timestamp
#from zmeyka_db_models.base_db_models import delete_likes_by_page_id_timestamp
#from zmeyka_db_models.base_db_models import delete_comm... |
# -*- encoding: utf-8 -*-
"""Tests for vumi.blinkenlights.heartbeat.monitor"""
import json
from twisted.internet.defer import inlineCallbacks
from vumi.persist.txredis_manager import TxRedisManager
from vumi.blinkenlights.heartbeat import storage
from vumi.blinkenlights.heartbeat import monitor
from vumi.tests.help... |
"""
Cache API class.
"""
from __future__ import print_function
import os
import shutil
from dbcollection.core.manager import CacheManager
from dbcollection.utils import nested_lookup
def cache(query=(), delete_cache=False, delete_cache_dir=False, delete_cache_file=False,
reset_cache=False, reset_path_cac... |
from groupon import Version
__author__ = "Allan Bunch"
__copyright__ = "Copyright (C) 2010 Webframeworks LLC"
__license__ = """Copyright 2010 Webframeworks LLC Licensed under the Apache
License, Version 2.0 (the "License"); you may not use this
file except in compliance with the Licen... |
from test_framework import BitcoinTestFramework
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
class InvalidateTest(BitcoinTestFramework):
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(se... |
import abc
import six
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import resource_helper
from neutron.common import exceptions as qexception
from neutron.plugins.common import constants
from neutron.services import service_base
class VPNServiceNotFound(qexcep... |
import platform
import re
import subprocess
from collections import namedtuple
from pkg_resources import get_entry_info
from ..objutils import memoize
from ..versioning import SpecifierSet, Version
__all__ = ['known_native_object_formats', 'known_platforms', 'parse_triplet',
'Platform', 'PlatformTriplet', ... |
# -*- coding: utf-8 -*-
# © Václav Šmilauer <<EMAIL>>
#
# Test case for sphere-facet interaction.
O.engines=[
ForceResetter(),
InsertionSortCollider([Bo1_Sphere_Aabb(),Bo1_Facet_Aabb()]),
#SpatialQuickSortCollider(),
InteractionLoop(
[Ig2_Facet_Sphere_Dem3DofGeom()],
[Ip2_FrictMat_FrictM... |
"""CSR Sparse Matrix Gradients."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.ops impor... |
"""Support for manual alarms controllable via MQTT."""
import copy
import datetime
import logging
import re
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
import homeassistant.util.dt as dt_util
from homeassistant.const import (
STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME... |
ns_prefix = "cim"
ns_uri = "http://iec.ch/TC57/2009/CIM-schema-cim14#Package_VoltageCompensator"
# EOF ------------------------------------------------------------------------- |
import urllib2
import json
import pandas as pd
data = {}
def num_or_dump(x):
try:
t = float(x)
except ValueError as e:
t = -9999.
return t
llave = raw_input("Ingresa la llave para la API de WUnderground: ")
for a in range(2008,2018):
d = urllib2.urlopen('http://api.wunderground.com/api/' + llave + '/history... |
""" Define constants for keys.
Each key constant is defined as a Key object, which allows comparison with
strings (e.g. 'A', 'Escape', 'Shift'). This enables handling of key events
without using the key constants explicitly (e.g. ``if ev.key == 'Left':``).
In addition, key objects that represent characters can be mat... |
#! /usr/bin/python
import sys
import os
import shutil
import pickle
import readline
import re
sys.path.insert(0, "XML2CODE")
import ystree
COMMANDS = ["help","create", "delete", "list", "restore", "load", "translate", "execute", "exit"]
RE_SPACE = re.compile('.*\s+$', re.M)
class cmdCompleter(object):
def _li... |
import cui
import curses
import lldb
import lldbutil
import re
import os
class SourceWin(cui.TitledWin):
def __init__(self, driver, x, y, w, h):
super(SourceWin, self).__init__(x, y, w, h, "Source")
self.sourceman = driver.getSourceManager()
self.sources = {}
self.filename = None... |
"""Copies a template from one zone to another."""
from baseCmd import *
from baseResponse import *
class copyTemplateCmd (baseCmd):
typeInfo = {}
def __init__(self):
self.isAsync = "true"
"""Template ID."""
"""Required"""
self.id = None
self.typeInfo['id'] = 'uuid'
... |
from typing import TYPE_CHECKING
from ...file_utils import _BaseLazyModule
_import_structure = {
"tokenization_cpm": ["CpmTokenizer"],
}
if TYPE_CHECKING:
from .tokenization_cpm import CpmTokenizer
else:
import importlib
import os
import sys
class _LazyModule(_BaseLazyModule):
"""... |
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
# Solution
# Find critical points, store in a max heap using min heap properties (-height)
#-------------------------------------------------------------------------------
import heapq
class Solution:
def getSk... |
"""
Scrapy Telnet Console extension
See documentation in docs/topics/telnetconsole.rst
"""
import pprint
import logging
import traceback
import binascii
import os
from twisted.internet import protocol
try:
from twisted.conch import manhole, telnet
from twisted.conch.insults import insults
TWISTED_CONCH_A... |
from copy import deepcopy
from cStringIO import StringIO
from os.path import isdir
from zipfile import ZIP_DEFLATED, ZIP_STORED, ZipFile, BadZipfile
# Import from lpod
from manifest import odf_manifest
from utils import _get_abspath
# Types and their default template
ODF_TYPES = {
'text': 'templates/text.ott... |
# -*- coding: utf-8 -*-
from rest_framework.pagination import \
BasePagination, _get_page_links, _get_displayed_page_numbers, \
_positive_int, _divide_with_ceil
from django.utils.translation import ugettext_lazy as _
from rest_framework.response import Response
from collections import OrderedDict
from django.te... |
from constraints.base_constraint import BaseConstraint
from collections import defaultdict
class AllEqual(BaseConstraint):
def __init__(self, variables, identifier=None):
'''
AllEqual Constraint is satisfied if all the variables are
assigned the same value.
moves_necessary is the n... |
# partial unit test for gmpy2 mpfr functionality
# relies on Tim Peters' "doctest.py" test-driver
r'''
>>> list([x for x in dir(a) if x != '__dir__'])
['__abs__', '__add__', '__bool__', '__ceil__', '__class__', '__delattr__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__... |
from datetime import datetime
import gevent.lock
import structlog
from raiden.storage.sqlite import SerializedSQLiteStorage
from raiden.transfer.architecture import Event, State, StateChange, StateManager
from raiden.utils.typing import Callable, Generic, List, Tuple, TypeVar
log = structlog.get_logger(__name__) # ... |
"""Convolutional network example.
Run the training for 50 epochs with
```
python __init__.py --num-epochs 50
```
It is going to reach around 0.8% error rate on the test set.
"""
import logging
import numpy
from argparse import ArgumentParser
from theano import tensor
from blocks.algorithms import GradientDescent, S... |
"""Import core names of TensorFlow.
Programs that want to build TensorFlow Ops and Graphs without having to import
the constructors and utilities individually can import this file:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
"""... |
# -*- coding: utf-8 -*-
# Language extension for distutils Python scripts. Based on this concept:
# http://wiki.maemo.org/Internationalize_a_Python_application
from distutils import cmd
from distutils.command.build import build as _build
import glob
import os
class build_trans(cmd.Command):
description = 'Compile .p... |
import random
from rally.common import logging
from rally.plugins.openstack import scenario
from rally.plugins.openstack.scenarios.zaqar import utils as zutils
class ZaqarBasic(zutils.ZaqarScenario):
"""Benchmark scenarios for Zaqar."""
@scenario.configure(context={"cleanup": ["zaqar"]})
@logging.log_de... |
#!/usr/bin/env python
"""
bubbleswidgetplugin.py
A bubbles widget custom widget plugin for Qt Designer.
Copyright (C) 2006 David Boddie <<EMAIL>>
Copyright (C) 2005-2006 Trolltech ASA. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Pub... |
#!/usr/bin/env python
import sys, os, random, pickle, json, codecs, time
import numpy as np
import sklearn.metrics as skm
import argparse
from model import AutumnNER
from utility import load_dataset
from utility import load_embeddings
from utility import report_performance
parser = argparse.ArgumentParser(description=... |
import types
from base import StudioTestCase
from contentcuration.models import FormatPreset
class GetPresetTestCase(StudioTestCase):
def test_accepts_string(self):
"""
Check that if we pass in a string, we won't error out.
"""
FormatPreset.get_preset("a")
def test_returns_... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class FriendLists(Choreography):
def __init__(self, temboo_session):
"""
Create a n... |
# -*- coding: utf-8 -*-
"""
(C) 2015, Niels Anders, EUBrazilCC
"""
from generic_tools import saveimg, getpoints, gridcellborders
import numpy as np
import sys, time, os.path
def calcSlope(dtm):
[r,c] = dtm.shape
print 'Calculate slope angle (%d x %d)...' % (c, r),
time.sleep(0.1)
t0 = time.... |
from __future__ import absolute_import, division, print_function, unicode_literals
class ArtifactCache(object):
"""The ArtifactCache is a small abstraction that allows caching
named things in some external storage mechanism.
The primary use case is for storing the build products on CI
systems to accel... |
import CodecManager
import StringIO
import codecs
import xml.dom.minidom
# "overriden" Document.toxml and toprettyxml to optionaly write the prolog.
def writexml(doc, prolog = True, encoding = None, indent = "", addindent = "", newl = ""):
writer = StringIO.StringIO()
if encoding is not None:
writer = codecs.loo... |
from openerp import models, api
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.multi
def recalculate_prices(self):
return self.reset_lines(price=True)
@api.multi
def recalculate_names(self):
return self.reset_lines(price=False)
@api.multi
def reset_lines(sel... |
"""
Hacks for the Django 1.0/1.0.2 releases.
"""
from django.conf import settings
from django.db.backends.creation import BaseDatabaseCreation
from django.db.models.loading import cache
from django.core import management
from django.core.management.commands.flush import Command as FlushCommand
from django.utils.datast... |
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <headingcell level=2>
# Usage of IC 74152
# <codecell>
from __future__ import print_function
from BinPy import *
# <codecell>
# Usage of IC 74152:
ic = IC_74152()
print(ic.__doc__)
# <codecell>
# The Pin configuration is:
inp = {1: 1, 2: 0, 3: 1, 4: 0, 5: ... |
from m5.objects import *
from alpha_generic import *
root = LinuxAlphaFSSystemUniprocessor(mem_mode='timing',
cpu_class=InOrderCPU).create_root() |
"""
Unit test for the hash functions.
"""
from invenio_utils.hash import md5, sha1
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
class TestHashUtils(InvenioTestCase):
"""
hashutils TestSuite.
"""
def test_md5(self):
self.assertEqual(md5('').hexdigest(),
... |
"""Myelin function builder and expression evaluator."""
import array
from .flow import set_builder_factory, Variable
DT_FLOAT32 = "float32"
DT_FLOAT64 = "float64"
DT_INT8 = "int8"
DT_INT16 = "int16"
DT_INT32 = "int32"
DT_INT64 = "int64"
DT_BOOL = "bool"
DT_INT = DT_INT32
DT_FLOAT = DT_FLOAT32
DT_DOUBLE = DT_FLOAT64... |
import os
import config
from constants import DNA_ALPHABET
def mutant_variants_dir_by_idx(mutant_idx):
"""Simplify directory retrieval for the pam_variants folder in a specific mutant directory
Args:
mutant_idx: int >= 0 (0 is default dCas9)
Returns:
path to the pam variants directory for... |
import sys
if sys.version_info < (2, 6):
print(sys.stderr, "{}: need Python 2.6 or later.".format(sys.argv[0]))
print(sys.stderror, "Your python is {}".format(sys.version))
sys.exit(1)
from setuptools import setup, find_packages
execfile('yamlformatter/__version__.py')
setup(
name = "python-yaml-logg... |
# coding: utf-8
import csv
import sys
import json
import os
import datetime
import urllib
import requests
import time
import argparse
from tqdm import tqdm
bizcircle_url = 'http://ajax.lianjia.com/ajax/mapsearch/area/bizcircle?city_id={code}'
circle_url = 'http://ajax.lianjia.com/ajax/housesell/area/bizcircle?ids={id... |
from datetime import datetime
import olympia.core.logger
from olympia.amo.celery import task
from olympia.amo.decorators import write
from olympia.users.models import UserProfile
log = olympia.core.logger.getLogger('z.accounts')
@task
@write
def primary_email_change_event(email, uid, timestamp):
"""Process th... |
"""MSAView - Fast and flexible visualisation of multiple sequence alignments.
Copyright (c) 2011 Joel Hedlund.
Contact: Joel Hedlund <<EMAIL>>
MSAView is a modular, configurable and extensible package for analysing and
visualising multiple sequence alignments and sequence features. It can import
and display data f... |
import maps
from tendrl.commons.objects.gluster_peer import GlusterPeer
def test_gluster_peer():
NS.tendrl_context = maps.NamedDict()
NS.tendrl_context.integration_id = '77deef29-b8e5-4dc5-8247-21e2a'\
'409a66a'
obj = GlusterPeer(
state="['Peer', 'Cluster',... |
import responses
from requests.exceptions import HTTPError
from gitlab_tests.base_test import BaseTest
from response_data.users import *
class TestGetUsers(BaseTest):
@responses.activate
def test_get_users(self):
responses.add(
responses.GET,
self.gitlab.api_url + '/users',
... |
"""
Description of satin.py
======================
API for SATIN database
:Example:
python satin.py
"""
import re
import os
import sys
import csv
import argparse
from datetime import date
import matplotlib as mpl
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import cartopy.io.shap... |
"""
File: commthread.py
Author: Jesse DeGuire
Contains a class for talking to the devices over a serial port and for the commands it will accept.
"""
import serial
from PySide import QtCore
from PySide.QtCore import QObject
from pjcbootloader import PJCBootloader
from pjcapplication import PJCApplication
from fla... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from preggy import expect
from tornado.testing import gen_test
from tornado import gen
from tornado.httpclient import HTTPError
from ujson import dumps, loads
from mock import Mock, patch
from tests.unit.base import ApiTestCase
from tests.fixtures import UserFactory
from hol... |
# -*- coding: utf-8 -*-
import pytest
import sys
from .test_base_class import TestBaseClass
from aerospike import exception as e
aerospike = pytest.importorskip("aerospike")
try:
import aerospike
except:
print("Please install aerospike python client.")
sys.exit(1)
class TestGetNodes(object):
def se... |
import logging
from pinger.app import get_current_app
from pinger.ext import ActionProvider
from pinger.ext.variables import interpolate_path
class Log(ActionProvider):
"""
Receives a response and logs it. Creates the parent folder if it doesnt exists.
Expects the following settings:
```
{"plug... |
# een eerste test om door de flowchart te lopen
from lxml import etree as ElementTree
from xml_element_traverser import XMLElementTraverser, Iteration
import re
class XMLElementVisitor(object):
# define explicit constructor (overruling the default constructur) with one parameter
def __init__(self, plain_text_f... |
""" contains helper functions for common irc commands """
import random
def msg(cli, user, msg):
for line in msg.split('\n'):
cli.send("PRIVMSG", user, ":%s" % line)
def msgrandom(cli, choices, dest, user=None):
o = "%s: " % user if user else ""
o += random.choice(choices)
msg(cli, dest, o)
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import *
from django.test import TestCase
from django.utils.safestring import mark_safe
class AssertFormErrorsMixin(object):
def assertFormErrors(self, expected, the_cal... |
import unittest
from contextlib import contextmanager
from io import StringIO
from unittest import mock
from django.db import DatabaseError, connection
from django.db.backends.base.creation import BaseDatabaseCreation
from django.test import SimpleTestCase
try:
import psycopg2 # NOQA
except ImportError:
pass... |
"""Tests for perfkitbenchmarker.custom_virtual_machine_spec."""
import unittest
from perfkitbenchmarker import custom_virtual_machine_spec
from perfkitbenchmarker import errors
import six
_COMPONENT = 'test_component'
_FLAGS = None
_STRING_TYPE_NAME = six.string_types[0].__name__
class MemoryDecoderTestCase(unit... |
from abc import ABCMeta
from abc import abstractmethod
from common.tools import log_check_call
from common.fsm_proxy import FSMProxy
from ..exceptions import PartitionError
class AbstractPartitionMap(FSMProxy):
__metaclass__ = ABCMeta
events = [{'name': 'create', 'src': 'nonexistent', 'dst': 'unmapped'},
... |
from __future__ import print_function
from operator import itemgetter
import mxnet as mx
import numpy as np
def nce_loss(data, label, label_weight, embed_weight, vocab_size, num_hidden):
label_embed = mx.sym.Embedding(data=label, input_dim=vocab_size,
weight=embed_weight,
... |
""" Tests for coprs messages """
import unittest
from fedmsg.tests.test_meta import Base
from .common import add_doc
_long_copr_end = """Package: mutt-kz-1.5.23.1-1.20150203.git.c8504a8a.fc21
COPR: fatka/mutt-kz
Built by: fatka
Status: success
ID: 00000100
Logs:
Build: https://copr-be.cloud.fed... |
"""Virtual Servers."""
# :license: MIT, see LICENSE for more details.
import re
import click
MEMORY_RE = re.compile(r"^(?P<amount>[0-9]+)(?P<unit>g|gb|m|mb)?$")
class MemoryType(click.ParamType):
"""Memory type."""
name = 'integer'
def convert(self, value, param, ctx): # pylint: disable=inconsistent-... |
"""
Support for X10 lights.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.x10/
"""
import logging
from subprocess import check_output, CalledProcessError, STDOUT
import voluptuous as vol
from homeassistant.const import (CONF_NAME, CONF_ID, CONF_... |
# -*- 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 ------------------------------------------------------------... |
import pygtk
pygtk.require('2.0')
import gtk
class InfoFrameComponent:
"""
Base class for everything that writes to the infoFrame.
These
"""
baseWidget = None #The widget pushed to the infoFrame (usually a container)
frameManager = None
#isActive = False
def __init__(self, frameManag... |
"""Make sure that existing Koogeek LS1 support isn't broken."""
import os
from datetime import timedelta
from unittest import mock
import pytest
from homekit.exceptions import AccessoryDisconnectedError, EncryptionError
import homeassistant.util.dt as dt_util
from homeassistant.components.light import SUPPORT_BRIGHT... |
"""
Create outline.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities.geometry.creation import lineation
from fabmetheus_uti... |
"""
Consider the fraction, n/d, where n and d are positive integers. If n<d and
HCF(n,d)=1, it is called a reduced proper fraction.
If we list the set of reduced proper fractions for d <= 8 in ascending order of
size, we get:
1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7,
3/4, 4/5, 5/... |
# -*- coding: utf-8 -*-
from django.db import models
import waffle
import jsonschema
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
from osf.models.validators import RegistrationResponsesValidator
from osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField
from osf.... |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
######################################################################
import re
import htmlentitydefs
######################################################################
emoticon_string = r"""
(?:
[<>]?
[:;=8] # eyes
[\-o\... |
from grow.pods import env
import os
import unittest
TESTDATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata', 'pod')
class EnvTest(unittest.TestCase):
def test_constructor_basic(self):
config = env.EnvConfig(host='localhost')
environment = env.Env(config)
self.assertEqual('local... |
# -*- coding ascii -*-
__pyspec = 1
import sys
STDOUT = 0
STDERR = 1
CONTEXT_INFO = 2
DATA_PROVIDER_INFO = 3
REPORT_OUT = 4
if sys.platform == "cli":
import System
import System.IO
class DotNetStdOutTransfer(System.IO.TextWriter):
def __init__(self):
super(DotNetStdOutTransfer, se... |
import os
import sys
import unittest
import api_schema_graph
from availability_finder import AvailabilityFinder, AvailabilityInfo
from branch_utility import BranchUtility, ChannelInfo
from compiled_file_system import CompiledFileSystem
from fake_host_file_system_provider import FakeHostFileSystemProvider
from fake_url... |
"""Basic checks for HomeKitalarm_control_panel."""
from aiohomekit.model.characteristics import CharacteristicsTypes
from aiohomekit.model.services import ServicesTypes
from tests.components.homekit_controller.common import setup_test_component
CURRENT_STATE = ("security-system", "security-system-state.current")
TARG... |
""" XVM (c) www.modxvm.com 2013-2015 """
#############################
# Command
def onHangarInit():
# debug
#runTest(('battleResults', '4806765629906229.dat'))
pass
def runTest(args):
if args is None:
return
cmd = args[0]
if cmd == 'battleResults':
_showBattleResults(int(ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.