content stringlengths 4 20k |
|---|
'''
Provides a Manifest Feature abstraction, similar to but more strict than the
Feature schema (see feature_utility.py).
Each Manifest Feature has a 'level' in addition to the keys defined in a
Feature. 'level' can be 'required', 'only_one', 'recommended', or 'optional',
indicating how an app or extension should defi... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
def sensu_subscription(module, path, name, state='present', backup=False):
changed = False
reasons = []
try:
import json
except ImportError:
impor... |
{'name' : 'Purchase Group Orders by Shop and Carrier',
'version' : '0.4',
'author' : 'Camptocamp',
'maintainer': 'Camptocamp',
'category': 'Purchase Management',
'complexity': "normal", # easy, normal, expert
'depends' : ['delivery', 'sale', 'purchase',
],
'description': """Only merge PO with the ... |
import maya.cmds as cmds
from tank.platform.qt import QtCore, QtGui
def _findShotCamera():
"""
Shot camera setup. You can replace this entire func with your own code to return the correct cameraShape for the app to use.
"""
camera = []
for each in cmds.ls(type = 'camera'):
getCamTransform =... |
"""
XBlock runtime services for LibraryContentModule
"""
from django.core.exceptions import PermissionDenied
from opaque_keys.edx.locator import LibraryLocator, LibraryUsageLocator
from search.search_engine_base import SearchEngine
from xmodule.library_content_module import ANY_CAPA_TYPE_VALUE
from xmodule.modulestore ... |
#!/usr/bin/env python3
# FIXME hardcoded python because we need for xlsxwriter
"""Creating summary table for SG10K batch
"""
import glob
import os
import csv
import sys
import yaml
import xlsxwriter
WRITE_CSV = False
WRITE_XLS = True
WRITE_CONSOLE = False
SUMMARY_KEYS = ["raw total sequences:",
#"rea... |
import os
from ctypes import CDLL
from ctypes.util import find_library
from django.conf import settings
# Creating the settings dictionary with any settings, if needed.
GEOIP_SETTINGS = {key: getattr(settings, key)
for key in ('GEOIP_PATH', 'GEOIP_LIBRARY_PATH', 'GEOIP_COUNTRY', 'GEOIP_CITY')
... |
from setuptools import setup
setup(name='python-gflags',
version='2.0',
description='Google Commandline Flags Module',
license='BSD',
author='Google Inc. and others',
author_email='<EMAIL>',
url='http://code.google.com/p/python-gflags',
py_modules=["gflags", "gflags_validators... |
from trove.guestagent.common import operating_system
from trove.guestagent.datastore.couchdb import service
from trove.guestagent.strategies.restore import base
class CouchDBBackup(base.RestoreRunner):
__strategy_name__ = 'couchdbbackup'
base_restore_cmd = 'sudo tar xPf -'
def __init__(self, *args, **kw... |
from spack import *
class PerlTaskWeaken(PerlPackage):
"""Ensure that a platform has weaken support"""
homepage = "http://search.cpan.org/~adamk/Task-Weaken-1.04/lib/Task/Weaken.pm"
url = "http://search.cpan.org/CPAN/authors/id/A/AD/ADAMK/Task-Weaken-1.04.tar.gz"
version('1.04', 'affd0c395515bb... |
# Performs actions requested by the user
import builtins
from subprocess import Popen, PIPE
import urllib.request
import os.path
import time
import argparse
from objects.tredly.tredlyhost import *
from objects.tredly.container import *
from includes.util import *
from includes.defines import *
from includes.output imp... |
BZ2_AVAILABLE = True
try:
import bz2
except ImportError:
BZ2_AVAILABLE = False
import os
import string
import sys
import tarfile
UNTRUSTED_PREFIXES = tuple(["/", "\\"] +
[c + ":" for c in string.ascii_letters])
def main():
if len(sys.argv) != 2 or sys.argv[1] in {"-h", "--help"}:
error("... |
import random
from oslo_config import cfg
from oslo_db import exception as db_exc
from oslo_log import log
from neutron.common import exceptions as exc
from neutron.common import utils
from neutron.plugins.ml2 import driver_api as api
LOG = log.getLogger(__name__)
IDPOOL_SELECT_SIZE = 100
class BaseTypeDriver(ap... |
from tempest_lib.common.utils import data_utils
from tempest_lib import exceptions as lib_exc
from tempest.api.compute import base
from tempest import test
class MultipleCreateNegativeTestJSON(base.BaseV2ComputeTest):
_name = 'multiple-create-test'
def _generate_name(self):
return data_utils.rand_na... |
import six
from nova import context
from nova import db
from nova import exception as ex
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.functional import integrated_helpers as helper
from nova.tests.unit import policy_fixture
def rand_flavor(**kwargs):
flav = {
'na... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
=====================
Classifier comparison
=====================
A comparison of a several classifiers in scikit-learn on synthetic datasets.
The point of this example is to illustrate the nature of decision boundaries
of different classifiers.
This should be taken with ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.callback.default import CallbackModule as CallbackModule_default
class CallbackModule(CallbackModule_default):
'''
This is the default callback interface, which simply prints messages
to stdout wh... |
#!/usr/bin/env python
import os
import re
import yaml
import argparse
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def rax_list_iterator(svc, *args, **kwargs):
method = kwargs.pop('method', 'list')
items = getattr(svc, method)(*args, **kwargs)
while items:
... |
import mock
from oslo_config import cfg
from neutron.common import exceptions as n_exc
from neutron import manager
from neutron.plugins.common import constants
from neutron.services import provider_configuration as provconf
from neutron.tests import base
class ParseServiceProviderConfigurationTestCase(base.BaseTest... |
"""Definition of program constructs, used in the lint step.
A program construct is any kind of value that an
identifier might take, such as "user-defined function"
or "built-in constant".
"""
import common.i18n as i18n
import common.position
class ProgramConstruct(object):
"""Base class to represent Gobstones co... |
''' Tests for byteorder module '''
from __future__ import division, print_function, absolute_import
import sys
from numpy.testing import assert_raises, assert_, run_module_suite
import scipy.io.matlab.byteordercodes as sibc
def test_native():
native_is_le = sys.byteorder == 'little'
assert_(sibc.sys_is_le... |
from bears.c_languages.ClangBear import clang_available, ClangBear
from bears.c_languages.codeclone_detection.ClangFunctionDifferenceBear import (
ClangFunctionDifferenceBear)
from coalib.bears.GlobalBear import GlobalBear
from coalib.results.Result import Result
from coalib.results.RESULT_SEVERITY import RESULT_SE... |
"""CholeskyOuterProduct bijector."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.contrib.distributions.python.ops.bijectors.cholesky_outer_product_impl import *
# pylint: enable=w... |
INSTANCE_TYPES = {
64: "STRING_TYPE",
68: "ONE_BYTE_STRING_TYPE",
65: "CONS_STRING_TYPE",
69: "CONS_ONE_BYTE_STRING_TYPE",
67: "SLICED_STRING_TYPE",
71: "SLICED_ONE_BYTE_STRING_TYPE",
66: "EXTERNAL_STRING_TYPE",
70: "EXTERNAL_ONE_BYTE_STRING_TYPE",
74: "EXTERNAL_STRING_WITH_ONE_BYTE_DATA_TYPE",
82: ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
__version__ = '${version}'
import os
from distutils.version import LooseVersion
try:
... |
"""DNS name dictionary"""
import collections
import dns.name
from ._compat import xrange
class NameDict(collections.MutableMapping):
"""A dictionary whose keys are dns.name.Name objects.
@ivar max_depth: the maximum depth of the keys that have ever been
added to the dictionary.
@type max_depth: int
... |
"""
Disqus OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/disqus.html
"""
from social.backends.oauth import BaseOAuth2
class DisqusOAuth2(BaseOAuth2):
name = 'disqus'
AUTHORIZATION_URL = 'https://disqus.com/api/oauth/2.0/authorize/'
ACCESS_TOKEN_URL = 'https://disqus.com/api/oauth... |
import openerp
from openerp.addons.crm import crm
from openerp.osv import fields, osv
from openerp import tools
from openerp.tools.translate import _
from openerp.tools import html2plaintext
class crm_claim_stage(osv.osv):
""" Model for claim stages. This models the main stages of a claim
management flow.... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from units.compat.mock import patch
from ansible.modules.network.dellos6 import dellos6_command
from units.modules.utils import set_module_args
from .dellos6_module import TestDellos6Module, load_fixture
class TestDe... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import base64
import json
import os
from ansible.errors import AnsibleError, AnsibleParserE... |
import praw
import json
import requests
import tweepy
import time
import os
import csv
import re
import configparser
import urllib.parse
import sys
from glob import glob
from gfycat.client import GfycatClient
from imgurpython import ImgurClient
import distutils.core
import itertools
import photohash
from PIL import Ima... |
#!/usr/bin/python3
"""
Problem management script.
"""
import argparse
import sys
import logging
import api
from api.common import APIException, InternalException
from os import path, walk, makedirs
from bson import json_util
import shutil
import glob
def check_files_exist(files):
for f in files:
if not p... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import sys, os, unittest
# the pyeq2 directory is located up one level from here
if -1 != sys.path[0].find('pyeq2-master'):raise Exception('Please rename git checkout directory from "pyeq2-master" to "... |
# -*- coding: utf-8 -*-
import unittest
from ansible.parsing.utils.addresses import parse_address
class TestParseAddress(unittest.TestCase):
tests = {
# IPv4 addresses
'192.0.2.3': ['192.0.2.3', None],
'192.0.2.3:23': ['192.0.2.3', 23],
# IPv6 addresses
'::': ['::', Non... |
# -*- coding: utf8 -*-
import libs
SQL = (
("achiv", "SELECT SQL_CALC_FOUND_ROWS ANAME,L1,L2,L3 FROM `af3_arhiv` limit 1;"),
("list_opis","""select @FOND_ID:=FOND_ID as FOND_ID, @OPIS_ID:=OPIS_ID as OPIS_ID, O.OKOD, O.ONAME, G3, G5, O.G7, G46 FROM `af3_opis` O LEFT JOIN `afweb_opis` o on(o.OPIS_ID=O.KOD) %(wher... |
# coding: utf-8
from __future__ import unicode_literals, division
import re
from .common import InfoExtractor
from ..compat import (
compat_str,
compat_HTTPError,
)
from ..utils import (
determine_ext,
float_or_none,
int_or_none,
parse_age_limit,
parse_duration,
ExtractorError
)
clas... |
"""Implementation of magic functions for IPython's own logging.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distribut... |
import numpy as np
from ...utils import warn
class _LinkViewer(object):
"""Class to link multiple Brain objects."""
def __init__(self, brains, time=True, camera=False, colorbar=True,
picking=False):
self.brains = brains
self.leader = self.brains[0] # select a brain as leader... |
from __future__ import print_function, unicode_literals
import os
import os.path as path
import subprocess
from shutil import copytree, rmtree, copy2
from mach.registrar import Registrar
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
from servo.command_base import (
Comma... |
#!/usr/bin/env python
import os
import cv2
import numpy as np
from scipy.misc import imresize
from scipy.signal import medfilt
### Parameters (you should edit these)
output_folder = '.'
video_path = 'angrywalk.mp4'
### ----------------------------------
def get_fps(capture):
if int((cv2.__version__).split('.')[0... |
#!/usr/bin/env python3
# This example demonstrates how to control the set of the locations in the
# binary code of the kernel monitored by RaceHound.
#
# This can be used, for example, to create a system that dynamically adds
# and removes the breakpoints according to some policy to sweep through
# the given area of t... |
# -*- coding: utf-8 -*-
"""
libs.utils.decorators
~~~~~~~~~~~~~~
here are the generic decorators for RMR
:copyright: (c) 2012 by arruda.
"""
from functools import wraps
from django.utils import simplejson
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpRespo... |
from ansible.module_utils.six import iteritems
from ansible.module_utils.network.common.utils import to_list
from ansible.module_utils.network.common.config import NetworkConfig
class ConfigBase(object):
argument_spec = {}
mutually_exclusive = []
identifier = ()
def __init__(self, **kwargs):
... |
import unittest
import numpy
import chainer
from chainer import backend
from chainer.backends import cuda
from chainer import gradient_check
from chainer import links
from chainer import testing
from chainer.testing import attr
def _sigmoid(x):
xp = backend.get_array_module(x)
half = x.dtype.type(0.5)
r... |
"""
Support for Rflink sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/light.rflink/
"""
import asyncio
from functools import partial
import logging
from homeassistant.components.rflink import (
CONF_ALIASSES, CONF_AUTOMATIC_ADD, CONF_DEVICE... |
from tests.support import unittest2, inPy3k
try:
unicode
except NameError:
# Python 3
unicode = str
long = int
import inspect
import sys
from mock import Mock, MagicMock, _magics
class TestMockingMagicMethods(unittest2.TestCase):
def test_deleting_magic_methods(self):
mock = Mock()
... |
from __future__ import absolute_import, division, print_function, \
with_statement
import socket
import struct
import logging
def compat_ord(s):
if type(s) == int:
return s
return _ord(s)
def compat_chr(d):
if bytes == str:
return _chr(d)
return bytes([d])
_ord = ord
_chr = ch... |
from __future__ import with_statement
import pytest
import time
import redis
from redis.exceptions import ConnectionError
from redis._compat import basestring, u, unichr
from .conftest import r as _redis_client
def wait_for_message(pubsub, timeout=0.1, ignore_subscribe_messages=False):
now = time.time()
tim... |
import unittest
from JumpScale import j
class TestSSHD(unittest.TestCase):
def setUp(self):
self.sshd = j.sal.sshd
self.key1 = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCUlY0UEUNExAQF/sIw2L2AJEmHj0eTCnSCwg7gYOQDNhrrzD0+HJulD1UTz+zZqiC2nIPWMfWBoEs3i4jDj79fyiGx4pgQJXFwioIqTONlEyvPIY0eCm3eeSaWrK9G0STd... |
from collections import defaultdict
import pymongo
from bson import SON
from mongoengine.base.fields import UPDATE_OPERATORS
from mongoengine.connection import get_connection
from mongoengine.common import _import_class
from mongoengine.errors import InvalidQueryError
from mongoengine.python_support import IS_PYMONGO... |
"""
A module that implments tooling to enable easy warnings about deprecations.
"""
from __future__ import absolute_import
import logging
import warnings
class PipDeprecationWarning(Warning):
pass
class RemovedInPip8Warning(PipDeprecationWarning, PendingDeprecationWarning):
pass
class RemovedInPip9Warnin... |
import time
import os
import numpy as np
from nibabel import trackvis as tv
from dipy.viz import fos
from dipy.io import pickles as pkl
from dipy.core import track_learning as tl
from dipy.core import track_performance as pf
from dipy.core import track_metrics as tm
fname='/home/eg01/Data/PBC/pbc2009icdm/brain1/bra... |
from Adafruit_I2C import Adafruit_I2C
import time
class TSL2561:
i2c = None
def __init__(self, address=0x29, debug=0, pause=0.8):
self.i2c = Adafruit_I2C(address)
self.address = address
self.pause = pause
self.debug = debug
self.gain = 0 # no gain preselected
s... |
from pybindgen import Module, FileCodeSink, param, retval, cppclass, typehandlers
def register_types(module):
root_module = module.get_root()
## Register a nested module for the namespace Config
nested_module = module.add_cpp_namespace('Config')
register_types_ns3_Config(nested_module)
... |
from sympy import (hyper, meijerg, S, Tuple, pi, I, exp, log,
cos, sqrt, symbols, oo, Derivative, gamma, O)
from sympy.series.limits import limit
from sympy.abc import x, z, k
from sympy.utilities.pytest import raises, slow
from sympy.utilities.randtest import (
random_complex_number as randcplx,... |
"""
Send payload to the Stream (messaging abstraction, provided by SunHead framework.
"""
import asyncio
from sunhead.events.stream import init_stream_from_settings
from sunhead.metrics import get_metrics
from aeroport.abc import AbstractDestination, AbstractPayload
from aeroport.utils import register_metric
class... |
import unittest, time, sys, random
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_import as h2i
import h2o_browse as h2b
def write_syn_dataset(csvPathname, rowCount, headerData, rList):
dsf = open(csvPathname, "w+")
dsf.write(headerData + "\n")
for i in range(rowCount):
# two cho... |
import os, sys, json, urlparse, urllib
def get_template(template_basename):
script_directory = os.path.dirname(os.path.abspath(__file__))
template_directory = os.path.abspath(os.path.join(script_directory,
"..",
... |
{
'conditions': [
['OS=="mac" or OS=="solaris"', {
'variables': {
'escaped_root': '<!(printf %q "<(module_root_dir)")',
},
# If we are on the Mac, or a Solaris derivative, attempt
# to build the DTrace provider extension.
'targets':... |
import octavia.common.data_models as models
class Topology(models.BaseDataModel):
def __init__(self, hostname=None, uuid=None, topology=None, role=None,
ip=None, ha_ip=None):
self.hostname = hostname
self.uuid = uuid
self.topology = topology
self.role = role
... |
import zstackwoodpecker.test_state as ts_header
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template2",
path_list=[[TestAction.create_volume, "volume1", "=scsi"],\
[TestAction.attach_volume, "vm1", "volume1"], \
[TestAction.create_volume_backup, "volume1", "... |
"""
Reference:
Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. "Imagenet classification with deep convolutional neural networks." Advances in neural information processing systems. 2012.
"""
import mxnet as mx
import numpy as np
def get_symbol(num_classes, dtype='float32', **kwargs):
input_data = mx.sym... |
"""These are job parameters that are common to every type of Jenkins job.
Example:
.. literalinclude:: /../../tests/yamlparser/fixtures/general-example-001.yaml
:Job Parameters:
* **project-type**:
Defaults to "freestyle", but "maven" as well as "multijob", "flow" or
"externaljob" can also be specif... |
import unittest
from mantid.geometry import BoundingBox
from mantid.kernel import V3D
class BoundingBoxTest(unittest.TestCase):
def test_default_construction_is_allowed(self):
box = BoundingBox()
self.assertTrue(isinstance(box, BoundingBox))
self.assertTrue(box.isNull())
def test_con... |
import os
from setuptools import setup
def find_packages(dir_):
packages = []
for _dir, subdirectories, files in os.walk(os.path.join(dir_, 'rfk')):
if '__init__.py' in files:
lib, fragment = _dir.split(os.sep, 1)
packages.append(fragment.replace(os.sep, '.'))
return packag... |
def plot_crystal_sketch(v0_h,v0_v,vH_h ,vH_v ,H_h ,H_v):
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
hshift = 0.2
vshift = 0.0
plt.figure(1, figsize=(6,6))
ax = plt.subplot(111)
ax.xaxis.set_ticks_position('none)
... |
import re
def result_contains_repaint_rects(text):
return isinstance(text, str) and (
re.search('"repaintRects": \[$', text, re.MULTILINE) != None or
text.find('Minimum repaint:') != -1)
def extract_layer_tree(input_str):
if not isinstance(input_str, str):
return '{}'
if input_s... |
"""Unit Tests for network code."""
from nova.network import linux_net
from nova import test
class IptablesManagerTestCase(test.TestCase):
binary_name = linux_net.get_binary_name()
sample_filter = ['#Generated by iptables-save on Fri Feb 18 15:17:05 2011',
'*filter',
... |
from Plugins.Plugin import PluginDescriptor
#------------------------------------------------------------------------------------------
def Pic_Thumb(*args, **kwa):
import ui
return ui.Pic_Thumb(*args, **kwa)
def picshow(*args, **kwa):
import ui
return ui.picshow(*args, **kwa)
def main(session, **kwargs):
from... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('scheduler', '0007_auto_20150819_0138'),
]
operations = [
migrations.CreateModel(
name='BluePrint',
f... |
class ResettingJar(object):
"""Testing stub for _p_jar attribute.
"""
def __init__(self):
from persistent import PickleCache # XXX stub it!
from persistent.interfaces import IPersistentDataManager
from zope.interface import directlyProvides
self.cache = self._cache = PickleCa... |
import types
from rx import Lock
from .observer import Observer, AbstractObserver
class Observable(object):
"""Represents a push-style collection."""
_methods = []
def __init__(self, subscribe):
self._subscribe = subscribe
self.lock = Lock()
# Deferred method assignment
... |
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.network.nso.nso import connect, verify_version, nso_argument_spec
from ansible.module_utils... |
import crm_lead_report
import crm_opportunity_report
import crm_phonecall_report
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
"""Tests for distutils.spawn."""
import unittest
import os
import time
from test.support import captured_stdout, run_unittest
from distutils.spawn import _nt_quote_args
from distutils.spawn import spawn, find_executable
from distutils.errors import DistutilsExecError
from distutils.tests import support
class SpawnTes... |
from django.contrib.gis.gdal import SpatialReference
from django.db import connections, DEFAULT_DB_ALIAS
def add_srs_entry(srs, auth_name='EPSG', auth_srid=None, ref_sys_name=None,
database=DEFAULT_DB_ALIAS):
"""
This function takes a GDAL SpatialReference system and adds its information
... |
from twisted.internet import protocol
from twisted.words.protocols.jabber import xmlstream
class BootstrapMixin(object):
"""
XmlStream factory mixin to install bootstrap event observers.
This mixin is for factories providing
L{IProtocolFactory<twisted.internet.interfaces.IProtocolFactory>} to make
... |
import os
import distutils
from setuptools import Command
from distutils.util import convert_path
from distutils import log
from distutils.errors import DistutilsOptionError
__all__ = ['config_file', 'edit_config', 'option_base', 'setopt']
def config_file(kind="local"):
"""Get the filename of the distutils, loca... |
from cuon.Databases.SingleData import SingleData
import logging
import pygtk
pygtk.require('2.0')
import gtk
import gtk.glade
import gobject
class SingleInpayment(SingleData):
def __init__(self, allTables):
SingleData.__init__(self)
# tables.dbd and address
self.sNameOfTable = "in... |
# -*- coding: utf-8 -*-
"""
Covenant Add-on
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, either version 3 of the License, or
(at your option) any later version.
This prog... |
import pytest
import mock
from django.core.exceptions import ValidationError
# AWX
from awx.main.models import (
Host,
Inventory,
InventorySource,
InventoryUpdate,
)
from awx.main.utils.filters import SmartFilter
@pytest.mark.django_db
class TestSCMUpdateFeatures:
def test_automatic_project_upd... |
import numpy as np, logging, time, struct
import collections,crcmod
logger = logging.getLogger(__name__)
class DS28CM00:
"""
DS28CM00 I2C/SMBus Silicon Serial Number
"""
crcPoly = 0b100110001
crcInitVal = 0
def __init__(self,itf,addr=0x50):
self.itf = itf
self.addr = addr
... |
""" Testing
"""
from __future__ import division, print_function, absolute_import
import os
import sys
import zlib
from io import BytesIO
if sys.version_info[0] >= 3:
cStringIO = BytesIO
else:
from cStringIO import StringIO as cStringIO
from tempfile import mkstemp
import numpy as np
from numpy.testing i... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import extract_attributes
class BFMTVBaseIE(InfoExtractor):
_VALID_URL_BASE = r'https?://(?:www\.)?bfmtv\.com/'
_VALID_URL_TMPL = _VALID_URL_BASE + r'(?:[^/]+/)*[^/?&#]+_%s[A-Z]-(?P<id>\d{12})\.h... |
# ===========================================
# Stackdriver module specific support methods.
#
try:
import json
except ImportError:
try:
import simplejson as json
except ImportError:
# Let snippet from module_utils/basic.py return a proper error in this case
pass
def send_deploy_e... |
import sys
import operator
import inspect
try:
xrange
except NameError: # support python3
xrange = range
def describeFunc(obj, method=False):
"""
Describe the function object passed as argument.
If this is a method object, the second argument
will be passed as True
@param obj:
@type... |
"""
Copyright 2015 Ryan Fobel
This file is part of opendrop_plugin.
opendrop_plugin is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
opendr... |
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.mininode import COIN, MAX_BLOCK_SIZE
class PrioritiseTransactionTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nod... |
#!/usr/bin/env python
from __future__ import print_function
import sys
import re
import shlex
from subprocess import Popen, PIPE, check_output
def get_tagname_or_hash():
"""return tagname if exists else hash"""
cmd = 'git log -1 --format="%h%d"'
output = check_output(shlex.split(cmd)).decode('utf-8').str... |
# -*- coding: utf-8 -*-
from wechat_sdk import WechatBasic
# 下面这些变量均假设已由 Request 中提取完毕
token = 'WECHAT_TOKEN' # 你的微信 Token
signature = 'f24649c76c3f3d81b23c033da95a7a30cb7629cc' # Request 中 GET 参数 signature
timestamp = '1406799650' # Request 中 GET 参数 timestamp
nonce = '1505845280' # Request 中 GET 参数 nonce
# 用户的请... |
"""
.. autoclass:: mwtypes.Page
:members:
"""
import jsonable
from .util import none_or
class Page(jsonable.Type):
"""
Page metadata
:Attributes:
.. autoattribute:: mwtypes.Page.id
:annotation: = Page ID : int
.. autoattribute:: mwtypes.Page.title
:annotatio... |
"""Join multiple binary files into single file and generate JSON snippet with offsets
-------------------------------------
How to use
-------------------------------------
python join_ctm.py -i "part_*.ctm" -o joined.ctm [-j offsets.js]
Will read multiple files following wildcard pattern (ordered lexicographically)... |
"""Temporary files.
This module provides generic, low- and high-level interfaces for
creating temporary files and directories. The interfaces listed
as "safe" just below can be used without fear of race conditions.
Those listed as "unsafe" cannot, and are provided for backward
compatibility only.
This module also pr... |
#!/usr/bin/env python
import os.path
import sys
from optparse import OptionParser
# check if the pymol module is installed
try :
import pymol
except :
sys.exit( "error : This script needs 'pymol' module. Please install pymol before running." )
######################################## function ################... |
from oslo_log import log as logging
from nova.cells import filters
LOG = logging.getLogger(__name__)
class AvailabilityZoneFilter(filters.BaseCellFilter):
"""Filters cells by availability zone.
Works with cell capabilities using the key
'availability_zones'
Note: cell can have multiple availability... |
# -*- coding: utf-8 -*-
"""
jinja2.meta
~~~~~~~~~~~
This module implements various functions that exposes information about
templates that might be interesting for various kinds of applications.
:copyright: (c) 2010 by the Jinja Team, see AUTHORS for more details.
:license: BSD, see LICENSE fo... |
"""
Configuration for Hysbakstryd server.
"""
class AttrDict(dict):
"""Access a dictionary like a dict OR like a class, and also act like a defaultdict with None as its factory.
Nice little tool, taken from: http://stackoverflow.com/a/14620633
"""
def __init__(self, *args, **kwargs):
super()... |
from math import fabs
import logging
from pyduel_engine.content import default_boards as boards
from pyduel_engine.content.engine_states import SqState, BoardType
from pyduel_engine.model import position as ps
def _adjacent_square_pos(pos):
return [ps.shift_down(pos), ps.shift_up(pos),
ps.shift_left... |
from celery import shared_task
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)
@shared_task(bind=True)
def invia_mail(self, pk):
from .models import Messaggio
messaggio = Messaggio.objects.get(pk=pk)
logger.info("messaggio id=%d" % pk)
# Controlla che il messaggio si... |
"""Battery Charge and Range Support for the Nissan Leaf."""
import logging
from homeassistant.const import DEVICE_CLASS_BATTERY
from homeassistant.helpers.icon import icon_for_battery_level
from homeassistant.util.distance import LENGTH_KILOMETERS, LENGTH_MILES
from homeassistant.util.unit_system import IMPERIAL_SYSTE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.