content stringlengths 4 20k |
|---|
{
'name': 'Intrastat Reporting',
'version': '1.0',
'category': 'Accounting & Finance',
'description': """
A module that adds intrastat reports.
=====================================
This module gives the details of the goods traded between the countries of
European Union.""",
'author': 'OpenERP SA'... |
from hachoir_core.i18n import _
from hachoir_core.tools import (
humanDuration, humanBitRate,
humanFrequency, humanBitSize, humanFilesize,
humanDatetime)
from hachoir_core.language import Language
from hachoir_metadata.filter import Filter, NumberFilter, DATETIME_FILTER
from datetime import date, datetime, ... |
"""Config flow for Elk-M1 Control integration."""
import logging
from urllib.parse import urlparse
import elkm1_lib as elkm1
import voluptuous as vol
from homeassistant import config_entries, exceptions
from homeassistant.const import (
CONF_ADDRESS,
CONF_HOST,
CONF_PASSWORD,
CONF_PROTOCOL,
CONF_T... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 1 16:54:05 2016
@author: alex
"""
import numpy as np
def main():
posList = generate_benzene_sites()
nList,zList = get_neighbors()
return posList, nList, zList
def generate_benzene_sites():
"""Generate the locations of a benzene r... |
import os
import os.path
import shutil
import tempfile
import re
# ===========================================
# Support method
def assemble_from_fragments(src_path, delimiter=None, compiled_regexp=None, ignore_hidden=False):
''' assemble a file from a directory of fragments '''
tmpfd, temp_path = tempfile.mk... |
"""HTTP proxy for opening RPC connection to bitcoind.
AuthServiceProxy has the following improvements over python-jsonrpc's
ServiceProxy class:
- HTTP connections persist for the life of the AuthServiceProxy object
(if server supports HTTP/1.1)
- sends protocol 'version', per JSON-RPC 1.1
- sends proper, incrementi... |
#!/usr/bin/python
"""Build App Engine source package.
"""
import json
import optparse
import os
import shutil
import subprocess
import sys
import test_file_herder
USAGE = """%prog src_path dest_path
Build the GAE source code package.
src_path Path to the source code root directory.
dest_path Path to the roo... |
"""Smoke tests for the ``UI`` end-to-end scenario."""
from fauxfactory import gen_string, gen_ipaddr
from robottelo import manifests
from robottelo.config import settings
from robottelo.constants import (
ANY_CONTEXT,
DEFAULT_LOC,
DEFAULT_ORG,
DEFAULT_SUBSCRIPTION_NAME,
DOMAIN,
FAKE_0_PUPPET_RE... |
#!/usr/bin/env python
import re
import simplejson
import os.path as op
from boutiques.validator import DescriptorValidationError
from boutiques.logger import raise_error, print_info
# BIDS validation module
def validate_bids(descriptor, valid=False):
if not valid:
msg = "Please provide a Boutiques descr... |
"""Tests for VectorSinhArcsinhDiag."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib import distributions
from tensorflow.contrib.distributions.python.ops import test_util
from tensorflow.python.platform import t... |
from nose.plugins.attrib import attr
from neon.backends.cpu import CPU
from neon.layers import FCLayer
from neon.params import IdentityValGen
from neon.util.testing import assert_tensor_equal
nin = 3
nout = 2
batch_size = 10
def check_fprop(layer, backend):
inputs = backend.ones((nin, batch_size))
output = ... |
"""bluesky.extrafilewriters.firescsvs
Writes fire emissions csv file in the form:
fire_id,hour,ignition_date_time,date_time,area_fract,flame_profile,smolder_profile,residual_profile,pm25_emitted,pm10_emitted,co_emitted,co2_emitted,ch4_emitted,nox_emitted,nh3_emitted,so2_emitted,voc_emitted,pm25_flame,pm10_flame,c... |
import json, re
from PyQt4.QtGui import (QSyntaxHighlighter, QTextCharFormat, QFont)
from PyQt4.QtCore import Qt
from supertux.highlighter import SuperTuxHighlighter, HighlightingRule
class SuperTuxLispHighlighter(SuperTuxHighlighter):
@staticmethod
def clean_text(text):
state = 0
tiles = t... |
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed, add_domain
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404
from django.utils.feedgenerator i... |
import contextlib
import tempfile
import unittest
import numpy
import chainer
from chainer.backends import cuda
from chainer import configuration
from chainer import functions
from chainer import testing
from chainer.testing import attr
class TestReporter(unittest.TestCase):
def test_empty_reporter(self):
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'curated'}
try:
from msrestazure.azure_exceptions import CloudError
from azure.mgmt.network.mode... |
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
EC2 = get_driver(Provider.EC2)
Rackspace = get_driver(Provider.RACKSPACE)
drivers = [EC2('access key id', 'secret key', region='us-east-1'),
Rackspace('username', 'api key', region='iad')]
nodes = [driver.list_no... |
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 ByAddress(Choreography):
def __init__(self, temboo_session):
"""
Create a new... |
import mock
from neutron.api.rpc.handlers import dvr_rpc
from neutron.tests import base
class DVRServerRpcApiTestCase(base.BaseTestCase):
def setUp(self):
self.client_p = mock.patch.object(dvr_rpc.n_rpc, "get_client")
self.client = self.client_p.start()
self.rpc = dvr_rpc.DVRServerRpcApi... |
def join_outer(self,
right,
left_on,
right_on=None):
"""
join_outer performs outer join operation on one or two frames, creating a new frame.
Parameters
----------
:param right: (Frame) Another frame to join with
:param left_on: (List[str]) Names o... |
"""
Automatically find data aggregation window and suggest whether to use TimeOfDay
and DayOfWeek encoder.
Example usage:
(timestamps, values) = read_csv_files('example_data/art_daily_flatmiddle.csv')
(med_sampling_interval, new_sampling_interval, useTimeOfDay,
useDayOfWeek) = get_suggested_timescale_and_encoder(ti... |
"""
Module containing some JavaScript resources.
"""
from __future__ import unicode_literals
bootstrap_js = """
if(typeof GM_xmlhttpRequest === "undefined") {
GM_xmlhttpRequest = function(/* object */ details) {
details.method = details.method.toUpperCase() || "GET";
if(!details.url) {
... |
from __future__ import absolute_import
import shlex
from ..config import config
bin_default = config.get('ffmpeg', 'bin')
probe = config.get('ffmpeg', 'probe')
def _input_cmd(cmd_input, input, add_probe=True, bin=None, add_bin=True):
""" Base of FFmpeg command with a single input.
"""
if add_bin:
... |
import webob.exc
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
class FoxInSocksController(object):
def index(self, req):
return "Try to say this Mr. Knox, sir..."
class FoxInSocksServerControllerExtension(wsgi.Controller):
@wsgi.action('add_tweedle')
def _add_tw... |
import rb
import gi
gi.require_version("Gst", "0.11")
from gi.repository import RB
from gi.repository import GObject, Gio, Gst
import config
import gettext
gettext.install('rhythmbox', RB.locale_dir())
EPSILON = 0.001
class ReplayGainPlayer(object):
def __init__(self, shell):
# make sure the replaygain elements... |
"""Regular expression based JavaScript parsing classes."""
__author__ = ('<EMAIL> (Robert Walker)',
'<EMAIL> (Andy Perelson)')
import copy
import re
from closure_linter import javascripttokens
from closure_linter.common import matcher
from closure_linter.common import tokenizer
# Shorthand
Type = java... |
from __future__ import absolute_import, unicode_literals
from django.contrib.auth.models import User, Permission
from django.contrib.comments import signals
from django.contrib.comments.models import Comment, CommentFlag
from django.contrib.contenttypes.models import ContentType
from django.utils import translation
f... |
"""Code related to bar charts."""
import copy
import warnings
from graphy import common
from graphy import util
class BarsStyle(object):
"""Style of a series of bars in a BarChart
Object Attributes:
color: Hex string, like '00ff00' for green
"""
def __init__(self, color):
self.color = color
clas... |
import re
import subprocess
# import feature, taskgen_method, before_method, task_gen
from waflib import TaskGen, Node, Task, Utils, Build, Options, Logs, Task
debug = Logs.debug
error = Logs.error
import shellcmd
#shellcmd.subprocess = pproc # the WAF version of the subprocess module is supposedly less buggy
shellcm... |
from __future__ import (absolute_import, division)
__metaclass__ = type
from units.compat import unittest
from ansible.module_utils.basic import heuristic_log_sanitize
class TestHeuristicLogSanitize(unittest.TestCase):
def setUp(self):
self.URL_SECRET = 'http://username:pas:<EMAIL>/data'
self.SSH... |
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT # <-- ADD THIS LINE
import logging.handlers
import config
def create_db(user_name, password):
# check if database doesn't already exists
try:
con = psycopg2.connect(dbname='postgres',
user=user_n... |
from suds import *
from suds.sax import Namespace, splitPrefix
def qualify(ref, resolvers, defns=Namespace.default):
"""
Get a reference that is I{qualified} by namespace.
@param ref: A referenced schema type name.
@type ref: str
@param resolvers: A list of objects to be used to resolve types.
... |
"""\
Augment the "bgen" package with definitions that are useful on the Apple Macintosh.
Intended usage is "from macsupport import *" -- this implies all bgen's goodies.
"""
# Import everything from bgen (for ourselves as well as for re-export)
from bgen import *
# Simple types
Boolean = Type("Boolean", "b")
Signe... |
import pytest
from concepts import tools
def test_maximal():
items = map(frozenset, ((1,), (2,), (3,), (1, 2)))
assert set(tools.maximal(items)) == {frozenset([3]), frozenset([1, 2])}
def test_sha256sum(tmp_path):
filepath = tmp_path / 'spam.txt'
filepath.write_text('spam', encoding='ascii')
r... |
from south.db import db
from django.db import models
from mysite.profile.models import *
class Migration:
no_dry_run = True
def forwards(self, orm):
# Adding field 'DataImportAttempt.stale'
db.add_column('profile_dataimportattempt', 'stale', orm['profile.dataimportattempt:stale'])
... |
import pytest
import math as m
import numpy as np
from sisl import Geometry, Atom, SuperCell
from sisl.geometry import sgeom
@pytest.fixture
def setup():
class t():
def __init__(self):
bond = 1.42
sq3h = 3.**.5 * 0.5
self.sc = SuperCell(np.array([[1.5, sq3h, 0.],
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_... |
from openerp.osv import osv
class account_voucher_populate_statement(osv.osv_memory):
_inherit = "account.voucher.populate.statement"
def get_statement_line_new(self,cr,uid,voucher,statement,context=None):
res = super(account_voucher_populate_statement,self).get_statement_line_new(cr,uid,voucher,state... |
"""Provides the :class:`~sqlalchemy.engine.url.URL` class which encapsulates
information about a database connection specification.
The URL object is created automatically when
:func:`~sqlalchemy.engine.create_engine` is called with a string
argument; alternatively, the URL is a public-facing construct which can
be us... |
"""
10. One-to-one relationships
To define a one-to-one relationship, use ``OneToOneField()``.
In this example, a ``Place`` optionally can be a ``Restaurant``.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_co... |
from sos.report.plugins import UbuntuPlugin
from sos.policies.distros.debian import DebianPolicy
import os
class UbuntuPolicy(DebianPolicy):
distro = "Ubuntu"
vendor = "Canonical"
vendor_urls = [
('Community Website', 'https://www.ubuntu.com/'),
('Commercial Support', 'https://www.canonic... |
from urlparse import urlparse
from cStringIO import StringIO
try:
from boto.s3.connection import S3Connection
from boto.s3.key import Key
except ImportError:
def open_url(url, offset=None, length=None):
raise ImportError('boto')
def list_files(prefix):
raise ImportError('boto')
else:
... |
import datetime
import time
from openerp.osv import osv
from openerp.tools.translate import _
from openerp.report import report_sxw
from openerp.tools.safe_eval import safe_eval as eval
#
# Use period and Journal for selection or resources
#
class report_assert_account(report_sxw.rml_parse):
def __init__(self, c... |
import time
import urllib
import socket
from xml.dom import minidom
from twisted.web import http
from twisted.web import static
from twisted.web import resource
import txlb
from txlb import util
from txlb.admin import css
from txlb.admin import template
class UnauthorizedResource(resource.Resource):
"""
The... |
"""SAVEE dataset."""
import collections
import os
import re
import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_datasets.public_api as tfds
LABEL_MAP = {
'a': 'anger',
'd': 'disgust',
'f': 'fear',
'h': 'happiness',
'n': 'neutral',
'sa': 'sadness',
'su': 'surprise',
}
SP... |
#coding=UTF-8
from pyspark import SparkContext, SparkConf, SQLContext, Row, HiveContext
from pyspark.sql.types import *
from datetime import date, datetime, timedelta
import sys, re, os
st = datetime.now()
conf = SparkConf().setAppName('PROC_F_CI_SUN_IND_INFO_TMP').setMaster(sys.argv[2])
sc = SparkContext(conf = conf)... |
from optparse import make_option
from django.core.management.base import CommandError
from django.core.management.commands.inspectdb import Command as InspectDBCommand
class Command(InspectDBCommand):
db_module = 'django.contrib.gis.db'
gis_tables = {}
def get_field_type(self, connection, table_name, row... |
# -*- coding: utf-8 -*-
import datetime
import json
import logging
import select
import threading
import time
import random
import simplejson
import openerp
from openerp.osv import osv, fields
from openerp.http import request
from openerp.tools.misc import DEFAULT_SERVER_DATETIME_FORMAT
_logger = logging.getLogger(__... |
'''
xbmcswift2.request
------------------
This module contains the Request class. This class represents an incoming
request from XBMC.
:copyright: (c) 2012 by Jonathan Beluch
:license: GPLv3, see LICENSE for more details.
'''
from xbmcswift2.common import unpickle_args
import urlparse
try:
... |
######################################################################
# This file should be kept compatible with Python 2.3, see PEP 291. #
######################################################################
import sys, os
# find_library(name) returns the pathname of a library, or None.
if os.name == "nt":
d... |
from mantid.kernel import *
from mantid.dataobjects import PeaksWorkspaceProperty
from mantid.api import *
from mantid.simpleapi import *
import fractional_indexing as indexing
class FindSatellitePeaks(DataProcessorAlgorithm):
def category(self):
return 'Crystal\\Peaks'
def seeAlso(self):
re... |
import json
import logging
from django.utils import html
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.debug import sensitive_variables # noqa
from oslo_utils import strutils
import six
from horizon import exceptions
from horizon import forms
from horizon import messages
from... |
# -*- coding: utf-8 -*-
import json
import logging
import pprint
import werkzeug
from odoo import http
from odoo.http import request
_logger = logging.getLogger(__name__)
class AdyenController(http.Controller):
_return_url = '/payment/adyen/return/'
@http.route([
'/payment/adyen/return',
], ty... |
"""
Definitions of test cases with various interesting error-related behaviors, to
be used by test modules to exercise different features of trial's test runner.
See the L{twisted.trial.test.test_tests} module docstring for details about how
this code is arranged.
"""
from __future__ import division, absolute_import
... |
# -*- coding: utf-8 -*-
import rayeval
import time
if __name__ == '__main__':
# rayeval.load_handranks('HandRanks.dat')
rayeval.load_handranks_9('/usr/local/shared/rayeval_hand_ranks_9.dat')
board = 'Ks Jd 9d * *'
pockets = ['9s Kd 4d 6c']
iterations = 1e6
t0 = time.time()
ngbb = rayeval... |
"""
Tests common to genericpath, macpath, ntpath and posixpath
"""
import genericpath
import os
import sys
import unittest
import warnings
from test import support
def safe_rmdir(dirname):
try:
os.rmdir(dirname)
except OSError:
pass
class GenericTest:
common_attributes = ['commonprefix'... |
"""Tests for wrappers._linalg"""
import math
import numpy as np
import pybayes.wrappers._linalg as linalg
from support import PbTestCase
def test_inv_func(self):
"""Work-around so that this function can be annotated in .pxd"""
# source data
arrays = [
np.array([[ 2.]]),
np.array([[ 0., ... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'OAuthToken.remote_ip'
db.add_column('feed_import_oauthtoken', 'remote_ip', self.gf('django... |
import itertools
import logging
from logging import NullHandler
from mock import Mock, patch
import multiprocessing
from nose import with_setup
from nose.tools import eq_, raises, timed, nottest
import ui.graphical.visualisation
from ui.graphical.visualisation import *
from ui.graphical.visualisation import Visualisabl... |
from weboob.tools.backend import Module
from weboob.capabilities.housing import CapHousing, Housing, HousingPhoto
from .browser import ExplorimmoBrowser
__all__ = ['ExplorimmoModule']
class ExplorimmoModule(Module, CapHousing):
NAME = 'explorimmo'
DESCRIPTION = u'explorimmo website'
MAINTAINER = u'Bezl... |
from django.http import HttpResponse
from push_notifications.models import APNSDevice, GCMDevice
from rest_framework.views import APIView
import json
from .models import *
from .serializers import *
class AddIosDeviceView(APIView):
"""
Add iOS device.
device -- Device parameter (format string)
"""
... |
# -*- encoding: utf-8 -*-
import argparse
import multiprocessing
import os
from abjad.tools import systemtools
from abjad.tools.developerscripttools.DirectoryScript import DirectoryScript
class PyTestScript(DirectoryScript):
r'''Runs pytest on various Abjad paths.
.. shell::
ajv test --help
''... |
import time
import numpy as np
import pyopencl as cl
gpu_idx = 0
platforms = cl.get_platforms()
i = 0
for platform in platforms:
gpu_devices = platform.get_devices(device_type=cl.device_type.GPU)
if gpu_idx < i + len(gpu_devices):
ctx = cl.Context(devices=[gpu_devices[gpu_idx - i]])
break
... |
__version__ = ''' $Id $ '''
__doc__='''Execute this script to see some test drawings.
This contains a number of routines to generate test drawings
for reportlab/graphics. For now many of them are contrived,
but we will expand them to try and trip up any parser.
Feel free to add more.
'''
import os, sys
from reportl... |
# -*- coding: utf-8 -*-
"""This class contains utility functions used internally by SoCo."""
from __future__ import (
absolute_import, print_function, unicode_literals
)
import functools
import re
import warnings
from .compat import (
StringType, UnicodeType, quote_url
)
from .xml import XML
def really_un... |
"""
Obfuscated, pure C windows/meterpreter/reverse_tcp
Implements various randomized string processing functions in an
attempt to obfuscate the call tree.
Inspiration from https://github.com/rsmudge/metasploit-loader
Module built by @harmj0y
"""
import random
from modules.common import helpers
class Payload:
... |
#!/usr/bin/env python
from __future__ import print_function
import abc
import traceback
from threading import Thread
import os
import time
import configparser
import errno
import subprocess
import sys
import logging
import requests
_base_path = os.path.dirname(os.path.abspath(__file__))
def eprint(*args, **kwargs):... |
import logging
import sys
import eventlet
from eventlet.green import threading as greenthreading
from eventlet import greenpool
import greenlet
from oslo_utils import excutils
from oslo_messaging._executors import base
from oslo_messaging import localcontext
LOG = logging.getLogger(__name__)
def spawn_with(ctxt, p... |
"""Convenience wrapper around Keras' MNIST and Fashion MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v2 as tf
INPUT_SHAPE = (28, 28, 1)
NUM_CLASSES = 10
def _load_random_data(num_train_and_test... |
"""
Readability OAuth1 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/readability.html
"""
from social.backends.oauth import BaseOAuth1
READABILITY_API = 'https://www.readability.com/api/rest/v1'
class ReadabilityOAuth(BaseOAuth1):
"""Readability OAuth authentication backend"""
name = 'rea... |
# -*- coding: utf-8 -*-
#
# Layouts Unit Tests
#
# To run this script use:
# python web2py.py -S eden -M -R applications/eden/modules/unit_tests/modules/s3layouts.py
#
import unittest
from gluon import current
from s3.s3layouts import homepage, S3AddResourceLink
# =====================================================... |
import mock
from nova import objects
from nova.tests.unit.objects import test_objects
FAKE_UUID = '0C5C9AD2-F967-4E92-A7F3-24410F697440'
class _TestNetworkRequestObject(object):
def test_basic(self):
request = objects.NetworkRequest()
request.network_id = '456'
request.address = '1.2.3.... |
import contextlib
class VirtAPI(object):
def provider_fw_rule_get_all(self, context):
"""Get the provider firewall rules
:param context: security context
"""
raise NotImplementedError()
@contextlib.contextmanager
def wait_for_instance_event(self, instance, event_names, dea... |
"""Chromium presubmit script for src/base.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into gcl.
"""
def _CheckNoInterfacesInBase(input_api, output_api):
"""Checks to make sure no files in libbase.a have |@interface|."""
pattern = input_a... |
import stock_invoice_directly
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""
Github (It)
@website https://github.com/
@provide-api yes (https://developer.github.com/v3/)
@using-api yes
@results JSON
@stable yes (using api)
@parse url, title, content
"""
from urllib import urlencode
from json import loads
from cgi import escape
# engine dependent config
catego... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_msg
version_added: "2.3"
short_description: Sends a message to logged in users on Windows hosts.
description:
- Wraps the msg.exe command ... |
"""Load plugins
"""
from stevedore import extension
from healing import exceptions
from healing import task_scheduler as scheduler
from healing.handler_plugins import plugin_config
from healing.openstack.common import log
from healing.openstack.common import threadgroup
LOG = log.getLogger(__name__)
CURRENT_HANDLE... |
from __future__ import unicode_literals
import re
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _, ungettext_lazy
from django.utils.encoding import force_text
from django.utils.ipv6 import is_valid_ipv6_add... |
"""Various tools used by MIME-reading or MIME-writing programs."""
import os
import rfc822
import tempfile
__all__ = ["Message","choose_boundary","encode","decode","copyliteral",
"copybinary"]
class Message(rfc822.Message):
"""A derived class of rfc822.Message that knows about MIME headers and
co... |
"""Formatters for the MSIE WebCache ESE database events."""
from plaso.lib import eventdata
class MsieWebCacheContainerEventFormatter(eventdata.ConditionalEventFormatter):
"""Formatter for a MSIE WebCache ESE database Container_# table record."""
DATA_TYPE = 'msie:webcache:container'
FORMAT_STRING_PIECES = [... |
# -*- coding: utf-8 -*-
"""
homeassistant.components.sensor.rpi_gpio
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Allows to configure a binary state sensor using RPi GPIO.
Note: To use RPi GPIO, Home Assistant must be run as root.
sensor:
platform: rpi_gpio
pull_mode: "UP"
value_high: "Active"
value_low: "Inactive... |
"""Implementation of tr-181 Device.ManagementServer hierarchy of objects.
Handles the Device.ManagementServer portion of TR-181, as described
in http://www.broadband-forum.org/cwmp/tr-181-2-2-0.html
"""
__author__ = '<EMAIL> (Denton Gentry)'
import tr.core
import tr.tr098_v1_4
import tr.tr181_v2_2
BASEMGMT181 = tr.... |
"""Quoted-printable content transfer encoding per RFCs 2045-2047.
This module handles the content transfer encoding method defined in RFC 2045
to encode US ASCII-like 8-bit data called `quoted-printable'. It is used to
safely encode text that is in a character set similar to the 7-bit US ASCII
character set, but that... |
#!/usr/bin/env python
# Input: .stem file (tsv: surface form, lemma, pos-tag, morphanas delimited by "||")
# Output: .stem file with only 1 ana in the last column (see heuristics below) and the lemma column is the lemma from the chosen ana
import sys
def get_lemma(ana, surf):
'''Return the lemma for an ana: eithe... |
from rdkit import Chem
from rdkit.Chem import rdSLNParse
from rdkit import Geometry
from rdkit import RDConfig
import unittest
import os,sys
class TestCase(unittest.TestCase) :
def setUp(self):
self.dataDir = os.path.join(RDConfig.RDBaseDir,'Code','GraphMol','SLNParse','testData')
def test1Basics(self):
m... |
"""Sample running boilerplate."""
__author__ = '<EMAIL> (Ali Afshar)'
def Run(source_file):
"""Load a source file and run a sample from it."""
source = open(source_file).read()
global_dict = {'__file__': source_file}
exec source in global_dict
samples = [global_dict[k] for k in global_dict if k.endswith('S... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 02 08:41:08 2014
@author: Acer
"""
import sys
import pycd3
import math
class NodeFactory(pycd3.INodeFactory):
def __init__(self, node):
pycd3.INodeFactory.__init__(self)
self.node = node
print "NodeFactory.__init__"
def getNodeNa... |
# Source:https://github.com/Show-Me-the-Code/show-me-the-code
# Python 3.4
"""
第 0017 题: 将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如
下所示:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<students>
<!--
学生信息表
"id" : [名字, 数学, 语文, 英文]
-->
{
"1" : ["张三", 150, 120, 100],
"2" : ["李四", 90, 99, 95],
... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import ExtractorError
class ChaturbateIE(InfoExtractor):
_VALID_URL = r'https?://(?:[^/]+\.)?chaturbate\.com/(?P<id>[^/?#]+)'
_TESTS = [{
'url': 'https://www.chaturbate.com/siswet19/',
'info_dict... |
import stat
def filetype(mode):
"""
Returns "dir" or "file" according to what type path is.
@param mode: file mode from "stat" command.
"""
if stat.S_ISLNK(mode):
return "link"
elif stat.S_ISDIR(mode):
return "dir"
elif stat.S_ISREG(mode):
return "file"
else:
return "unknown"
def rwxt... |
import datetime
from core.platform import models
from core.tests import test_utils
(user_models,) = models.Registry.import_models([models.NAMES.user])
class ExplorationUserDataModelTest(test_utils.GenericTestBase):
"""Tests for the ExplorationUserDataModel class."""
DATETIME_OBJECT = datetime.datetime.strpt... |
from django.contrib.gis.db import models
from django.contrib.gis.tests.utils import gisfield_may_be_null
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class NamedModel(models.Model):
name = models.CharField(max_length=30)
objects = models.GeoManager()
class M... |
#! -*- coding: utf-8 -*-
import sys
import time
import urlparse
import os
from datetime import datetime, timedelta
import json
import pymongo
import logging
from scrapy.conf import settings
from collections import defaultdict
reload(sys)
sys.setdefaultencoding('utf-8')
def get_param(sys):
#处理时间
... |
"""SCons.Defaults
Builders and other things for the local site. Here's where we'll
duplicate the functionality of autoconf until we move it into the
installation procedure or use something like qmconf.
The code that reads the registry to find MSVC components was borrowed
from distutils.msvccompiler.
"""
#
# Copyri... |
"""
Define and register a code-block directive using pygments
"""
# Requirements
# ------------
# ::
import codecs
from docutils import nodes
from docutils.parsers.rst import directives
try:
import pygments
from pygments.lexers import get_lexer_by_name
from pygments.formatters.html import _get_ttype_clas... |
from functools import reduce
# from . import ast
class Document(object):
"""Base class for documents to be pretty printed."""
pass
class Text(Document):
"""Textual element in a document."""
def __init__(self, text):
self._text = text
def __str__(self):
return "Text('%s')" % self... |
"""Test Interface implementation
"""
import doctest
import unittest
import sys
class InterfaceTests(unittest.TestCase):
def _makeDerivedInterface(self):
from zope.interface import Interface
from zope.interface import Attribute
class _I1(Interface):
a1 = Attribute("This is an a... |
import base64
import os
import sys
if sys.version_info < (3,):
from httplib import (
HTTPSConnection,
HTTPConnection,
HTTP_PORT,
HTTPS_PORT,
)
from urlparse import urlparse
else:
from http.client import (
HTTPSConnection,
HTTPConnection,
HTTP_... |
import argparse
import contextlib
import json
import os
import subprocess
import sys
import tempfile
SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
SRC_DIR = os.path.abspath(
os.path.join(SCRIPT_DIR, os.path.pardir, os.path.pardir))
# run-webkit-tests returns the number of failures as the return
# code... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.