text stringlengths 4 1.02M | meta dict |
|---|---|
from django.core.paginator import Paginator
from djapian.tests.utils import BaseTestCase, Entry, Person
class ResultSetPaginationTest(BaseTestCase):
num_entries = 100
per_page = 10
num_pages = num_entries / per_page
def setUp(self):
p = Person.objects.create(name="Alex")
for i in range(self.num_entries):
Entry.objects.create(
author=p,
title="Entry with number %s" % i,
text="foobar " * i
)
Entry.indexer.update()
self.result = Entry.indexer.search("title:number")
def test_pagination(self):
paginator = Paginator(self.result, self.per_page)
self.assertEqual(paginator.num_pages, self.num_pages)
page = paginator.page(5)
| {
"content_hash": "2ecd2afc5b3d7c108b2bff7cc471478a",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 61,
"avg_line_length": 26.896551724137932,
"alnum_prop": 0.6115384615384616,
"repo_name": "daevaorn/djapian",
"id": "aa115822cf281aca65f153707f8490801ccd20b5",
"size": "780",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/djapian/tests/pagination.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "86224"
}
],
"symlink_target": ""
} |
"""
.. module: security_monkey.watchers.iam.iam_user
:platform: Unix
.. version:: $$VERSION$$
.. moduleauthor:: Patrick Kelley <pkelley@netflix.com> @monkeysecurity
"""
from security_monkey.watcher import Watcher
from security_monkey.watcher import ChangeItem
from security_monkey.exceptions import InvalidAWSJSON
from security_monkey.exceptions import BotoConnectionIssue
from security_monkey import app
import json
import urllib
def all_managed_policies(conn):
managed_policies = {}
for policy in conn.policies.all():
for attached_user in policy.attached_users.all():
policy = {
"name": policy.policy_name,
"arn": policy.arn,
"version": policy.default_version_id
}
if attached_user.arn not in managed_policies:
managed_policies[attached_user.arn] = [policy]
else:
managed_policies[attached_user.arn].append(policy)
return managed_policies
class IAMUser(Watcher):
index = 'iamuser'
i_am_singular = 'IAM User'
i_am_plural = 'IAM Users'
def __init__(self, accounts=None, debug=False):
super(IAMUser, self).__init__(accounts=accounts, debug=debug)
def policy_names_for_user(self, conn, user):
all_policy_names = []
marker = None
while True:
response = self.wrap_aws_rate_limited_call(
conn.get_all_user_policies,
user.user_name,
marker=marker
)
all_policy_names.extend(response.policy_names)
if response.is_truncated == u'true':
marker = response.marker
else:
break
return all_policy_names
def access_keys_for_user(self, conn, user):
all_access_keys = []
marker = None
while True:
response = self.wrap_aws_rate_limited_call(
conn.get_all_access_keys,
user_name=user.user_name,
marker=marker
)
all_access_keys.extend(response.access_key_metadata)
if response.is_truncated == u'true':
marker = response.marker
else:
break
return all_access_keys
def mfas_for_user(self, conn, user):
all_mfas = []
marker = None
while True:
response = self.wrap_aws_rate_limited_call(
conn.get_all_mfa_devices,
user_name=user.user_name,
marker=marker
)
all_mfas.extend(response.mfa_devices)
if response.is_truncated == u'true':
marker = response.marker
else:
break
return all_mfas
def certificates_for_user(self, conn, user):
all_certificates = []
marker = None
while True:
response = self.wrap_aws_rate_limited_call(
conn.get_all_signing_certs,
user_name=user.user_name,
marker=marker
)
all_certificates.extend(response.certificates)
if response.is_truncated == u'true':
marker = response.marker
else:
break
return all_certificates
def slurp(self):
"""
:returns: item_list - list of IAM Groups.
:returns: exception_map - A dict where the keys are a tuple containing the
location of the exception and the value is the actual exception
"""
self.prep_for_slurp()
item_list = []
exception_map = {}
from security_monkey.common.sts_connect import connect
for account in self.accounts:
all_users = []
try:
iam_b3 = connect(account, 'iam_boto3')
managed_policies = all_managed_policies(iam_b3)
iam = connect(account, 'iam')
marker = None
while True:
users_response = self.wrap_aws_rate_limited_call(
iam.get_all_users,
marker=marker
)
# build our iam user list
all_users.extend(users_response.users)
# ensure that we get every iam user
if hasattr(users_response, 'marker'):
marker = users_response.marker
else:
break
except Exception as e:
exc = BotoConnectionIssue(str(e), 'iamuser', account, None)
self.slurp_exception((self.index, account, 'universal'), exc, exception_map)
continue
for user in all_users:
if self.check_ignore_list(user.user_name):
continue
item_config = {
'user': {},
'userpolicies': {},
'accesskeys': {},
'mfadevices': {},
'signingcerts': {}
}
app.logger.debug("Slurping %s (%s) from %s" % (self.i_am_singular, user.user_name, account))
item_config['user'] = dict(user)
if managed_policies.has_key(user.arn):
item_config['managed_policies'] = managed_policies.get(user.arn)
### USER POLICIES ###
policy_names = self.policy_names_for_user(iam, user)
for policy_name in policy_names:
policy_document = self.wrap_aws_rate_limited_call(
iam.get_user_policy,
user.user_name,
policy_name
)
policy_document = policy_document.policy_document
policy = urllib.unquote(policy_document)
try:
policydict = json.loads(policy)
except:
exc = InvalidAWSJSON(policy)
self.slurp_exception((self.index, account, 'universal', user.user_name), exc, exception_map)
item_config['userpolicies'][policy_name] = dict(policydict)
### ACCESS KEYS ###
access_keys = self.access_keys_for_user(iam, user)
for key in access_keys:
item_config['accesskeys'][key.access_key_id] = dict(key)
### Multi Factor Authentication Devices ###
mfas = self.mfas_for_user(iam, user)
for mfa in mfas:
item_config['mfadevices'][mfa.serial_number] = dict(mfa)
### LOGIN PROFILE ###
login_profile = 'undefined'
try:
login_profile = self.wrap_aws_rate_limited_call(
iam.get_login_profiles,
user.user_name
)
login_profile = login_profile.login_profile
item_config['loginprofile'] = dict(login_profile)
except:
pass
### SIGNING CERTIFICATES ###
certificates = self.certificates_for_user(iam, user)
for cert in certificates:
_cert = dict(cert)
del _cert['certificate_body']
item_config['signingcerts'][cert.certificate_id] = dict(_cert)
item_list.append(
IAMUserItem(account=account, name=user.user_name, config=item_config)
)
return item_list, exception_map
class IAMUserItem(ChangeItem):
def __init__(self, account=None, name=None, config={}):
super(IAMUserItem, self).__init__(
index=IAMUser.index,
region='universal',
account=account,
name=name,
new_config=config)
| {
"content_hash": "c8be7ac32defeba0428da6d6fb25790d",
"timestamp": "",
"source": "github",
"line_count": 234,
"max_line_length": 116,
"avg_line_length": 34.111111111111114,
"alnum_prop": 0.5086444500125282,
"repo_name": "monkeysecurity/security_monkey",
"id": "7d95fa9abfea21eee44db7bb394db98e9b6965ae",
"size": "8599",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "security_monkey/watchers/iam/iam_user.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "22086"
},
{
"name": "Dart",
"bytes": "81616"
},
{
"name": "HTML",
"bytes": "76595"
},
{
"name": "JavaScript",
"bytes": "8629"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "441430"
},
{
"name": "Shell",
"bytes": "16916"
}
],
"symlink_target": ""
} |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
SECRET_KEY = 'damn it is hard to guess' or os.environ.get('SECRET_KEY')
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
MAIL_SERVER = 'smtp.163.com'
MAIL_PORT = 25
MAIL_USE_TLS = True
FLASKY_MAIL_SUBJECT_PREFIX = '[Seaside メイド喫茶]'
FLASKY_MAIL_SENDER = 'wangzhihao9110@163.com'
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
FLASKY_ADMIN = os.environ.get('FLASKY_ADMIN')
FLASKY_POSTS_PER_PAGE = 20
FLASKY_FOLLOWERS_PER_PAGE = 20
FLASKY_COMMENTS_PER_PAGE = 20
SQLALCHEMY_RECORD_QUERIES = True
FLASKY_DB_QUERY_TIMEOUT = 0.5
FLASKY_SLOW_DB_QUERY_TIME = 0.5
SSL_DISABLE = True
MAX_SEARCH_RESULTS = 50
@staticmethod
def init_app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.environ.get('DEV_DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
class TestConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = os.environ.get('TEST_DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data-test.sqlite')
WTF_CSRF_ENABLED = False
class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
'sqlite:///' + os.path.join(basedir, 'data.sqlite')
WHOOSH_BASE = os.path.join(basedir, 'search.db')
@classmethod
def init_app(cls, app):
Config.init_app(app)
import logging
from logging.handlers import SMTPHandler
credentials = None
secure = None
if getattr(cls, 'MAIL_USERNAME', None) is not None:
credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
if getattr(cls, 'MAIL_USE_TLS', None):
secure = ()
mail_handler = SMTPHandler(
mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
fromaddr=cls.FLASKY_MAIL_SENDER,
toaddrs=[cls.FLASKY_ADMIN],
subject=cls.FLASKY_MAIL_SUBJECT_PREFIX + 'Application Error',
credentials=credentials,
secure=secure)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
class HerokuConfig(ProductionConfig):
SSL_DISABLE = bool(os.environ.get('SSL_DISABLE'))
DEBUG = True
@classmethod
def init_app(cls, app):
ProductionConfig.init_app(app)
# handle proxy server headers
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
import logging
from logging import StreamHandler
file_handler = StreamHandler()
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)
config = {
'development': DevelopmentConfig,
'testing': TestConfig,
'Production': ProductionConfig,
'heroku': HerokuConfig,
'default': DevelopmentConfig,
}
| {
"content_hash": "d011b709d0d3b17702637c3ccfa1d25e",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 75,
"avg_line_length": 30.63917525773196,
"alnum_prop": 0.642328398384926,
"repo_name": "SanbaiWang/sanbaiblog",
"id": "46a10866082d0377dd53ae35c1e5213522572322",
"size": "2999",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "90791"
},
{
"name": "HTML",
"bytes": "577276"
},
{
"name": "JavaScript",
"bytes": "37853"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "PHP",
"bytes": "2232"
},
{
"name": "Python",
"bytes": "64919"
}
],
"symlink_target": ""
} |
import BaseHTTPServer
import copy
import errno
import inspect
import itertools
import new
import os
import re
import shutil
import shlex
import signal
import socket
import stat
import StringIO
import subprocess
import sys
import time
import traceback
import testsuite
from M2Crypto import SSL
#conary
from conary.cmds import branch
from conary import callbacks
from conary import checkin
from conary.cmds import clone
from conary import conarycfg
from conary import conaryclient
from conary.cmds import cscmd
from conary import errors
from conary import files
from conary import rpmhelper
from conary import trove
from conary import versions
from conary.build import cook, loadrecipe, use
from conary.cmds import conarycmd
from conary.cmds import cvccmd
from conary.cmds import rollbacks
from conary.cmds import updatecmd
from conary.cmds import verify
from conary.conaryclient import cmdline, filetypes
from conary.deps import arch, deps
from conary.lib import cfg as cfgmod
from conary.lib import cfgtypes, log
from conary.lib import httputils
from conary.lib import openpgpkey
from conary.lib import sha1helper
from conary.lib import util
from conary.local import database
from conary.repository import errors as repo_errors
from conary.repository import netclient, changeset, filecontents, trovesource
from conary.repository import searchsource
from conary.server import server as cny_server
from conary.server.server import SecureHTTPServer
#test
from testrunner import testhelp
from testrunner.testcase import safe_repr
from testutils import apache_server, base_server, os_utils, sock_utils
from testutils import sqlharness
from conary_test import recipes
from conary_test import resources
# make tryConnect available
tryConnect = sock_utils.tryConnect
class _NoneArg:
pass
NoneArg = _NoneArg()
_File = filetypes._File
server_path = os.path.abspath(cny_server.__file__).replace('.pyc', '.py')
def _isIndividual():
# Make it compatible with testsuites that are not class-based yet
individual = getattr(testsuite, '_individual', None)
if individual is None:
individual = getattr(testsuite, 'Suite').individual
global _individual
_individual = individual
return individual
class Symlink(filetypes.Symlink):
pass
class RegularFile(filetypes.RegularFile):
pass
class BlockDevice(filetypes.BlockDevice):
pass
class CharacterDevice(filetypes.CharacterDevice):
pass
class Directory(filetypes.Directory):
pass
_fileClasses = [Symlink, RegularFile, BlockDevice, CharacterDevice, Directory]
if hasattr(filetypes, 'NamedPipe'):
class NamedPipe(filetypes.NamedPipe):
pass
_fileClasses.append(NamedPipe)
if hasattr(filetypes, 'Socket'):
class Socket(filetypes.Socket):
pass
_fileClasses.append(Socket)
for klass in _fileClasses:
klass.kwargs['version'] = None
klass.kwargs['config'] = None
klass.kwargs['pathId'] = None
# Support for specifying trove scripts
class TroveScript:
def __init__(self, script = None, conversions = None):
self.script = script
self.conversions = conversions
class RollbackScript(TroveScript):
pass
# Let's us load recipes from strings using the class name to find the right
# recipe instead of the class's "name" attribute
class LoaderFromString(loadrecipe.RecipeLoaderFromString):
@staticmethod
def _validateName(recipeClass, name):
return recipeClass.__name__ == name
# this is an override for arch.x86flags -- we never want to use
# any system flags (normally gathered from places like /proc/cpuinfo)
# because they could change the results from run to run
def x86flags(archTag, *args):
# always pretend we're on i686 for x86 machines
if archTag == 'x86':
flags = []
for f in ('i486', 'i586', 'i686'):
flags.append((f, deps.FLAG_SENSE_PREFERRED))
return deps.Dependency(archTag, flags)
# otherwise, just use the archTag with no flags
return deps.Dependency(archTag)
# override the existing x86flags() function
arch.x86flags = x86flags
# reinitialize arch
arch.initializeArch()
class IdGen0(cook._IdGen):
formatStr = "%s"
def __call__(self, path, version, flavor):
if self.map.has_key(path):
return self.map[path]
fileid = sha1helper.md5String(self.formatStr % path)
self.map[(path, flavor)] = (fileid, None, None)
return (fileid, None, None)
class IdGen1(IdGen0):
formatStr = "1%s"
class IdGen3(IdGen0):
formatStr = "111%s"
class ContentStore:
def getPath(self):
return self.path
def reset(self):
if os.path.exists(self.path):
shutil.rmtree(self.path)
util.mkdirChain(self.path)
def __init__(self, path):
self.path = path
class RepositoryServer(base_server.BaseServer):
"""
sets up a repository that will be run as a child process
"""
def setNeedsReset(self):
self.needsReset = True
def reset(self):
self.contents.reset()
if self.reposDB:
self.reposDB.reset()
if self.cache:
self.cache.reset()
self.needsPGPKey = True
self.needsReset = False
super(RepositoryServer, self).reset()
def resetIfNeeded(self):
if self.needsReset:
self.reset()
def getMap(self):
if self.sslEnabled and self.useSSL:
dest = 'https://localhost:%d/conary/' % self.port
else:
dest = 'http://localhost:%d/conary/' % self.port
d = dict((name, dest) for name in self.nameList)
return d
# assume the first entry in a multihomed name list is the "main" name
def getName(self):
return self.nameList[0]
def __init__(self, nameList, reposDB, contents, server, serverDir, reposDir,
conaryPath, repMap, requireSigs, authCheck=None,
entCheck=None, authTimeout = None, readOnlyRepository=False,
serverIdx=0, proxies=None, useSSL=False, forceSSL = False,
sslCert=None, sslKey=None, closed=False, commitAction = None,
deadlockRetry=None, excludeCapsuleContents=False,
withCache=False):
base_server.BaseServer.__init__(self)
assert(isinstance(contents, ContentStore))
assert(reposDB is None or isinstance(reposDB, sqlharness.RepositoryDatabase))
self.contents = contents
self.reposDB = reposDB
if isinstance(nameList, str):
nameList = [nameList]
self.nameList = nameList
self.needsPGPKey = True
self.conaryPath = conaryPath
self.serverDir = serverDir
self.server = server
self.requireSigs = requireSigs
self.reposDir = reposDir
self.traceLog = os.path.join(self.reposDir, 'trace.log')
self.tmpDir = reposDir
self.authCheck = authCheck
self.entCheck = entCheck
self.authTimeout = authTimeout
self.readOnlyRepository = readOnlyRepository
self.repMap = repMap
self.serverIdx = serverIdx
self.proxies = proxies
self.useSSL = getattr(self, 'sslOnly', useSSL)
self.forceSSL = forceSSL
self.excludeCapsuleContents = excludeCapsuleContents
self.deadlockRetry = deadlockRetry
if withCache:
self.cache = ContentStore(reposDir + '/cscache')
self.cache.reset()
else:
self.cache = None
if self.useSSL and (sslCert is None or sslKey is None):
if sslCert is None:
sslCert = resources.get_archive('ssl-cert.crt')
if sslKey is None:
sslKey = resources.get_archive('ssl-cert.key')
self.sslCert = sslCert
self.sslKey = sslKey
self.closed = closed
self.initPort()
self.commitAction = commitAction
self.needsReset = True
def writeServerConfigFile(self, configFile, **kw):
conaryrc = kw.pop('conaryrc', None)
configValues = {
'contentsDir' : self.contents.getPath(),
'baseUri' : '/conary',
'repositoryDB' : self.reposDB.getDriver(),
'serverName' : " ".join(self.nameList),
'traceLog' : '3 ' + self.traceLog,
'logFile' : os.path.join(self.reposDir, 'repos.log'),
'tmpDir' : self.reposDir,
}
if self.requireSigs:
configValues['requireSigs'] = True
if self.authCheck:
configValues['externalPasswordURL'] = self.authCheck
if self.entCheck:
configValues['entitlementCheckURL'] = self.entCheck
if self.authTimeout is not None:
configValues['authCacheTimeout'] = self.authTimeout
if self.authTimeout is not None:
configValues['authCacheTimeout'] = self.authTimeout
if self.forceSSL:
configValues['forceSSL'] = True
if self.excludeCapsuleContents:
configValues['excludeCapsuleContents'] = True
if self.deadlockRetry is not None:
configValues['deadlockRetry'] = self.deadlockRetry
if self.readOnlyRepository:
configValues['readOnlyRepository'] = self.readOnlyRepository
if self.sslEnabled and self.useSSL and self.sslCert:
self.writeSSLRepoConfig(configValues)
if self.closed:
configValues['closed'] = self.closed
if self.commitAction:
configValues['commitAction'] = self.commitAction
if self.cache:
configValues['changesetCacheDir'] = self.cache.getPath()
# Add the command line options
configValues.update(kw)
f = open(configFile, "w+")
for item in configValues.iteritems():
print >> f, "%s %s" % item
# Multi-valued, cannot be added to a dictionary
for repname, reppath in self.repMap.iteritems():
print >> f, 'repositoryMap %s %s' %(repname, reppath)
f.close()
if conaryrc:
f = open(conaryrc, 'w')
for serverName in self.nameList:
f.write('repositoryMap %s http://localhost:%s/conary/\n'
% (serverName, configValues['port']) )
f.write('installLabelPath localhost@rpl:linux\n')
f.close()
def writeSSLRepoConfig(self, configValues):
configValues['useSSL'] = True
configValues['sslCert'] = self.sslCert
configValues['sslKey'] = self.sslKey
class ApacheServer(RepositoryServer, apache_server.ApacheServer):
def __init__(self, *args, **kwargs):
self.useCache = kwargs.pop('useCache', False)
RepositoryServer.__init__(self, *args, **kwargs)
apache_server.ApacheServer.__init__(self, topDir=self.reposDir)
self.logFileObj = None
def getServerDir(self):
return resources.get_path('conary_test', 'server')
def getPythonHandler(self):
return 'conary.server.apachehooks'
def _createAppConfig(self):
configValues = {
'tmpDir' : self.tmpDir,
'traceLog' : '3 ' + self.traceLog,
'authCacheTimeout': self.authTimeout or 0,
}
if self.closed:
configValues['closed'] = self.closed
if self.useCache:
configValues['changesetCacheDir'] = \
os.path.join(self.serverRoot, 'cscache')
self.cache = ContentStore(configValues['changesetCacheDir'])
if self.authTimeout is None:
configValues['authCacheTimeout'] = 2
self.writeServerConfigFile(os.path.join(self.serverRoot, 'test.cnr'),
**configValues)
def reset(self):
if not self.logFileObj:
try:
self.logFileObj = open(self.serverRoot + '/error_log')
except OSError, err:
if err.errno != errno.ENOENT:
raise
data = self.logFileObj.read()
if 'Traceback (most recent call last)' in data:
sys.stderr.write("Contents of error_log after test:\n" + data)
sys.stderr.flush()
# this is a bad hack to clear the cache
csCachePath = os.path.join(self.serverRoot, 'cscache')
if os.path.exists(csCachePath):
shutil.rmtree(csCachePath)
os.mkdir(csCachePath)
super(ApacheServer, self).reset()
def _startAppSpecificTasks(self, resetDir = True):
if resetDir:
if os.path.exists(self.reposDir):
shutil.rmtree(self.reposDir)
os.mkdir(self.reposDir)
self.createConfig()
if self.reposDB:
self.reposDB.reset()
def _stopAppSpecificTasks(self):
if self.reposDB:
self.reposDB._reset()
self.reposDB.stop()
def getServerConfigPath(self):
return os.path.join(self.serverRoot, 'test.cnr')
class ApacheServerWithCache(ApacheServer):
def __init__(self, *args, **kwargs):
kwargs['useCache'] = True
ApacheServer.__init__(self, *args, **kwargs)
class ApacheSSLServer(ApacheServer, apache_server.ApacheSSLMixin):
sslEnabled = True
sslOnly = True
def initPort(self):
return apache_server.ApacheSSLMixin.initPort(self)
def createConfig(self):
ApacheServer.createConfig(self)
return apache_server.ApacheSSLMixin.createConfig(self)
def writeSSLRepoConfig(self, configValues):
# No need to add anything in the repository's config
pass
class ApacheSSLServerWithCache(ApacheSSLServer, ApacheServerWithCache):
def __init__(self, *args, **kwargs):
kwargs['useCache'] = True
ApacheSSLServer.__init__(self, *args, **kwargs)
class StandaloneServer(RepositoryServer):
sslEnabled = True
def __init__(self, *args, **kwargs):
RepositoryServer.__init__(self, *args, **kwargs)
self.serverpid = -1
if 'SERVER_FILE_PATH' in os.environ:
self.serverFilePath = os.environ['SERVER_FILE_PATH']
self.delServerPath = False
else:
self.serverFilePath = None
self.delServerPath = True
self.serverLog = self.reposDir + '/server.log'
util.removeIfExists(self.serverLog)
def start(self, resetDir = True):
if self.serverpid != -1:
return
if resetDir:
if os.path.exists(self.reposDir):
shutil.rmtree(self.reposDir)
os.mkdir(self.reposDir)
self.contents.reset()
if self.reposDB:
if resetDir:
self.reposDB.reset()
self.reposDB.stop()
sb = os.stat(self.server)
if not stat.S_ISREG(sb.st_mode) or not os.access(self.server, os.X_OK):
print "bad server path: %s" % self.server
sys.exit(1)
if self.serverFilePath is None:
self.serverFilePath = testhelp.getTempDir('conarytest-server-file-')
if getattr(self, 'socket', None):
self.socket.close()
self.socket = None
self.serverpid = os.fork()
if self.serverpid == 0:
try:
log = os.open(self.serverLog, os.O_WRONLY | os.O_CREAT | os.O_APPEND)
os.dup2(log, 1)
os.dup2(log, 2)
os.close(log)
print "starting server"
sys.stdout.flush()
serverrc = os.path.join(self.reposDir, 'serverrc')
conaryrc = os.path.join(self.reposDir, 'conaryrc')
self.writeServerConfigFile(serverrc, port=self.port,
conaryrc = conaryrc)
args = (sys.executable, self.server, '--config-file', serverrc)
#if self.reposDB:
# self.reposDB.stop()
os_utils.osExec(args)
except:
traceback.print_exc()
os._exit(70)
def stop(self):
if self.serverpid != -1:
signals = [signal.SIGTERM, signal.SIGTERM, signal.SIGKILL]
if os.environ.get('COVERAGE_DIR', None):
signals.insert(0, signal.SIGUSR2)
for signum in signals:
os.kill(self.serverpid, signum)
pid, status = os.waitpid(self.serverpid, os.WNOHANG)
if pid:
# Process successfully reaped
self.serverpid = -1
break
time.sleep(0.5)
else:
# Still not dead 0.5s after a SIGKILL, keep waiting.
os.waitpid(self.serverpid, 0)
if self.reposDB:
self.reposDB.stop()
self.reposDB = None
if self.serverFilePath and self.delServerPath:
util.rmtree(self.serverFilePath)
self.serverFilePath = None
def isStarted(self):
return self.serverpid != -1 or self.reposDB is not None
def getServerConfigPath(self):
return os.path.join(self.reposDir, 'serverrc')
class ExistingServer(RepositoryServer):
def __init__(self, name, port=8000):
RepositoryServer.__init__(self, [name])
self.port = port
self.reposDir = None
self.name = name
#self.reset()
def reset(self):
repos = netclient.StandaloneServer(self.getMap())
repos.c[self.name].reset()
self.needsPGPKey = True
def start(self):
pass
def stop(self):
pass
class ProxyServerOverrides:
def writeServerConfigFile(self, configFile, **kw):
configValues = {
'proxyContentsDir' : self.contents.getPath(),
'changesetCacheDir' : os.path.join(self.reposDir, 'cscache'),
'tmpDir' : self.reposDir,
'traceLog' : '3 %s' %
os.path.join(self.reposDir, 'trace.log'),
'logFile' : os.path.join(self.reposDir, 'proxy.log')
}
if self.capsuleServerUrl:
configValues['capsuleServerUrl'] = self.capsuleServerUrl
# We only proxy localhost1
configValues['injectCapsuleContentServers'] = 'localhost1'
if self.cacheTimeout is not None:
configValues['memCacheTimeout'] = "%d" % self.cacheTimeout
if self.cacheLocation is not None:
configValues['memCache'] = "%s" % self.cacheLocation
# discard this for proxies
kw.pop('conaryrc', False)
if self.proxies:
for k, v in self.proxies.items():
if v.startswith('conary'):
configValues["conaryProxy " + k] = "http" + v[6:]
else:
configValues["proxy " + k] = v
# Add the command line options
configValues.update(kw)
if self.sslEnabled and self.useSSL and self.sslCert:
self.writeSSLRepoConfig(configValues)
f = open(configFile, "w+")
for item in configValues.iteritems():
print >> f, "%s %s" % item
for ent in self.entitlements:
print >> f, "entitlement %s %s" % ent
for user in self.users:
print >> f, "user %s %s %s" % user
f.close()
def updateConfig(self, cfg):
cfg.configLine("conaryProxy http http://localhost:%s" % self.port)
def reset(self):
self.contents.reset()
csCacheDir = os.path.join(self.reposDir, 'cscache')
shutil.rmtree(csCacheDir, ignore_errors = True)
os.mkdir(csCacheDir)
self.contents.reset()
def __init__(self, entitlements, users, capsuleServerUrl, cacheTimeout,
cacheLocation):
self.entitlements = entitlements
self.users = users
self.capsuleServerUrl = capsuleServerUrl
self.cacheTimeout = cacheTimeout
self.cacheLocation = cacheLocation
class StandaloneProxyServer(ProxyServerOverrides, StandaloneServer):
def __init__(self, *args, **kwargs):
entitlements = kwargs.pop('entitlements', [])
users = kwargs.pop('users', [])
capsuleServerUrl = kwargs.pop('capsuleServerUrl', None)
cacheTimeout = kwargs.pop('cacheTimeout', None)
cacheLocation = kwargs.pop('cacheLocation', None)
ProxyServerOverrides.__init__(self, entitlements, users,
capsuleServerUrl, cacheTimeout, cacheLocation)
StandaloneServer.__init__(self, *args, **kwargs)
class StandaloneSSLProxyServer(ProxyServerOverrides, StandaloneServer):
def __init__(self, *args, **kwargs):
entitlements = kwargs.pop('entitlements', [])
users = kwargs.pop('users', [])
capsuleServerUrl = kwargs.pop('capsuleServerUrl', None)
ProxyServerOverrides.__init__(self, entitlements, users,
capsuleServerUrl)
kwargs['useSSL'] = True
kwargs['forceSSL'] = True
StandaloneServer.__init__(self, *args, **kwargs)
class ApacheProxyServer(ProxyServerOverrides, ApacheServer):
def __init__(self, *args, **kwargs):
entitlements = kwargs.pop('entitlements', [])
users = kwargs.pop('users', [])
capsuleServerUrl = kwargs.pop('capsuleServerUrl', None)
cacheTimeout = kwargs.pop('cacheTimeout', None)
cacheLocation = kwargs.pop('cacheLocation', None)
ProxyServerOverrides.__init__(self, entitlements, users,
capsuleServerUrl, cacheTimeout, cacheLocation)
ApacheServer.__init__(self, *args, **kwargs)
class ApacheSSLProxyServer(ProxyServerOverrides, ApacheSSLServer):
def __init__(self, *args, **kwargs):
entitlements = kwargs.pop('entitlements', [])
users = kwargs.pop('users', [])
capsuleServerUrl = kwargs.pop('capsuleServerUrl', None)
ProxyServerOverrides.__init__(self, entitlements, users,
capsuleServerUrl)
ApacheSSLServer.__init__(self, *args, **kwargs)
class ServerCache:
serverType = ''
def __init__(self):
self.servers = [ None ] * 5
def stopServer(self, serverIdx):
if self.servers[serverIdx] is not None:
server = self.servers[serverIdx]
self.servers[serverIdx] = None
server.stop()
def getCachedServer(self, serverIdx):
return self.servers[serverIdx]
def startServer(self, reposDir, conaryPath, SQLserver, serverIdx = 0,
requireSigs = False, serverName = None, authCheck = None,
entCheck = None, authTimeout = None,
readOnlyRepository=False, needsPGPKey=True,
useSSL=False, sslCert=None, sslKey=None, forceSSL = False,
closed = False, commitAction = None, deadlockRetry = None,
resetDir = True, excludeCapsuleContents = False,
**kwargs):
if self.servers[serverIdx] is not None:
self.servers[serverIdx].resetIfNeeded()
return self.servers[serverIdx]
if serverName is None:
name = 'localhost'
if serverIdx > 0:
name += str(serverIdx)
else:
name = serverName
envname = 'CONARY_SERVER'
if serverIdx > 0:
reposDir += '-%d' %serverIdx
envname += str(serverIdx)
if not os.path.isdir(reposDir):
os.mkdir(reposDir)
reposDB = SQLserver.getDB("testdb%d" % serverIdx,
keepExisting = not resetDir)
server, serverClass, serverDir, proxyClass, proxy = \
self.getServerClass(envname, useSSL)
if not serverClass and serverDir:
return server
contents = ContentStore(reposDir + '/contents')
self.servers[serverIdx] = serverClass(name, reposDB, contents, server,
serverDir,
reposDir,
conaryPath,
self.getMap(),
requireSigs,
authCheck = authCheck,
entCheck = entCheck,
authTimeout = authTimeout,
readOnlyRepository = readOnlyRepository,
serverIdx = serverIdx,
useSSL = useSSL,
sslCert = sslCert,
sslKey = sslKey,
forceSSL = forceSSL,
deadlockRetry = deadlockRetry,
closed = closed,
commitAction = commitAction,
excludeCapsuleContents =
excludeCapsuleContents,
**kwargs)
self.servers[serverIdx].start(resetDir = resetDir)
return self.servers[serverIdx]
def getServerClass(self, envname, useSSL):
useDefault = False
server = os.environ.get(envname, None)
kw = {}
if server is None:
useDefault = True
server = os.environ.get('CONARY_SERVER', None)
if server is None:
server = server_path
if useSSL and server.startswith('apache') and 'ssl' not in server:
server = 'apachessl' + server[6:]
srvClassMap = [
('apache', ApacheServer),
('apachecached', ApacheServerWithCache),
('apachessl', ApacheSSLServer),
('apachesslcached', ApacheSSLServerWithCache),
]
serverDir = serverClass = None
for srvName, srvClass in srvClassMap:
if server == srvName:
serverDir = resources.get_path('conary', 'server')
serverClass = srvClass
break
if server.startswith(srvName + ':'):
server = serverDir = server.split(":", 1)[1]
serverClass = srvClass
break
if serverDir is None: # Not found in the previous mappings
# use localhost: only if explicitly set
if server.startswith("localhost:") and not useDefault:
server = 'localhost'
serverDir = None
serverClass = ExistingServer
else:
serverClass = StandaloneServer
serverDir = os.path.dirname(server)
conaryProxyType = os.environ.get('CONARY_PROXY', None)
if conaryProxyType is not None:
if conaryProxyType == 'standalone':
proxyClass = StandaloneProxyServer
#proxyPath = server
proxyPath = server_path
elif conaryProxyType == 'apache':
proxyClass = ApacheProxyServer
proxyPath = server
else:
raise ValueError, "Unknown setting for CONARY_PROXY '%s'" % \
conaryProxyType
else:
proxyClass = None
proxyPath = None
return server, serverClass, serverDir, proxyClass, proxyPath
def resetAllServers(self):
for i in range(len(self.servers)):
server = self.servers[i]
if server is not None:
server.reset()
def resetAllServersIfNeeded(self):
for i in range(len(self.servers)):
server = self.servers[i]
if server is not None:
server.resetIfNeeded()
def stopAllServers(self, clean=False):
for i in range(len(self.servers)):
server = self.servers[i]
if server is not None:
self.servers[i] = None
server.stop()
if clean and hasattr(server, 'reposDir'):
util.rmtree(server.reposDir, ignore_errors=True)
def getServer(self, serverIdx=0):
return self.servers[serverIdx]
def getMap(self):
servers = {}
for server in self.servers:
if server:
servers.update(server.getMap())
return servers
def getServerNames(self):
for server in self.servers:
if server:
yield server.getName()
_servers = ServerCache()
_reposDir = None
_proxy = None
_httpProxy = None
def getReposDir(globalvar, testname):
if globalvar:
return globalvar
if _isIndividual():
globalvar = '/tmp/%s/repos' % testname
if not os.access(globalvar, os.W_OK):
globalvar = ('/tmp/%s-%s/repos' % (testname, os_utils.effectiveUser))
else:
globalvar = testhelp.getTempDir('%s-repos-' % testname)
# add /repos to the end of this so that the proxy can live in
# this temp directory too
globalvar += '/repos'
os.mkdir(globalvar)
return globalvar
class RepositoryHelper(testhelp.TestCase):
topDir = None
defLabel = versions.Label("localhost@rpl:linux")
def __init__(self, *args, **kw):
testhelp.TestCase.__init__(self, *args, **kw)
global _servers, _proxy
self.servers = _servers
self.proxy = _proxy
def _getReposDir(self):
## Need to be able to override this in base classes
global _reposDir
_reposDir = getReposDir(_reposDir, 'conarytest')
return _reposDir
def setUp(self):
if 'CONARY_IDGEN' in os.environ:
className = "IdGen%s" % os.environ['CONARY_IDGEN']
cook._IdGen = sys.modules[__name__].__dict__[className]
if _isIndividual():
self.topDir = '/tmp/conarytest-%s' % os_utils.effectiveUser
if self.topDir:
self.tmpDir = self.topDir
else:
self.tmpDir = testhelp.getTempDir('conarytest-')
self.reposDir = self._getReposDir()
self.workDir = self.tmpDir + "/work"
self.buildDir = self.tmpDir + "/build"
self.rootDir = self.tmpDir + "/root"
self.cacheDir = self.tmpDir + "/cache"
self.configDir = self.tmpDir + "/cfg"
if self.topDir:
self.reset()
self.cfg = conarycfg.ConaryConfiguration(False)
self.cfg.name = 'Test'
self.cfg.contact = 'http://bugzilla.rpath.com/'
self.cfg.installLabelPath = conarycfg.CfgLabelList([ self.defLabel ])
self.cfg.installLabel = self.defLabel
self.cfg.buildLabel = self.defLabel
self.cfg.buildPath = self.buildDir
self.cfg.dbPath = '/var/lib/conarydb'
self.cfg.debugRecipeExceptions = False
self.cfg.repositoryMap.clear()
self.cfg.useDir = None
self.cfg.quiet = True
self.cfg.resolveLevel = 1
self.cfg.user.addServerGlob('*', 'test', 'foo')
# Keep HTTP retries from blocking the testsuite.
self.cfg.connectAttempts = 1
global _proxy
self.proxy = _proxy
# set the siteConfigPath to be absolute, only including the
# files from the current conary that's being tested.
conaryDir = resources.get_path()
if conaryDir.startswith('/usr') or '_ROOT_' in conaryDir:
if '_ROOT_' in conaryDir:
# we're doing testall - use a different path
offset = conaryDir.index('_ROOT_') + len('_ROOT_')
else:
offset = 0
siteDir = conaryDir[:offset] + '/etc/conary/site'
componentDir = conaryDir[:offset] + '/etc/conary/components'
else:
siteDir = conaryDir + '/config/site'
componentDir = conaryDir + '/config/components'
self.cfg.siteConfigPath = [ cfgtypes.Path(siteDir) ]
self.cfg.componentDirs = [ cfgtypes.Path(componentDir) ]
# this causes too much trouble; turn it on only for the
# test(s) where we care
self.cfg.configComponent = False
self.cfg.root = self.rootDir
self.cfg.lookaside = self.cacheDir
os.umask(0022)
# set up the flavor based on the defaults in use
self.initializeFlavor()
self._origDir = os.getcwd()
testhelp.TestCase.setUp(self)
self.cfg.buildLabel = self.defLabel
self.cfg.installLabelPath = conarycfg.CfgLabelList([self.defLabel])
self.cfg.defaultMacros = [
resources.get_archive('macros'),
resources.get_archive('macros.d', '*'),
resources.get_archive('site'),
]
self.cfg.siteConfigPath = [resources.get_archive('site')]
self.logFilter.clear()
self.cfg.sourceSearchDir = self.sourceSearchDir = resources.get_archive()
self.cfg.enforceManagedPolicy = False
self.cfg.resolveLevel = 2
self.cfg.updateThreshold = 10
policyPath = os.environ.get('CONARY_POLICY_PATH',
'/usr/lib/conary/policy').split(':')
self.cfg.policyDirs = policyPath
self.cfg.baseClassDir = self.tmpDir + "/baseclasses"
# set up the keyCache so that it won't prompt for passwords in
# any of the test suites.
keyCache = openpgpkey.OpenPGPKeyFileCache()
openpgpkey.setKeyCache(keyCache)
# pre-populate private key cache
keyCache.setPrivatePath(resources.get_archive('secring.gpg'))
self.prepopulateKeyCache(keyCache)
# Create dummy keyring
pubRing = util.joinPaths(self.configDir, 'gpg', 'pubring.gpg')
# pre-populate public key cache
self.cfg.pubRing = [ pubRing, resources.get_archive('pubring.gpg') ]
keyCache.setPublicPath(self.cfg.pubRing)
keyCache.getPublicKey('')
self.origTroveVersion = (trove.TROVE_VERSION, trove.TROVE_VERSION_1_1)
if self.topDir and os.path.isdir(self.tmpDir):
self.reset()
else:
if not os.path.exists(self.tmpDir):
os.mkdir(self.tmpDir)
os.mkdir(self.workDir)
os.mkdir(self.rootDir)
os.mkdir(self.cacheDir)
os.mkdir(self.configDir)
# save the original environment
self.origEnv = dict(os.environ)
# default recipes only need to be loaded for certain tests
loadrecipe._defaultsLoaded = True
# Reset IP cache
httputils.IPCache.clear()
def prepopulateKeyCache(self, keyCache):
fingerprint = '95B457D16843B21EA3FC73BBC7C32FC1F94E405E'
keyCache.getPrivateKey(fingerprint, '111111')
keyCache.getPrivateKey('', '111111')
def tearDown(self):
log.setVerbosity(log.WARNING)
self.resetFlavors()
os.chdir(self._origDir)
testhelp.TestCase.tearDown(self)
if not _isIndividual():
self.reset()
shutil.rmtree(self.tmpDir)
trove.TROVE_VERSION = self.origTroveVersion[0]
trove.TROVE_VERSION_1_1 = self.origTroveVersion[1]
self.logFilter.clear()
# restore the environment
for key in os.environ.keys():
del os.environ[key]
for key, value in self.origEnv.iteritems():
os.environ[key] = value
if hasattr(self, 'cfg'):
del self.cfg
def getRepositoryClient(self, user = 'test', password = 'foo',
serverIdx = None, repositoryMap = None):
cfg = copy.copy(self.cfg)
self.cfg.entitlementDirectory = '/tmp'
cfg.user = conarycfg.UserInformation()
if repositoryMap is None:
cfg.repositoryMap = conarycfg.RepoMap()
if serverIdx is None:
for name in self.servers.getServerNames():
cfg.user.addServerGlob(name, user, password)
cfg.repositoryMap.update(self.servers.getMap())
else: # we only need to talk to a particular server instance
server = self.servers.getCachedServer(serverIdx)
if server is not None:
for name in server.nameList:
cfg.user.addServerGlob(name, user, password)
cfg.repositoryMap.update(server.getMap())
else:
cfg.repositoryMap = repositoryMap
client = conaryclient.ConaryClient(cfg)
return client.getRepos()
def addUserAndRole(self, repos, reposLabel, user, pw):
repos.addRole(reposLabel, user)
repos.addUser(reposLabel, user, pw)
repos.updateRoleMembers(reposLabel, user, [user])
def setupUser(self, repos, reposLabel, user, pw, troves, label):
self.addUserAndRole(repos, reposLabel, user, pw)
repos.addAcl(reposLabel, user, troves, label)
repos.setRoleCanMirror(reposLabel, user, True)
return self.getRepositoryClient(user = user, password = pw)
def printRepMap(self):
rmap = self.servers.getMap()
for name, url in rmap.items():
print 'repositoryMap %s %s' %(name, url)
def openDatabase(self, root=None):
if root is None:
root = self.rootDir
return database.Database(root, self.cfg.dbPath)
def getConaryClient(self):
return conaryclient.ConaryClient(self.cfg)
def openRepository(self, *args, **kwargs):
for count in range(3):
try:
return self.__openRepository(*args, **kwargs)
except:
time.sleep(0.5 * (count + 1))
return self.__openRepository(*args, **kwargs)
def __openRepository(self, serverIdx=0, requireSigs=False,
serverName=None, authCheck=None, entCheck=None,
readOnlyRepository=False, proxies=None,
useSSL=False, sslCert=None, sslKey=None,
authTimeout=None, forceSSL=False,
closed=False, commitAction=None,
deadlockRetry=None, serverCache=None,
resetDir=True, excludeCapsuleContents=False,
**kwargs):
if serverCache is None:
serverCache = self.servers
server = serverCache.getCachedServer(serverIdx)
SQLserver = sqlharness.start(self.topDir)
newServer = server is None
reposDir = self.reposDir
if newServer:
if serverCache.serverType:
reposDir += '-%s' % serverCache.serverType
server = serverCache.startServer(reposDir, resources.get_path(), SQLserver,
serverIdx, requireSigs, serverName,
authCheck = authCheck,
entCheck = entCheck,
readOnlyRepository=readOnlyRepository,
useSSL = useSSL,
sslCert = sslCert,
sslKey = sslKey,
authTimeout = authTimeout,
forceSSL = forceSSL,
closed = closed,
commitAction = commitAction,
deadlockRetry = deadlockRetry,
excludeCapsuleContents =
excludeCapsuleContents,
resetDir = resetDir,
**kwargs)
# We keep this open to stop others from reusing the port; tell the
# code which tracks fd leaks so this doesn't reported
if getattr(server, 'socket', None):
self._expectedFdLeak(server.socket.fileno())
else:
server.setNeedsReset()
if 'CONARY_HTTP_PROXY' in os.environ:
httpAddr = os.environ['CONARY_HTTP_PROXY']
global _httpProxy
if _httpProxy is None and httpAddr:
proxyPath = os.path.join(
os.path.dirname(self.reposDir), "http-proxy")
_httpProxy = self.getHTTPProxy(path = proxyPath)
# make sure map is up to date
self.cfg.repositoryMap.update(serverCache.getMap())
serverPath, serverClass, serverDir, proxyClass, proxyPath = \
serverCache.getServerClass('CONARY_SERVER', useSSL)
if newServer and proxyPath:
# if we're using a proxy, (re)start it with the right server map
proxyDir = os.path.dirname(self.reposDir) + '/proxy'
contents = ContentStore(proxyDir + '/contents')
if self.proxy:
self.proxy.stop()
if proxies is None and _httpProxy is not None:
# No proxies were specified, and we have an HTTP proxy. Use it
# for the Conary proxy
d = lambda: 1
_httpProxy.updateConfig(d)
pp = d.proxy
else:
pp = proxies
self.proxy = proxyClass('proxy', None,
contents, proxyPath, None,
proxyDir, resources.get_path(),
self.cfg.repositoryMap,
None, proxies = pp)
self.proxy.start()
global _proxy
_proxy = self.proxy
if self.proxy:
self.proxy.updateConfig(self.cfg)
elif _httpProxy:
_httpProxy.updateConfig(self.cfg)
count = 0
client = conaryclient.ConaryClient(self.cfg)
repos = client.getRepos()
label = versions.Label("%s@rpl:linux" % server.getName())
# Try to connect several times with the much safer tryConnect
# (which consumes one port, not one port per iteration)
# We wait 60 seconds. Sometimes we're seeing the build bots being
# overloaded, and spawning a server might take longer than 10 seconds
# to come up
try:
sock_utils.tryConnect('localhost', server.port)
except socket.error, e:
msg = 'unable to open networked repository: %s' %str(e)
print >> sys.stderr, msg
print >> sys.stderr, 'server log follows:'
print >> sys.stderr, '-------------------'
f = open(server.serverLog, 'r')
print >> sys.stderr, f.read()
f.close()
try:
# We failed to connect. Try to stop the server,
# hopefully that unblocks the next test
self.stopRepository(serverIdx)
except Exception, e:
print traceback.format_exc()
print 'failed to stop server: %s: %s' % (e.__class__.__name__, e)
raise RuntimeError(msg)
if self.proxy:
sock_utils.tryConnect('localhost', self.proxy.port)
# There may be other things that were not fully started yet, like HTTP
# caches and so on. We'll now try an end-to-end connection.
ready = False
while count < 500:
try:
try:
repos.troveNames(label)
ready = True
break
except Exception, e:
if closed and closed in str(e):
# If in closed mode, stop looping when we get the message
# we expect
break
raise
except repo_errors.OpenError:
pass
time.sleep(0.01)
count += 1
if not ready:
if closed:
# Well, this is a closed repo, we expect it not to pass some
# of the tests above
return repos
#import epdb, sys
#epdb.post_mortem(sys.exc_info()[2])
try:
self.stopRepository(serverIdx)
except:
pass
raise RuntimeError('unable to open networked repository: %s'
%str(e))
if server.needsPGPKey and not server.readOnlyRepository:
ascKey = open(resources.get_archive('key.asc'), 'r').read()
for n in range(50):
try:
repos.addNewAsciiPGPKey(label, 'test', ascKey)
break
except repo_errors.InsufficientPermission:
# This seems to be the #1 cause of transient test failures.
time.sleep(0.1)
else:
raise
server.needsPGPKey = False
return repos
def addfile(self, *fileList, **kwArgs):
cvccmd.sourceCommand(self.cfg, ( "add", ) + fileList, kwArgs )
def revertSource(self, *fileList, **kwArgs):
cvccmd.sourceCommand(self.cfg, ( "revert", ) + fileList, kwArgs )
def setSourceFlag(self, path, text = None, binary = None):
if text:
argSet = { 'text' : True }
elif binary:
argSet = { 'binary' : True }
else:
argSet = {}
cvccmd.sourceCommand(self.cfg, [ "set", path ], argSet )
def describe(self, file):
cvccmd.sourceCommand(self.cfg, [ 'describe', file ], {} )
def markRemovedCmd(self, trvSpec):
oldStdin = sys.stdin
sys.stdin = StringIO.StringIO("Y\n")
try:
self.discardOutput(cvccmd.sourceCommand, self.cfg,
[ 'markremoved', trvSpec ], {} )
finally:
sys.stdin = oldStdin
def markRemoved(self, trvSpec, repos = None):
oldStdin = sys.stdin
sys.stdin = StringIO.StringIO("Y\n")
if not repos:
repos = self.openRepository()
try:
self.discardOutput(checkin.markRemoved, self.cfg, repos, trvSpec)
finally:
sys.stdin = oldStdin
def mkbranch(self, src, newVer, what=None, shadow = False, binaryOnly=False,
sourceOnly=False, ignoreConflicts=True, targetFile = None):
if isinstance(src, (list, tuple)):
troveSpecs = src
else:
assert(what)
if type(src) == str and src[0] != "/" and src.find("@") == -1:
assert(what)
src = "/" + self.cfg.buildLabel.asString() + "/" + src
elif isinstance(src, (versions.Version, versions.Label)):
assert(what)
src = src.asString()
troveSpecs = [what + '=' + src]
if type(newVer) == str and newVer[0] == "@":
newVer = versions.Label("localhost" + newVer)
elif isinstance(newVer, str):
newVer = versions.Label(newVer)
repos = self.openRepository()
branch.branch(repos, self.cfg, newVer.asString(),
troveSpecs = troveSpecs, makeShadow = shadow,
sourceOnly = sourceOnly, binaryOnly = binaryOnly,
forceBinary = True, ignoreConflicts = ignoreConflicts,
targetFile = targetFile)
def checkout(self, nameList, versionStr = None, dir = None,
callback = None):
dict = {}
if dir:
dict = { "dir" : dir }
if callback is None:
callback = checkin.CheckinCallback()
if type(nameList) is str:
nameList = [ nameList ]
if versionStr:
assert(len(nameList) == 1)
cvccmd.sourceCommand(self.cfg, [ "checkout",
nameList[0] +'='+ versionStr ],
dict, callback=callback)
else:
cvccmd.sourceCommand(self.cfg, [ "checkout" ] + nameList, dict,
callback=callback)
def refresh(self, globs = None, logLevel=log.INFO):
callback = checkin.CheckinCallback()
level = log.getVerbosity()
log.setVerbosity(logLevel)
if globs:
args = [globs]
else:
args = []
cvccmd.sourceCommand(self.cfg, ["refresh"] + args, None,
callback=callback)
log.setVerbosity(level)
def commit(self, logLevel=log.INFO, callback=None, message = 'foo',
cfg=None):
self.openRepository()
if not callback:
callback = checkin.CheckinCallback()
if not cfg:
cfg = self.cfg
level = log.getVerbosity()
log.setVerbosity(logLevel)
cvccmd.sourceCommand(cfg, [ "commit" ], { 'message' : message },
callback=callback)
log.setVerbosity(level)
def context(self, name = None, cfg=None):
if cfg is None:
cfg = self.cfg
cvccmd.sourceCommand(cfg, [ "context", name ], {})
def diff(self, *args, **kwargs):
self.openRepository()
(retVal, str) = self.captureOutput(cvccmd.sourceCommand,
self.cfg, [ "diff" ] + list(args),
{})
# (working version) Thu Jul 1 09:51:03 2004 (no log message)
# -> (working version) (no log message)
str = re.sub(r'\) .* \(', ') (', str, 1)
if kwargs.get('rc', None) is not None:
assert(kwargs['rc'] == retVal)
return str
def stat(self, *args):
self.openRepository()
(rc, str) = self.captureOutput(cvccmd.sourceCommand,
self.cfg, [ "stat" ] + list(args), {})
return str
def removeDateFromLogMessage(self, str):
# 1.0-2 Test (http://buzilla.rpath.com/) Mon Nov 22 12:11:24 2004
# -> 1.0-2 Test
str = re.sub(r'\(http://bugzilla.rpath.com/\) .*', '', str)
return str
def showLog(self, *args, **argSet):
self.openRepository()
(rc, str) = self.captureOutput(cvccmd.sourceCommand,
self.cfg, [ "log" ] + list(args), argSet)
return self.removeDateFromLogMessage(str)
def annotate(self, *args):
self.openRepository()
(rc, str) = self.captureOutput(cvccmd.sourceCommand,
self.cfg, [ "annotate" ] + list(args),
{})
# remove date information from string
# also remove variable space padding
str = re.sub(r'(\n[^ ]*) *\((.*) .*\):', r'\1 (\2):', str)
# first line doesn't have an \n
str = re.sub(r'^([^ ]*) *\((.*) .*\):', r'\1 (\2):', str)
return str
def rdiff(self, *args):
self.openRepository()
(rc, str) = self.captureOutput(cvccmd.sourceCommand,
self.cfg, [ "rdiff" ] + list(args),
{})
str = re.sub(r'\(http://bugzilla.rpath.com/\).*', '(http://bugzilla.rpath.com/)', str, 1)
return str
def rollbackList(self, root):
db = database.Database(root, self.cfg.dbPath)
(rc, str) = self.captureOutput(rollbacks.listRollbacks, db, self.cfg)
return str
def rollbackCount(self):
f = open(self.rootDir + "/var/lib/conarydb/rollbacks/status")
l = f.readline()
(min, max) = l.split()
max = int(max)
return max
def rollback(self, root, num = None, replaceFiles = False, tagScript = None,
justDatabase = False, showInfoOnly = False,
abortOnError = False, capsuleChangesets = []):
# hack to allow the root as the first parameter
if num is None and type(root) == int:
num = root
root = self.rootDir
self.cfg.root = root
client = conaryclient.ConaryClient(self.cfg)
repos = self.openRepository()
try:
ret = client.applyRollback("r.%d" % num,
replaceFiles=replaceFiles,
tagScript = tagScript,
justDatabase = justDatabase,
showInfoOnly = showInfoOnly,
abortOnError = abortOnError,
capsuleChangesets = capsuleChangesets)
finally:
client.close()
return ret
def newpkg(self, name, factory = None):
self.openRepository()
args = {}
if factory:
args['factory'] = factory
cvccmd.sourceCommand(self.cfg, [ "newpkg", name], args)
def makeSourceTrove(self, name, recipeFile, buildLabel=None,
extraFiles=None, factory=None):
if factory is None:
factory = (name.startswith('factory-') and 'factory') or None
oldBuildLabel = self.cfg.buildLabel
if buildLabel:
self.cfg.buildLabel = buildLabel
origDir = os.getcwd()
try:
os.chdir(self.workDir)
self.newpkg(name, factory = factory)
os.chdir(name)
if recipeFile is not None:
self.writeFile(name + '.recipe', recipeFile)
self.addfile(name + '.recipe')
if extraFiles:
for fname in extraFiles:
kwargs = dict(binary=False, text=False)
if isinstance(fname, tuple):
fname, ftype = fname[:2]
if ftype == 'binary':
kwargs['binary'] = True
elif ftype == 'text':
kwargs['text'] = True
bname = os.path.basename(fname)
shutil.copy(fname, bname)
self.addfile(bname, **kwargs)
self.commit()
finally:
os.chdir(origDir)
self.cfg.buildLabel = oldBuildLabel
def updateSourceTrove(self, name, recipeFile, versionStr=None):
origDir = os.getcwd()
os.chdir(self.workDir)
self.checkout(name, versionStr=versionStr)
os.chdir(name)
self.writeFile(name + '.recipe', recipeFile)
self.commit()
os.chdir(origDir)
def remove(self, name):
self.openRepository()
cvccmd.sourceCommand(self.cfg, [ "remove", name], {})
def rename(self, oldname, newname):
self.openRepository()
cvccmd.sourceCommand(self.cfg, [ "rename", oldname, newname], {})
def update(self, *args):
self.openRepository()
callback = checkin.CheckinCallback()
cvccmd.sourceCommand(self.cfg, [ "update" ] + list(args), {},
callback=callback)
def resetFlavors(self):
use.clearFlags()
use.track(False)
def resetAllRepositories(self):
self.servers.resetAllServers()
if self.proxy:
self.proxy.reset()
def merge(self, *args):
self.openRepository()
cvccmd.sourceCommand(self.cfg, [ "merge" ] + list(args), {})
def resetRepository(self, serverIdx=0):
server = self.servers.getServer(serverIdx)
if server is not None:
server.reset()
self.openRepository(serverIdx=serverIdx)
def stopRepository(self, serverIdx=0):
server = self.servers.getServer(serverIdx)
if server is not None:
self.servers.stopServer(serverIdx)
def resetWork(self):
if os.path.exists(self.workDir):
util.rmtree(self.workDir)
if os.path.exists(self.workDir):
raise IOError, '%s exists but must not!' %self.workDir
util.mkdirChain(self.workDir)
def resetRoot(self):
if os.path.exists(self.rootDir):
util.rmtree(self.rootDir)
util.mkdirChain(self.rootDir)
def resetCache(self):
if os.path.exists(self.cacheDir):
util.rmtree(self.cacheDir)
util.mkdirChain(self.cacheDir)
def reset(self):
self.servers.resetAllServersIfNeeded()
self.resetWork()
self.resetRoot()
self.resetCache()
def _cvtVersion(self, verStr, source=False):
if isinstance(verStr, versions.Version):
return verStr
verStr = str(verStr)
if verStr[0] == ':':
buildLabel = self.cfg.buildLabel
if '/' not in verStr:
verStr += '/1'
verStr = '/%s@%s%s' % (buildLabel.getHost(),
buildLabel.getNamespace(),
verStr)
elif verStr[0] == '@':
buildLabel = self.cfg.buildLabel
if '/' not in verStr:
verStr += '/1'
verStr = '/%s%s' % (buildLabel.getHost(), verStr)
elif verStr[0] != '/':
if '@' in verStr:
if '/' not in verStr:
verStr += '/1'
verStr = '/%s' % verStr
else:
verStr = '/%s/%s' % (self.cfg.buildLabel.asString(), verStr)
if '-' not in verStr:
if source:
verStr += '-1'
else:
verStr += '-1-1'
try:
v = versions.VersionFromString(verStr).copy()
v.resetTimeStamps()
return v
except errors.ParseError:
pass
try:
newVerStr = verStr
if '-' not in verStr.rsplit('/')[-1]:
if source:
newVerStr += '-1'
else:
newVerStr += '-1-1'
v = versions.VersionFromString(newVerStr).copy()
v.resetTimeStamps()
return v
except errors.ParseError:
pass
v = versions.ThawVersion(verStr)
return v
def addCollection(self, name, version=None, strongList=None,
weakRefList=None, calcSize=False, repos=None,
defaultFlavor=None, createComps=False,
existsOkay=False, redirect=None,
changeSetFile = None, buildReqs=None,
labelPath=None, sourceName=None,
preUpdateScript = None, postInstallScript = None,
postUpdateScript = None,
preRollbackScript = None, postRollbackScript = None,
preInstallScript = None, preEraseScript = None,
postEraseScript = None,
compatClass = None, flavor = None,
loadedReqs=None, metadata=None, imageGroup = None,
pathConflicts=None):
if not repos:
repos = self.openRepository()
if isinstance(version, (list, tuple)):
strongList = version
version = None
assert(strongList or redirect)
if version is None and defaultFlavor is None:
name, version, defaultFlavor = cmdline.parseTroveSpec(name)
if not version:
version = '1.0'
version = self._cvtVersion(version)
assert(':' not in name and not name.startswith('fileset'))
if defaultFlavor is None:
defaultFlavor = deps.Flavor()
elif isinstance(defaultFlavor, str):
defaultFlavor = deps.parseFlavor(defaultFlavor)
fullList = {}
if weakRefList is None:
hasWeakRefs = False
weakRefList = []
else:
hasWeakRefs = True
idx = 0
for weakRef, troveList in zip((False, True), (strongList, weakRefList)):
for info in troveList:
idx += 1
trvFlavor = None
trvVersion = None
byDefault = True
if isinstance(info, str):
trvName = info
if '=' in trvName or '[' in trvName:
(trvName, trvVersion, trvFlavor) \
= cmdline.parseTroveSpec(trvName)
elif isinstance(info, trove.Trove):
(trvName, trvVersion, trvFlavor) \
= info.getNameVersionFlavor()
elif len(info) == 1:
(trvName,) = info
elif len(info) == 2:
(trvName, item) = info
if isinstance(item, bool):
byDefault = item
else:
trvVersion = item
elif len(info) == 3:
(trvName, trvVersion, trvFlavor) = info
elif len(info) == 4:
(trvName, trvVersion, trvFlavor, byDefault) = info
else:
assert(False)
if trvVersion is None and trvFlavor is None:
(trvName, trvVersion, trvFlavor) = \
cmdline.parseTroveSpec(trvName)
if not trvVersion:
trvVersion = version
else:
trvVersion = self._cvtVersion(trvVersion)
if trvFlavor is None:
trvFlavor = defaultFlavor
elif type(trvFlavor) == str:
trvFlavor = deps.parseFlavor(trvFlavor)
if trvName[0] == ':':
trvName = name + trvName
if createComps and ':' in trvName:
self.addComponent(trvName, trvVersion.freeze(),
str(trvFlavor), filePrimer=idx, sourceName=sourceName)
fullList[(trvName, trvVersion, trvFlavor)] = (byDefault,
weakRef)
if flavor:
flavor = deps.parseFlavor(flavor, raiseError=True)
else:
flavor = deps.mergeFlavorList([x[2] for x in fullList],
deps.DEP_MERGE_TYPE_DROP_CONFLICTS)
if not hasWeakRefs:
collList = [ x for x in fullList.iteritems() if trove.troveIsCollection(x[0][0])]
troves = repos.getTroves([x[0] for x in collList], withFiles=False)
for (troveTup, (byDefault, _)), trv in itertools.izip(collList,
troves):
for childInfo in trv.iterTroveList(strongRefs=True,
weakRefs=True):
childByDefault = (trv.includeTroveByDefault(*childInfo)
and byDefault)
currInfo = fullList.get(childInfo, None)
if currInfo:
childByDefult = currInfo[0] or childByDefault
fullList[childInfo] = (childByDefault, currInfo[1])
else:
fullList[childInfo] = (childByDefault, True)
if redirect is not None:
redirectList = []
for info in redirect:
if info is None:
redirectList.append((None, None, None))
continue
if not isinstance(info, (list, tuple)):
info = [info]
if len(info) == 1:
redirName = info[0]
redirBranch = version.branch()
redirFlavor = flavor
elif len(info) == 2:
redirName, redirBranch = info
redirBranch = versions.VersionFromString(redirBranch)
redirFlavor = deps.parseFlavor('')
else:
redirName, redirBranch, redirFlavor = info
redirBranch = versions.VersionFromString(redirBranch)
redirFlavor = deps.parseFlavor(redirFlavor)
redirectList.append((redirName, redirBranch, redirFlavor))
# add a pkg diff
if redirect is not None:
troveType = trove.TROVE_TYPE_REDIRECT
else:
troveType = trove.TROVE_TYPE_NORMAL
coll = trove.Trove(name, version, flavor, None, type=troveType)
if existsOkay and repos.hasTrove(name, version, flavor):
return repos.getTrove(name, version, flavor)
coll.setIsCollection(True)
coll.setSize(0) # None is widely used as a shortcut
for info, (byDefault, weakRef) in fullList.iteritems():
coll.addTrove(*info, **dict(byDefault=byDefault, weakRef=weakRef))
if not sourceName:
sourceName = name + ':source'
coll.setSourceName(sourceName)
coll.setBuildTime(1238075164.694746)
if redirect:
for toName, toBranch, toFlavor in redirectList:
coll.addRedirect(toName, toBranch, toFlavor)
else:
coll.setProvides(deps.parseDep('trove: %s' % name))
if buildReqs is not None:
buildReqs = self.makeTroveTupleList(buildReqs)
coll.setBuildRequirements(buildReqs)
if loadedReqs:
loadedReqs = self.makeTroveTupleList(loadedReqs)
coll.setLoadedTroves(loadedReqs)
if pathConflicts is not None:
for path in pathConflicts:
coll.troveInfo.pathConflicts.append(path)
if labelPath:
coll.setLabelPath(labelPath)
if compatClass:
coll.setCompatibilityClass(compatClass)
for spec, script in \
[ (preUpdateScript, coll.troveInfo.scripts.preUpdate),
(postInstallScript, coll.troveInfo.scripts.postInstall),
(postUpdateScript, coll.troveInfo.scripts.postUpdate),
(preRollbackScript, coll.troveInfo.scripts.preRollback),
(postRollbackScript, coll.troveInfo.scripts.postRollback),
(preInstallScript, coll.troveInfo.scripts.preInstall),
(preEraseScript, coll.troveInfo.scripts.preErase),
(postEraseScript, coll.troveInfo.scripts.postErase), ]:
if spec is None: continue
if type(spec) == str:
spec = TroveScript(script = spec)
script.script.set(spec.script)
if spec.conversions:
assert(compatClass)
assert(isinstance(spec, RollbackScript))
script.conversions.addList(
(compatClass, x) for x in spec.conversions)
if calcSize:
compList = [x for x in fullList \
if not trove.troveIsCollection(x[0])]
size = (x.getSize() \
for x in repos.getTroves(compList, withFiles=False))
coll.setSize(sum(x for x in size if x is not None))
if metadata:
if not isinstance(metadata, (list, tuple)):
metadata = [metadata]
for item in metadata:
coll.troveInfo.metadata.addItem(item)
if imageGroup is not None:
coll.troveInfo.imageGroup.set(imageGroup)
coll.computeDigests()
assert(redirect or list(coll.iterTroveList(strongRefs=True)))
# create an absolute changeset
cs = changeset.ChangeSet()
diff = coll.diff(None, absolute = True)[0]
cs.newTrove(diff)
if changeSetFile:
cs.addPrimaryTrove(coll.getName(), coll.getVersion(),
coll.getFlavor())
cs.writeToFile(changeSetFile)
else:
repos.commitChangeSet(cs)
return coll
addQuickTestCollection = addCollection
def makeTroveTupleList(self, troveItems, defaultFlavor=None):
tupleList = []
for item in troveItems:
if isinstance(item, trove.Trove):
tupleList.append(item.getNameVersionFlavor())
elif isinstance(item, tuple):
bflv = None
if len(item) == 1:
bver = self._cvtVersion('1')
bname = item
elif len(item) == 2:
if isinstance(item[0], trove.Trove):
bname, bver = item[0].getName(), item[0].getVersion()
bflv = item[1]
else:
bname, bver = item
bver = self._cvtVersion(bver)
else:
bname, bver, bflv = item
bver = self._cvtVersion(bver)
if bflv is None:
bflv = defaultFlavor
elif isinstance(bflv, str):
bflv = deps.parseFlavor(bflv)
tupleList.append((bname, bver, bflv))
else:
assert 0, "unknown tuple source %s" % item
return tupleList
def addComponent(self, *args, **kw):
changeSetFile = kw.pop('changeSetFile', None)
hidden = kw.pop('hidden', False)
repos = kw.pop('repos', None)
if not repos:
repos = self.openRepository()
kw['repos'] = repos
t, cs = self.Component(*args, **kw)
if cs is not None:
if changeSetFile:
cs.writeToFile(changeSetFile)
else:
repos.commitChangeSet(cs, hidden = hidden)
return t
def Component(self, troveName, version=None, flavor=None,
fileContents=None,
provides=deps.DependencySet(),
requires=deps.DependencySet(),
filePrimer=0, setConfigFlags=True,
repos=None, existsOkay=False, pathIdSalt='',
redirect=None, sourceName=None, metadata=None,
factory=None, capsule=None,
versus=None, buildTime=1238075164.694746):
if isinstance(flavor, list):
fileContents = flavor
flavor = None
elif isinstance(version, list):
fileContents = version
version = None
if version is None and flavor is None:
troveName, version, flavor = cmdline.parseTroveSpec(troveName)
if not version:
version = '1.0'
if flavor is None:
flavor = ''
troveVersion = self._cvtVersion(version,
source=troveName.endswith(':source'))
isSource = troveName.endswith(':source')
assert(':' in troveName or trove.troveIsFileSet(troveName))
componentDir = self.workDir + "/component"
if os.path.exists(componentDir):
shutil.rmtree(componentDir)
util.mkdirChain(componentDir)
if isinstance(flavor, list):
assert(fileContents is None)
fileContents = flavor
flavor = ''
flavor = deps.parseFlavor(flavor)
# add a pkg diff
if redirect is not None:
troveType = trove.TROVE_TYPE_REDIRECT
else:
troveType = trove.TROVE_TYPE_NORMAL
# we create the trove with the wrong flavor here and fix it later
# (by unioning in the file flavors)
t = trove.Trove(troveName, troveVersion, flavor, None, type=troveType)
# set up a file with some contents
fileList = []
if redirect is not None:
redirectList = []
assert(fileContents is None)
for info in redirect:
if info is None:
continue
if not isinstance(info, (list, tuple)):
info = [info]
if len(info) == 1:
redirName = info[0]
redirBranch = troveVersion.branch()
redirFlavor = flavor
elif len(info) == 2:
redirName, redirBranch = info
redirBranch = versions.VersionFromString(redirBranch)
redirFlavor = None
else:
redirName, redirBranch, redirFlavor = info
redirBranch = versions.VersionFromString(redirBranch)
if redirFlavor is not None:
redirFlavor = deps.parseFlavor(redirFlavor)
redirectList.append((redirName, redirBranch, redirFlavor))
else:
if capsule:
assert(capsule.endswith('.rpm'))
f = files.FileFromFilesystem(capsule,
trove.CAPSULE_PATHID)
hdr = rpmhelper.readHeader(open(capsule))
t.addRpmCapsule(os.path.basename(capsule),
troveVersion,
f.fileId(), hdr)
fileList.append((f, trove.CAPSULE_PATHID,
filecontents.FromFilesystem(capsule)))
elif fileContents is None:
path = '/contents%s' % filePrimer
contents = 'hello, world!\n'
if not filePrimer:
filePrimer = '\0'
filePrimer = str(filePrimer)
# Pad it on the left with zeros, up to 16 chars long
pathId = filePrimer.rjust(16, '\1')
pathId = pathId[0:16]
contents = RegularFile(contents = contents, pathId = pathId,
config = None)
fileContents = [(path, contents)]
index = 0
for fileInfo in fileContents:
fileReq = None
fileProv = None
fileFlavor = None
if isinstance(fileInfo, str):
fileInfo = [fileInfo, 'foo']
fileName, contents = fileInfo[0:2]
if isinstance(contents, filetypes._File):
assert(len(fileInfo) == 2)
else:
if len(fileInfo) > 3:
if isinstance(fileInfo[3], (list, tuple)):
fileReq = fileInfo[3][0]
fileProv = fileInfo[3][1]
else:
fileReq = fileInfo[3]
if len(fileInfo) > 2 and fileInfo[2] is not None:
fileVersion = self._cvtVersion(fileInfo[2])
else:
fileVersion = troveVersion
contents = RegularFile(requires = fileReq,
provides = fileProv,
contents = contents)
contents.version = fileVersion
cont = componentDir + '/' + fileName
dir = os.path.dirname(cont)
if not os.path.exists(dir):
util.mkdirChain(dir)
pathId = contents.pathId
if pathId is None:
pathId = sha1helper.md5String(pathIdSalt + fileName)
else:
pathId += '0' * (16 - len(pathId))
f = contents.get(pathId)
f.flags.isSource(isSource)
if contents.config is not None:
f.flags.isConfig(contents.config)
elif ((setConfigFlags and fileName.startswith('/etc'))
or troveName.endswith(':source')):
f.flags.isConfig(True)
index += 1
if capsule and not (f.flags.isConfig() or
getattr(contents, 'isGhost', None)):
# RBL-5684: we force ghost files to not be marked as
# payload
f.flags.isEncapsulatedContent(True)
if contents.version:
fileVersion = self._cvtVersion(contents.version)
elif (versus and versus.hasFile(pathId) and
versus.getFile(pathId)[1] == f.fileId()):
# reuse file version if it hasn't changed
fileVersion = versus.getFile(pathId)[2]
else:
fileVersion = troveVersion
if not troveName.endswith(':source'):
if fileName[0] != '/':
fileName = '/' + fileName
assert(len(pathId) == 16)
t.addFile(pathId, fileName, fileVersion, f.fileId())
if hasattr(contents, 'contents'):
fileList.append((f, pathId, contents.contents))
else:
fileList.append((f, pathId, None))
# find the flavor for this trove; it depends on the flavors of the
# files
for f, pathId, contents in fileList:
flavor.union(f.flavor())
t.changeFlavor(flavor)
# create an absolute changeset
cs = changeset.ChangeSet()
if existsOkay and repos.hasTrove(troveName, troveVersion, flavor):
return repos.getTrove(troveName, troveVersion, flavor), None
if factory is not None:
t.setFactory(factory)
if not redirect:
if isinstance(requires, str):
req = deps.parseDep(requires)
else:
req = requires.copy()
if isinstance(provides, str):
prov = deps.parseDep(provides)
else:
prov = provides.copy()
prov.union(deps.parseDep('trove: %s' % t.getName()))
for f, pathId, contents in fileList:
req.union(f.requires())
prov.union(f.provides())
t.setRequires(req)
t.setProvides(prov)
if not troveName.endswith(':source'):
if not sourceName:
sourceName = troveName.split(":")[0] + ":source"
t.setSourceName(sourceName)
t.computePathHashes()
t.setBuildTime(buildTime)
if redirect:
for toName, toBranch, toFlavor in redirectList:
t.addRedirect(toName, toBranch, toFlavor)
if redirect:
for toName, toBranch, toFlavor in redirectList:
t.addRedirect(toName, toBranch, toFlavor)
size = 0
# add the file and file contents
for f, pathId, contents in fileList:
cs.addFile(None, f.fileId(), f.freeze())
if f.hasContents and not f.flags.isEncapsulatedContent():
cs.addFileContents(pathId, f.fileId(),
changeset.ChangedFileTypes.file, contents,
f.flags.isConfig())
size += f.contents.size()
if metadata:
if not isinstance(metadata, (tuple, list)):
metadata = [metadata]
for item in metadata:
t.troveInfo.metadata.addItem(item)
t.setSize(size)
t.computeDigests()
diff = t.diff(None, absolute = True)[0]
cs.newTrove(diff)
cs.setPrimaryTroveList([t.getNameVersionFlavor()])
return t, cs
addQuickTestComponent = addComponent
def addDbComponent(self, db, name, version='1', flavor='',
provides=deps.DependencySet(),
requires=deps.DependencySet()):
fileList = []
# create a file
cont = self.workDir + '/contents'
f = open(cont, 'w')
f.write('hello, world!\n')
f.close()
pathId = sha1helper.md5FromString('0' * 32)
f = files.FileFromFilesystem(cont, pathId)
fileList.append((f, cont, pathId))
v = self._cvtVersion(version)
flavor = deps.parseFlavor(flavor)
t = trove.Trove(name, v, flavor, None)
for f, name, pathId in fileList:
t.addFile(pathId, '/' + name, v, f.fileId())
t.setRequires(requires)
t.setProvides(provides)
info = db.addTrove(t)
db.addTroveDone(info)
db.commit()
return t
addQuickDbTestPkg = addDbComponent
def addRPMComponent(self, nameSpec, rpmPath, versus = None,
fileContents=None, requires=deps.DependencySet()):
if rpmPath[0] != '/':
rpmPath = resources.get_archive(rpmPath)
f = open(rpmPath, "r")
h = rpmhelper.readHeader(f)
expandDir = self.workDir + '/rpm'
if os.path.exists(expandDir):
shutil.rmtree(expandDir)
os.mkdir(expandDir)
p = os.popen("cd %s; cpio --quiet -iumd" % (expandDir, ), "w")
rpmhelper.extractRpmPayload(f, p)
p.close()
f.close()
fl = []
for path, mode, flags, linksTo, fileColor, rdev in itertools.izip(
h[rpmhelper.OLDFILENAMES],
h[rpmhelper.FILEMODES], h[rpmhelper.FILEFLAGS],
h[rpmhelper.FILELINKTOS],
h[rpmhelper.FILECOLORS],
h[rpmhelper.FILERDEVS]):
if stat.S_ISDIR(mode):
fl.append((path, Directory()))
elif stat.S_ISBLK(mode) or stat.S_ISCHR(mode):
minor = rdev & 0xff | (rdev >> 12) & 0xffffff00
major = (rdev >> 8) & 0xfff
if stat.S_ISBLK(mode):
fl.append((path, BlockDevice(major, minor)))
elif stat.S_ISCHR(mode):
fl.append((path, CharacterDevice(major, minor)))
else:
isConfig = ((flags & rpmhelper.RPMFILE_CONFIG) != 0)
isGhost = ((flags & rpmhelper.RPMFILE_GHOST) != 0)
# You can't have symlinks that are initialContents
if stat.S_ISLNK(mode):
fobj = Symlink(linksTo)
else:
if isGhost:
contents = ''
# can't have files which are both initialContents
# and config
isConfig = False
else:
contents = open(expandDir + path)
if fileColor == 2:
req = 'abi: ELF64(SysV x86_64)'
elif fileColor == 1:
req = 'abi: ELF32(SysV x86)'
else:
req = None
fobj = RegularFile(contents = contents,
config = isConfig,
initialContents = isGhost,
requires = req)
if isGhost:
# RBL-5684: we force ghost files to not be marked as
# payload (see Component)
fobj.isGhost = True
fl.append((path, fobj))
fl.extend(fileContents or [])
return self.addComponent(nameSpec, fileContents = fl,
capsule = rpmPath, versus = versus,
requires=requires)
def addTestPkg(self, num, requires=[], fail=False, content='',
flags=[], localflags=[], packageSpecs=[], subPackages=[],
version='1.0', branch=None,
header='', fileContents='',
tag=None, binary=False):
""" This method is a wrapper around the recipes.py createRecipe
method. It creates the recipe with the given characteristics,
and then commits it to the repository.
num = recipe name is 'test%(num)s
requires = other packages added to the buildRequires of
this package
fail - if true, an exit(1) is added
fileContents - contents of the text file in the package
content - place to add content to the recipe setup() function
header - place to add content to the recipe before setup()
branch - place this source component on a branch
localFlags - check Flags.foo for this recipe for every foo passed in
flags - check use.[Arch,Use].foo, for every [Arch,Use].foo passed in
"""
origDir = os.getcwd()
os.chdir(self.workDir)
pkgname = 'test%d' % num
if not 'packages' in self.__dict__:
self.packages = {}
if num in self.packages:
self.checkout(pkgname, branch)
else:
self.newpkg(pkgname)
os.chdir(pkgname)
if not isinstance(subPackages, (tuple, list)):
subPackages = [subPackages]
if not isinstance(packageSpecs, (tuple, list)):
packageSpecs = [packageSpecs]
fileContents = recipes.createRecipe(num, requires, fail, content,
packageSpecs, subPackages, version=version, flags=flags,
localflags=localflags, header=header, fileContents=fileContents,
tag=tag, binary=binary)
self.writeFile(pkgname + '.recipe', fileContents)
if num not in self.packages:
self.addfile(pkgname + '.recipe')
self.commit()
os.chdir('..')
shutil.rmtree(pkgname)
os.chdir(origDir)
self.packages[num] = pkgname
return fileContents
def cookTestPkg(self, num, logLevel=log.WARNING, macros={}, prep=False):
stdout = os.dup(sys.stdout.fileno())
stderr = os.dup(sys.stderr.fileno())
null = os.open('/dev/null', os.O_WRONLY)
os.dup2(null, sys.stdout.fileno())
os.dup2(null, sys.stderr.fileno())
try:
return cook.cookItem(self.repos, self.cfg, 'test%s' % num, macros=macros, prep=prep)
finally:
os.dup2(stdout, sys.stdout.fileno())
os.dup2(stderr, sys.stderr.fileno())
os.close(null)
os.close(stdout)
os.close(stderr)
def createMetadataItem(self, **kw):
mi = trove.MetadataItem()
for key, value in kw.items():
if isinstance(value, (list, tuple)):
for val in value:
getattr(mi, key).set(val)
else:
getattr(mi, key).set(value)
return mi
def cookFromRepository(self, troveName, buildLabel = None, ignoreDeps = False, repos = None, logBuild = False, callback = None):
if buildLabel:
oldLabel = self.cfg.buildLabel
self.cfg.buildLabel = buildLabel
if not repos:
repos = self.openRepository()
built = self.discardOutput( cook.cookItem, repos, self.cfg, troveName,
ignoreDeps = ignoreDeps, logBuild = logBuild,
callback = callback )
if buildLabel:
self.cfg.buildLabel = oldLabel
return built[0]
def verifyFifo(self, file):
return stat.S_ISFIFO(os.lstat(file).st_mode)
def verifyFile(self, path, contents=None, perms=None):
f = open(path, "r")
other = f.read()
if contents is not None:
if other != contents:
self.fail("contents incorrect for %s" % path)
assert(other == contents)
if perms is not None:
assert(os.stat(path)[stat.ST_MODE] & 0777 == perms)
def verifyNoFile(self, file):
try:
f = open(file, "r")
except IOError, err:
if err.errno == 2:
return
else:
self.fail("verifyNoFile returned unexpected error code: %d" % err.errno)
else:
self.fail("file exists: %s" % file)
def verifySrcDirectory(self, contents, dir = "."):
self.verifyDirectory(contents + [ "CONARY" ], dir)
def verifyDirectory(self, contents, dir = "."):
self.verifyFileList(contents, os.listdir(dir))
def verifyPackageFileList(self, pkg, ideal):
list = [ x[1] for x in pkg.iterFileList() ]
self.verifyFileList(ideal, list)
def verifyTroves(self, pkg, ideal):
actual = [ (x[0], x[1].asString(), x[2]) \
for x in pkg.iterTroveList(strongRefs=True) ]
if sorted(actual) != sorted(ideal):
self.fail("troves don't match expected: got %s expected %s"
%(actual, ideal))
def verifyFileList(self, ideal, actual):
dict = {}
for n in ideal: dict[n] = 1
for n in actual:
if dict.has_key(n):
del dict[n]
else:
self.fail("unexpected file %s" % n)
if dict:
self.fail("files missing %s" % " ".join(dict.keys()))
assert(not dict)
def verifyInstalledFileList(self, dir, list):
paths = {}
for path in list:
paths[path] = True
dirLen = len(dir)
# this skips all of /var/lib/conarydb/
for (dirName, dirNameList, pathNameList) in os.walk(dir):
for path in pathNameList:
if path[0] == ".": continue
fullPath = dirName[dirLen:] + "/" + path
if fullPath == "/var/log/conary": continue
if fullPath.startswith("/var/lib/conarydb/"): continue
if paths.has_key(fullPath):
del paths[fullPath]
else:
self.fail("unexpected file %s" % fullPath)
if paths:
self.fail("files missing %s" % " ".join(paths.keys()))
def cookItem(self, *args, **kw):
return self.discardOutput(cook.cookItem, *args, **kw)
# Kludge to make debugging tests that only fail in Hudson easier
_printOnError = False
def cookObject(self, loader, prep=False, macros={}, sourceVersion = None,
serverIdx = 0, ignoreDeps = False, logBuild = False,
targetLabel = None, repos = None,
groupOptions = None, resume = None):
theClass = loader.getRecipe()
if repos is None:
repos = self.openRepository(serverIdx)
if sourceVersion is None:
sourceVersion = cook.guessSourceVersion(repos, theClass.name,
theClass.version,
self.cfg.buildLabel,
searchBuiltTroves=True)[0]
if not sourceVersion:
# just make up a sourceCount -- there's no version in
# the repository to compare against
sourceVersion = versions.VersionFromString('/%s/%s-1' % (
self.cfg.buildLabel.asString(),
theClass.version))
use.resetUsed()
try:
builtList, _ = self.captureOutput(cook.cookObject,
repos,
self.cfg,
[loader],
sourceVersion,
prep=prep, macros=macros,
allowMissingSource=True,
ignoreDeps=ignoreDeps,
logBuild=logBuild,
groupOptions=groupOptions,
resume=resume,
_printOnError=self._printOnError,
)
finally:
repos.close()
return builtList
def cookPackageObject(self, theClass, prep=False, macros={},
sourceVersion = None, serverIdx = 0,
ignoreDeps = False):
""" cook a package object, return the buildpackage components
and package obj
"""
repos = self.openRepository(serverIdx)
if sourceVersion is None:
sourceVersion, _ = cook.guessSourceVersion(repos, theClass.name,
theClass.version,
self.cfg.buildLabel,
searchBuiltTroves=True)
if not sourceVersion:
# just make up a sourceCount -- there's no version in
# the repository to compare against
sourceVersion = versions.VersionFromString('/%s/%s-1' % (
self.cfg.buildLabel.asString(),
theClass.version))
use.resetUsed()
stdout = os.dup(sys.stdout.fileno())
stderr = os.dup(sys.stderr.fileno())
null = os.open('/dev/null', os.O_WRONLY)
os.dup2(null, sys.stdout.fileno())
os.dup2(null, sys.stderr.fileno())
try:
res = cook._cookPackageObject(repos, self.cfg, theClass,
sourceVersion,
prep=prep, macros=macros,
ignoreDeps=ignoreDeps)
finally:
os.dup2(stdout, sys.stdout.fileno())
os.dup2(stderr, sys.stderr.fileno())
os.close(null)
os.close(stdout)
os.close(stderr)
repos.close()
if not res:
return None
#return bldList, recipeObj
return res[0:2]
def getRecipeObjFromRepos(self, name, repos):
stdout = os.dup(sys.stdout.fileno())
stderr = os.dup(sys.stderr.fileno())
null = os.open('/dev/null', os.O_WRONLY)
os.dup2(null, sys.stdout.fileno())
os.dup2(null, sys.stderr.fileno())
try:
loader, sourceVersion = loadrecipe.recipeLoaderFromSourceComponent(
name, self.cfg, repos)[0:2]
recipeObj = cook._cookPackageObject(repos, self.cfg, loader,
sourceVersion, prep=True, requireCleanSources=True)
finally:
os.dup2(stdout, sys.stdout.fileno())
os.dup2(stderr, sys.stderr.fileno())
os.close(null)
os.close(stdout)
os.close(stderr)
return recipeObj
def repairTroves(self, pkgList = [], root = None):
if root is None:
root = self.rootDir
repos = self.openRepository()
db = self.openDatabase(root = root)
troveList = []
for item in pkgList:
name, ver, flv = updatecmd.parseTroveSpec(item)
troves = db.findTrove(None, (name, ver, flv))
troveList += troves
db.repairTroves(repos, troveList)
def updatePkg(self, root, pkg=[], version = None, tagScript = None,
noScripts = False, keepExisting = False, replaceFiles = None,
resolve = False, depCheck = True, justDatabase = False,
flavor = None, recurse = True, sync = False,
info = False, fromFiles = [], checkPathConflicts = True,
test = False, migrate = False, keepRequired = None,
raiseError = False, callback = None, restartInfo = None,
applyCriticalOnly = False, syncChildren = False,
keepJournal = False, noRestart=False,
exactFlavors = False, replaceManagedFiles = False,
replaceModifiedFiles = False, replaceUnmanagedFiles = False,
replaceModifiedConfigFiles = False, skipCapsuleOps = False,
criticalUpdateInfo = None, modelFile = None):
if not isinstance(root, str) or not root[0] == '/':
# hack to allow passing of rootdir as first argument
# as we used to
if isinstance(root, list):
pkg = root
else:
pkg = [root]
root = self.rootDir
newcfg = self.cfg
newcfg.root = root
if callback is None:
callback = callbacks.UpdateCallback()
if replaceFiles is not None:
replaceManagedFiles = replaceFiles
replaceUnmanagedFiles = replaceFiles
replaceModifiedFiles = replaceFiles
replaceModifiedConfigFiles = replaceFiles
repos = self.openRepository()
if isinstance(pkg, (str, list)):
if isinstance(pkg, str):
if version is not None:
if type(version) is not str:
version = version.asString()
item = "%s=%s" % (pkg, version)
else:
item = pkg
if flavor is not None:
item += '[%s]' % flavor
pkgl = [ item ]
else:
assert(version is None)
assert(flavor is None)
pkgl = list(itertools.chain(*(util.braceExpand(x) for x in pkg)))
# For consistency's sake, if in migrate mode, fake the command
# line to say migrate
if migrate:
newSysArgv = [ 'conary', 'migrate' ]
else:
newSysArgv = [ 'conary', 'update' ]
oldSysArgv = sys.argv
# Add the packages to handle
newSysArgv.extend(pkgl)
newcfg.autoResolve = resolve
try:
if keepJournal:
k = { 'keepJournal' : True }
else:
k = {}
try:
sys.argv = newSysArgv
updatecmd.doUpdate(newcfg, pkgl,
tagScript=tagScript,
keepExisting=keepExisting,
replaceManagedFiles=\
replaceManagedFiles,
replaceUnmanagedFiles=\
replaceUnmanagedFiles,
replaceModifiedFiles=\
replaceModifiedFiles,
replaceModifiedConfigFiles=\
replaceModifiedConfigFiles,
depCheck=depCheck,
justDatabase=justDatabase,
recurse=recurse, split=True,
sync=sync, info=info,
fromFiles=fromFiles,
checkPathConflicts=checkPathConflicts,
test=test, migrate=migrate,
keepRequired=keepRequired,
callback=callback,
restartInfo=restartInfo,
applyCriticalOnly=applyCriticalOnly,
syncChildren=syncChildren,
forceMigrate=migrate,
noRestart=noRestart,
exactFlavors=exactFlavors,
criticalUpdateInfo=criticalUpdateInfo,
skipCapsuleOps=skipCapsuleOps,
noScripts=noScripts,
systemModelFile=modelFile,
**k)
finally:
sys.argv = oldSysArgv
except conaryclient.DependencyFailure, msg:
if raiseError:
raise
print msg
except errors.InternalConaryError, err:
raise
except errors.ConaryError, msg:
if raiseError:
raise
log.error(msg)
else:
# we have a changeset object; mimic what updatecmd does
assert(not info)
assert(not fromFiles)
assert(not test)
assert(checkPathConflicts)
cl = conaryclient.ConaryClient(self.cfg)
cl.setUpdateCallback(callback)
job = [ (x[0], (None, None), (x[1], x[2]),
not keepExisting) for x in
pkg.getPrimaryTroveList() ]
try:
try:
updJob, suggMap = cl.updateChangeSet(job,
keepExisting = keepExisting,
keepRequired = keepRequired,
recurse = recurse, split = True,
sync = sync,
fromChangesets = [ pkg ])
if depCheck:
assert(not suggMap)
if replaceFiles is None:
replaceFiles = False
# old applyUpdate API doesn't support separate args
assert(not replaceManagedFiles)
assert(not replaceUnmanagedFiles)
assert(not replaceModifiedFiles)
assert(not replaceModifiedConfigFiles)
cl.applyUpdate(updJob, replaceFiles = replaceFiles,
tagScript = tagScript, justDatabase = justDatabase,
keepJournal = keepJournal)
finally:
updJob.close()
cl.close()
except conaryclient.DependencyFailure, msg:
if raiseError:
raise
print msg
except errors.InternalConaryError, err:
raise
except errors.ConaryError, err:
if raiseError:
raise
log.error(err)
def verifyDatabase(self):
db = self.openDatabase()
for info in list(db.iterAllTroves()):
assert db.getTrove(*info).verifyDigests(), "Update failed"
def updateAll(self, **kw):
updatecmd.updateAll(self.cfg, **kw)
def localChangeset(self, root, pkg, fileName):
db = database.Database(root, self.cfg.dbPath)
newcfg = copy.deepcopy(self.cfg)
newcfg.root = root
db = database.Database(root, self.cfg.dbPath)
newcfg = copy.deepcopy(self.cfg)
newcfg.root = root
verify.LocalChangeSetCommand(db, newcfg, pkg, fileName)
db.close()
def changeset(self, repos, troveSpecs, fileName, recurse=True):
cscmd.ChangeSetCommand(self.cfg, troveSpecs, fileName,
recurse=recurse)
def erasePkg(self, root, pkg, version = None, tagScript = None,
depCheck = True, justDatabase = False, flavor = None,
test = False, recurse=True, callback = None,
skipCapsuleOps = False):
db = database.Database(root, self.cfg.dbPath)
try:
if type(pkg) == list:
sys.argv = [ 'conary', 'erase' ] + pkg
updatecmd.doUpdate(self.cfg, pkg,
tagScript = tagScript, depCheck = depCheck,
justDatabase = justDatabase,
updateByDefault = False, test = test,
recurse=recurse, callback=callback,
skipCapsuleOps = skipCapsuleOps)
elif version and flavor:
item = "%s=%s[%s]" % (pkg, version, flavor)
sys.argv = [ 'conary', 'erase', item ]
updatecmd.doUpdate(self.cfg, [ item ],
tagScript = tagScript, depCheck = depCheck,
justDatabase = justDatabase,
updateByDefault = False, test = test,
recurse=recurse, callback=callback,
skipCapsuleOps = skipCapsuleOps)
elif version:
item = "%s=%s" % (pkg, version)
sys.argv = [ 'conary', 'erase', item ]
updatecmd.doUpdate(self.cfg, [ item ],
tagScript = tagScript, depCheck = depCheck,
justDatabase = justDatabase,
updateByDefault = False, test = test,
recurse=recurse, callback=callback,
skipCapsuleOps = skipCapsuleOps)
elif flavor:
item = "%s[%s]" % (pkg, flavor)
sys.argv = [ 'conary', 'erase', item ]
updatecmd.doUpdate(self.cfg, [ item ],
tagScript = tagScript, depCheck = depCheck,
justDatabase = justDatabase,
updateByDefault = False, test = test,
recurse=recurse, callback=callback,
skipCapsuleOps = skipCapsuleOps)
else:
sys.argv = [ 'conary', 'erase', pkg ]
updatecmd.doUpdate(self.cfg, [ pkg ],
tagScript = tagScript, depCheck = depCheck,
justDatabase = justDatabase,
updateByDefault = False, test = test,
recurse=recurse, callback=callback,
skipCapsuleOps = skipCapsuleOps)
except conaryclient.DependencyFailure, msg:
print msg
except errors.ClientError, msg:
log.error(msg)
db.close()
def restoreTrove(self, root, *troveList):
rmv = conarycmd.RestoreCommand()
cfg = copy.copy(self.cfg)
cfg.root = root
return rmv.runCommand(cfg, {}, ( 'conary', 'restore' ) + troveList)
def removeFile(self, root, *pathList):
rmv = conarycmd.RemoveCommand()
cfg = copy.copy(self.cfg)
cfg.root = root
return rmv.runCommand(cfg, {}, ( 'conary', 'remove' ) + pathList)
def build(self, str, name, vars = None, buildDict = None,
sourceVersion = None, serverIdx = 0, logLevel = log.WARNING,
returnTrove = None, macros=None, prep = False):
(built, d) = self.buildRecipe(str, name, d = buildDict,
vars = vars,
sourceVersion = sourceVersion,
logLevel = logLevel, macros = macros,
prep = prep)
if prep:
return
(name, version, flavor) = built[0]
if returnTrove is None:
returnTroveList = [ name ]
else:
name = name.split(':')[0]
if not isinstance(returnTrove, (list, tuple)):
l = ( returnTrove, )
else:
l = returnTrove
returnTroveList = []
for compName in l:
if compName[0] == ':':
returnTroveList.append(name + compName)
else:
returnTroveList.append(compName)
version = versions.VersionFromString(version)
repos = self.openRepository(serverIdx)
trvList = repos.getTroves(
[ (x, version, flavor) for x in returnTroveList ] )
if isinstance(returnTrove, (list, tuple)):
return trvList
return trvList[0]
def buildRecipe(self, theClass, theName, vars = None, prep=False,
macros = None,
sourceVersion = None, d = None, serverIdx = 0,
logLevel = None, ignoreDeps=False,
logBuild=False, repos = None, groupOptions = None,
resume = None, branch = None):
use.setBuildFlagsFromFlavor(theName, self.cfg.buildFlavor)
if logLevel is None:
logLevel = log.WARNING
if vars is None:
vars = {}
if macros is None:
macros = {}
if branch is None:
if sourceVersion is not None:
branch = sourceVersion.branch()
else:
branch = versions.Branch([self.cfg.buildLabel])
built = []
if repos is None:
repos = self.openRepository()
loader = LoaderFromString(theClass, "/test.recipe", cfg = self.cfg,
repos = repos, objDict = d,
component = theName)
recipe = loader.getRecipe()
for name in vars.iterkeys():
setattr(recipe, name, vars[name])
level = log.getVerbosity()
log.setVerbosity(logLevel)
built = self.cookObject(loader, prep=prep, macros=macros,
sourceVersion=sourceVersion,
serverIdx = serverIdx,
ignoreDeps = ignoreDeps,
logBuild = logBuild,
repos = repos, groupOptions=groupOptions,
resume = resume)
log.setVerbosity(level)
recipe = loader.getRecipe()
# the rest of this is a horrible hack to allow the recipe from this
# load to be used as a superclass later on
del recipe.version
recipe.internalAbstractBaseClass = True
newD = {}
if d:
newD.update(d)
newD[theName] = recipe
return (built, newD)
def overrideBuildFlavor(self, flavorStr):
flavor = deps.parseFlavor(flavorStr)
if flavor is None:
raise RuntimeError, 'Invalid flavor %s' % flavorStr
buildFlavor = self.cfg.buildFlavor.copy()
if (deps.DEP_CLASS_IS in flavor.getDepClasses() and
deps.DEP_CLASS_IS in buildFlavor.getDepClasses()):
# instruction set deps are overridden completely -- remove
# any buildFlavor instruction set info
del buildFlavor.members[deps.DEP_CLASS_IS]
buildFlavor.union(flavor,
mergeType = deps.DEP_MERGE_TYPE_OVERRIDE)
self.cfg.buildFlavor = buildFlavor
def pin(self, troveName):
updatecmd.changePins(self.cfg, [ troveName ], True)
def unpin(self, troveName):
updatecmd.changePins(self.cfg, [ troveName ], False)
def clone(self, targetBranch, *troveSpecs, **kw):
oldQuiet = self.cfg.quiet
if kw.pop('verbose', False):
self.cfg.quiet = False
else:
self.cfg.quiet = True
kw.setdefault('ignoreConflicts', True)
kw.setdefault('message', 'foo')
clone.CloneTrove(self.cfg, targetBranch, troveSpecs, **kw)
cfgmod.quiet = oldQuiet
def promote(self, *params, **kw):
oldQuiet = self.cfg.quiet
if kw.pop('verbose', False):
self.cfg.quiet = False
else:
self.cfg.quiet = True
kw.setdefault('message', 'foo')
kw.setdefault('allFlavors', True)
troveSpecs = []
labelList = []
for arg in params:
if '--' in arg:
labelList.append(arg.split('--', 1))
else:
troveSpecs.append(arg)
cs = clone.promoteTroves(self.cfg, troveSpecs, labelList, **kw)
cfgmod.quiet = oldQuiet
return cs
def initializeFlavor(self):
use.clearFlags()
self.cfg.useDirs = [resources.get_archive('use')]
self.cfg.archDirs = [resources.get_archive('arch')]
self.cfg.initializeFlavors()
use.setBuildFlagsFromFlavor('', self.cfg.buildFlavor, error=False)
self._origFlavor = use.allFlagsToFlavor('')
buildIs = use.Arch.getCurrentArch()._toDependency()
self.buildIs = { 'is' : buildIs }
def checkConaryLog(self, logText, rootDir = None, skipSections = 0):
if rootDir is None:
rootDir = self.cfg.root
# we split this into a list of lines per command
sections = []
sectionNum = None
for line in open(rootDir + os.path.sep + self.cfg.logFile[0]).xreadlines():
# strip off the timestamps and any extra whitespace
line = line[line.index(']') + 1 :].strip()
if sectionNum is None:
# first line in a section
assert(line.startswith('version'))
# remove the version number
line = line[line.index(':') + 2:]
sectionNum = len(sections)
sections.append([ line ])
else:
sections[sectionNum].append(line)
if "command complete" in line:
sectionNum = None
sections = sections[skipSections:]
gotLog = "".join("\n".join(x) + "\n" for x in sections)
assert(gotLog == logText)
def checkUpdate(self, pkgList, expectedJob, depCheck=True,
keepExisting = False, recurse = True,
resolve = False, sync = False, replaceFiles = False,
exactMatch = True, apply = False, erase = False,
fromChangesets = [], syncChildren = False,
updateOnly = False, resolveGroupList=[],
syncUpdate = False, keepRequired = None,
migrate = False, removeNotByDefault = False,
oldMigrate = False, checkPrimaryPins = True,
client=None, resolveSource=None):
""" Performs an update as given to doUpdate, and checks the resulting
job for correctness. If apply is True, then the job is applied
as well.
Parameters:
pkgList: a list of troveSpecs to attempt to update (foo=3.3[bar])
expectedJob: a list of changeSpecs that describe the contents
of the expected update job.
apply: actually apply the given job if it passes the check.
the rest of the parameters are as with doUpdate.
Acceptable formats for items in the expectedJob list:
* foo matches foo being updated or installed
* foo=--1.0 matches foo 1.0 is installed and nothing
is removed
* foo=1.0--2.0 matches update from 1.0 to 2.0
* foo=1.0-- matches removal of 1.0
Flavors are accepted as well. All portions are specified in
trove spec format.
"""
if client:
assert not resolve, \
"Resolve cannot be specified when passing client"
cl = client
else:
if resolve:
newcfg = copy.deepcopy(self.cfg)
newcfg.autoResolve = resolve
else:
newcfg = self.cfg
cl = conaryclient.ConaryClient(newcfg)
repos = self.openRepository()
if oldMigrate:
syncUpdate = removeNotByDefault = True
installMissing = syncUpdate
areAbsolute = not keepExisting
if isinstance(pkgList, str):
pkgList = [pkgList]
if isinstance(expectedJob, str):
expectedJob = [expectedJob]
pkgList = list(itertools.chain(*(util.braceExpand(x) for x in pkgList)))
applyList = cmdline.parseChangeList(pkgList, keepExisting,
updateByDefault=not erase)
updJob, suggMap = cl.updateChangeSet(applyList,
keepExisting = keepExisting,
keepRequired = keepRequired,
recurse = recurse, split = True, sync = sync,
updateByDefault = not erase,
fromChangesets = fromChangesets,
resolveDeps=depCheck, syncChildren=syncChildren,
updateOnly=updateOnly,
resolveGroupList=resolveGroupList,
installMissing=installMissing,
removeNotByDefault=removeNotByDefault,
migrate=migrate,
checkPrimaryPins=checkPrimaryPins,
resolveSource=resolveSource)
if depCheck:
assert(not suggMap or resolve)
expectedJob = list(itertools.chain(*(util.braceExpand(x) for x in expectedJob)))
self.checkJobList(updJob.getJobs(), expectedJob, exactMatch)
if apply:
cl.applyUpdate(updJob, replaceFiles = replaceFiles)
updJob.close()
def checkLocalUpdates(self, expectedJobs, troveNames=None,
exactMatch = True, getImplied=False):
"""
check conary's understanding of the local system changes that
have been made.
"""
repos = self.openRepository()
cl = conaryclient.ConaryClient(self.cfg)
localUpdates = cl.getPrimaryLocalUpdates(troveNames)
if getImplied:
repos = self.openRepository()
localUpdates += cl.getChildLocalUpdates(repos, localUpdates)
self.checkJobList([localUpdates], expectedJobs, exactMatch)
def checkJobList(self, actualJob, expectedJob, exactMatch):
# check a given set of jobs against a changeList type
# of jobs.
erases = trovesource.SimpleTroveSource()
installs = trovesource.SimpleTroveSource()
jobList = []
for job in actualJob:
for (n, oldInfo, newInfo, isAbs) in job:
assert(not isAbs)
if oldInfo[0]:
erases.addTrove(n, *oldInfo)
if newInfo[0]:
installs.addTrove(n, *newInfo)
jobList.append((n, oldInfo, newInfo))
changeList = cmdline.parseChangeList(expectedJob)
for (n, oldInfo, newInfo, isAbs), jobStr in zip(changeList, expectedJob):
if oldInfo != (None, None):
try:
troveList = erases.findTrove(None, (n, oldInfo[0], oldInfo[1]))
except errors.TroveNotFound:
relatedJobs = [x for x in jobList if x[0] == n]
if relatedJobs:
raise RuntimeError('failed to find erasure for %s. Jobs involving %s found: %s' % (jobStr, n, relatedJobs))
else:
raise RuntimeError('failed to find job for %s. Jobs: %s' % (n, jobList))
if len(troveList) > 1:
raise RuntimeError, (
'(%s,%s,%s) matched multiple erased troves' \
% (n, oldInfo[0], oldInfo[1]))
oldVer, oldFla = troveList[0][1:]
if newInfo != (None, None) or isAbs:
try:
troveList = installs.findTrove(None, (n, newInfo[0],
newInfo[1]))
except errors.TroveNotFound:
raise RuntimeError('failed to find install for %s. Jobs involving %s found: %s' % (jobStr, n, [x for x in jobList if x[0] == n]))
if len(troveList) > 1:
raise RuntimeError, (
'(%s,%s,%s) matched multiple installed troves' \
% (n, newInfo[0], newInfo[1]))
newVer, newFla = troveList[0][1:]
if oldInfo == (None, None):
if isAbs:
# we found the trove in the list of installed troves
# we didn't specify whether it was a new install or a
# install relative to anything, just assume that the
# old trove version is correct
jobToCheck = [ x for x in jobList \
if x[0] == n and x[2] == (newVer, newFla) ]
assert(len(jobToCheck) == 1)
jobToCheck = jobToCheck[0]
else:
# this _must_ be a fresh install.
jobToCheck = (n, (None, None), (newVer, newFla))
elif newInfo == (None, None):
# this _must_ be a fresh install.
jobToCheck = (n, (oldVer, oldFla), (None, None))
else:
jobToCheck = (n, (oldVer, oldFla), (newVer, newFla))
if jobToCheck in jobList:
jobList.remove(jobToCheck)
else:
raise RuntimeError('expected job %s for job str %s was '
'not included in update' %(jobToCheck,
jobStr))
if exactMatch and jobList:
raise RuntimeError, 'update performed extra jobs %s' % (jobList,)
def getSearchSource(self):
return searchsource.NetworkSearchSource(self.openRepository(),
self.cfg.installLabelPath,
self.cfg.flavor)
def checkCall(self, testFn, args, kw, fn, expectedArgs,
cfgValues={}, returnVal=None, ignoreKeywords=False,
checkCallback=None, **expectedKw):
methodCalled = [False]
def _placeHolder(*args, **kw):
"""
Pretends to be the fn that we are checking the parameters of.
"""
methodCalled[0] = True
if checkCallback:
checkCallback(*args, **kw)
self.assertEqual(len(args), len(expectedArgs))
for i, (arg, expectedArg) in enumerate(zip(args, expectedArgs)):
if isinstance(expectedArg, _NoneArg):
assert arg is None, \
"%s: argument %d is not None" % (arg, i + 1)
elif expectedArg is None:
pass
elif (inspect.isclass(expectedArg)
and isinstance(arg, expectedArg)):
pass
else:
assert arg == expectedArg, \
"%s != %s" % (repr(arg), repr(expectedArg))
for key, expectedVal in expectedKw.iteritems():
val = kw.pop(key)
if isinstance(expectedVal, _NoneArg):
assert val is None, \
"%s: %s s not None" % (key, repr(val))
elif expectedVal is None:
pass
elif (inspect.isclass(expectedVal)
and isinstance(arg, expectedVal)):
pass
else:
assert val == expectedVal, \
"%s: %s != %s" % (key, repr(val), repr(expectedVal))
if not ignoreKeywords:
assert not kw, "%s" % repr(kw)
if not cfgValues:
return
found = False
for arg in args:
if isinstance(arg, cfgmod.ConfigFile):
found = True
for cfgKey, cfgValue in cfgValues.iteritems():
assert arg[cfgKey] == cfgValue, \
"%s: %s != %s" % (
cfgKey, repr(arg[cfgKey]), repr(cfgValue))
break
assert(found)
if fn is not None:
fnModule, fnName = fn.rsplit('.', 1)
if fnModule in sys.modules:
origFn = sys.modules[fnModule].__dict__[fnName]
sys.modules[fnModule].__dict__[fnName] = _placeHolder
isClassMethod = False
else:
fnModule, className = fnModule.rsplit('.', 1)
isClassMethod = True
class_ = sys.modules[fnModule].__dict__[className]
origFn = getattr(class_, fnName)
setattr(class_,
fnName, new.instancemethod(_placeHolder, None, class_))
try:
rv = testFn(*args, **kw)
if fn is not None:
assert(methodCalled[0])
if returnVal is not None:
assert(rv == returnVal)
return rv
finally:
if fn is not None:
if isClassMethod:
setattr(class_, fnName, origFn)
else:
sys.modules[fnModule].__dict__[fnName] = origFn
def checkCommand(self, testFn, cmd, fn, expectedArgs,
cfgValues={}, returnVal=None, ignoreKeywords=False,
checkCallback=None,
**expectedKw):
"""Runs testFn with the given command line.
@param testFn: the function to pass our fake argv to.
@param cmd: the command line to turn into an argv list.
Should start with the program name.
@param fn: the module and function that we are checking to ensure
is called
@param expectedArgs: the args that should have been passed to fn.
If an arg value is None, then no assertion about that
argument is made. If the parameter should be None, pass
in the rephelp.NoneArg instead.
@param cfgValues: assert that the given cfg values are set.
Can only be used if one of the params passed into
fn is a Configuration objec.t
@param ignoreKeywords: if True, ignore any extra keywords not
specified in the expectedKw argument.
@param checkCallback: if not None, a function to call for
customized checks. Called w/ the original functions'
keywords and args.
"""
level = log.getVerbosity()
argv = shlex.split(cmd)
try:
return self.checkCall(testFn, [argv], {}, fn, expectedArgs,
cfgValues=cfgValues, returnVal=returnVal,
ignoreKeywords=ignoreKeywords,
checkCallback=checkCallback, **expectedKw)
finally:
log.setVerbosity(level)
def findAndGetTroves(self, *troveSpecs, **kw):
repos = kw.pop('repos', None)
if not repos:
repos = self.openRepository()
troveSpecs = [cmdline.parseTroveSpec(x) for x in troveSpecs ]
results = repos.findTroves(self.cfg.installLabelPath,
troveSpecs, self.cfg.flavor)
troveTupList = list(itertools.chain(*results.values()))
troves = repos.getTroves(troveTupList, **kw)
troves = dict(itertools.izip(troveTupList, troves))
finalResult = []
for troveSpec in troveSpecs:
assert(len(results[troveSpec]) == 1)
finalResult.append(troves[results[troveSpec][0]])
return finalResult
def findAndGetTrove(self, troveSpec, **kw):
return self.findAndGetTroves(troveSpec, **kw)[0]
def setTroveVersion(self, val):
trove.TROVE_VERSION = val
trove.TROVE_VERSION_1_1 = val
def loadRecipe(self, name, flavor, init=False):
repos = self.openRepository()
oldBuildFlavor = self.cfg.buildFlavor
self.overrideBuildFlavor(flavor)
use.setBuildFlagsFromFlavor(name, self.cfg.buildFlavor)
use.Arch._getMacro('targetarch')
loader = loadrecipe.recipeLoaderFromSourceComponent(name, self.cfg,
repos,
buildFlavor=self.cfg.buildFlavor)[0]
recipeClass = loader.getRecipe()
if init:
return recipeClass(self.cfg, None, [])
self.cfg.buildFlavor = oldBuildFlavor
return recipeClass
def getConaryProxy(self, idx = 0, proxies = None,
entitlements = [], users = [], useApache = False,
withCapsuleContentServer = False,
useSSL = False, cacheTimeout = None, cacheLocation = None):
cProxyDir = os.path.join(self.tmpDir, "conary-proxy")
if idx:
cProxyDir += "-%s" % str(idx)
cProxyContentsDir = os.path.join(cProxyDir, "contents")
util.rmtree(cProxyDir, ignore_errors = True)
util.mkdirChain(cProxyContentsDir)
conaryPath = resources.get_path()
server = server_path
classMap = {
(True, True): ApacheSSLProxyServer,
(True, False) : ApacheProxyServer,
(False, True) : StandaloneSSLProxyServer,
(False, False) : StandaloneProxyServer,
}
key = (bool(useApache), bool(useSSL))
ProxyClass = classMap[key]
if withCapsuleContentServer:
capsuleServerUrl = "http://localhost:%s/toplevel" % \
self.capsuleContentServer.port
else:
capsuleServerUrl = None
cProxy = ProxyClass('proxy', None,
ContentStore(cProxyContentsDir), server, None,
cProxyDir, conaryPath, None, None, serverIdx = idx,
proxies = proxies, entitlements = entitlements,
users = users, capsuleServerUrl = capsuleServerUrl,
cacheTimeout = cacheTimeout, cacheLocation = cacheLocation)
return cProxy
def getHTTPProxy(self, idx = 0, path = None):
if path:
cProxyDir = path
else:
cProxyDir = os.path.join(self.tmpDir, "http-proxy")
if idx:
cProxyDir += "-%s" % str(idx)
h = HTTPProxy(cProxyDir)
if h.start():
return h
else:
raise testhelp.SkipTestException("Squid is not installed")
def assertSubstringIn(self, val, target):
matches = [val in x for x in target]
self.assertTrue(matches, "%s not found in %s" % (
safe_repr(val), safe_repr(target)))
@staticmethod
def sleep(length):
'sleep at least <length> time even if signal causes short sleep'
start = time.time()
now = start
while now < start + length:
time.sleep(length - (now - start))
now = time.time()
@staticmethod
def trimRecipe(recipe):
'''
Strip leading whitespace off a recipe so you can indent
recipes in a test while still using multi-line string
literals. Will remove all leading whitespace common to
non-blank lines.
'''
minWhitespace = None
pattern = re.compile('^(\s*)\S')
for line in recipe.splitlines():
match = pattern.match(line)
if match:
whitespace = len(match.group(1))
if minWhitespace is None or whitespace < minWhitespace:
minWhitespace = whitespace
if minWhitespace is None:
return recipe
ret = ''
for line in recipe.splitlines():
ret += line[minWhitespace:] + '\n'
return ret
class HTTPProxy(base_server.BaseServer):
"""Dealing with HTTP proxies"""
proxyBinPath = "/usr/sbin/squid"
configTemplate = """\
http_port %(port)s
http_port %(authPort)s
cache_dir ufs %(cacheDir)s 100 4 4
access_log %(accessLog)s squid
cache_log %(cacheLog)s
cache_store_log %(storeLog)s
pid_filename %(pidFile)s
auth_param basic program %(authprog)s %(passwdFile)s
auth_param basic children 5
auth_param basic realm Squid proxy-caching web server
auth_param basic credentialsttl 2 hours
auth_param basic casesensitive on
acl acl_myport_nonauth myport %(port)s
acl acl_myport_auth myport %(authPort)s
cache_effective_user %(user)s
cache_effective_group %(group)s
visible_hostname localhost.localdomain
%(acls)s
"""
def __init__(self, topdir):
self.topdir = topdir
self.cacheDir = os.path.join(topdir, "cache-dir")
self.accessLog = os.path.join(topdir, "access.log")
self.cacheLog = os.path.join(topdir, "cache.log")
self.storeLog = os.path.join(topdir, "store.log")
self.pidFile = os.path.join(topdir, "squid.pid")
self.configFile = os.path.join(topdir, "squid.conf")
self.authPasswdFile = os.path.join(topdir, "passwd.auth")
self.stopped = True
self.pid = None
def updateConfig(self, cfg, auth = False):
port = (auth and self.authPort) or self.port
cfg.proxy = { 'http' : 'http://localhost:%d/' % port,
'https' : 'https://localhost:%d/' % port,
}
def start(self):
if not os.path.exists(self.proxyBinPath):
return None
# We will start the proxy on these ports
self.port, self.authPort = testhelp.findPorts(num = 2)
self.writeConfigFile()
stdout = open(os.devnull, "w+")
stderr = open(os.devnull, "w+")
# For debugging squid, uncomment the next line
#stderr = None
# Kill any existing proxies first
p = subprocess.Popen(self.getStopCmd(), stdout=stderr, stderr=stderr)
ret = p.wait()
# Initialize cache
p = subprocess.Popen(self.getInitCmd(), stdout=stderr, stderr=stderr)
ret = p.wait()
if ret != 0:
raise Exception("Unable to init squid with config file %s: %s" %
(self.configFile, ret))
# Start it
p = subprocess.Popen(self.getStartCmd(), stdout=stderr, stderr=stderr)
ret = p.wait()
if ret != 0:
raise Exception("Unable to start squid with config file %s: %s" %
(self.configFile, ret))
# Wait till we can open a connection
sock_utils.tryConnect("127.0.0.1", self.port)
# Save the pid, in case the directory gets removed
# Loop several times if squid didn't have the chance to write the pid
# file
for i in range(10):
if os.path.exists(self.pidFile):
break
time.sleep(0.1)
else:
# Give it several more seconds before failing
time.sleep(2)
self.pid = int(open(self.pidFile).readline().strip())
self.stopped = False
proxyUri = "127.0.0.1:%s" % self.port
return proxyUri
def getStartCmd(self):
return self.getBaseCmd()
def getInitCmd(self):
return self.getBaseCmd() + [ '-z' ]
def getStopCmd(self):
return self.getBaseCmd() + [ '-k', 'kill' ]
def getBaseCmd(self):
return [self.proxyBinPath, '-D', '-f', self.configFile]
def writeConfigFile(self):
util.mkdirChain(os.path.dirname(self.configFile))
acls = self.getAcls()
# Determine libdir
from distutils import sysconfig
libdir = sysconfig.get_config_vars()['LIBDIR']
for name in ('basic_ncsa_auth', 'ncsa_auth'):
authprog = os.path.join(libdir, 'squid', name)
if os.path.exists(authprog):
break
else:
raise RuntimeError("Couldn't find basic_ncsa_auth for squid")
opts = dict(port = self.port, authPort = self.authPort,
cacheDir = self.cacheDir,
accessLog = self.accessLog, storeLog = self.storeLog,
cacheLog = self.cacheLog, pidFile = self.pidFile,
passwdFile = self.authPasswdFile,
acls = "\n".join(acls),
libdir = libdir,
user = os_utils.effectiveUser,
group = os_utils.effectiveGroup,
authprog = authprog,
)
open(self.configFile, "w+").write(self.configTemplate % opts)
# Write password file too
open(self.authPasswdFile, "w").write("rpath:IOiVc37UsPIV2\n")
def getAcls(self):
return [
"acl acl_proxy_auth proxy_auth REQUIRED",
"http_access deny acl_myport_auth !acl_proxy_auth",
"http_access allow all"]
def stop(self):
if self.stopped:
return
stdout = open(os.devnull, "w+")
stderr = open(os.devnull, "w+")
# For debugging squid, uncomment the next line
#stderr = None
# Insist on killing squid
for i in range(5):
p = subprocess.Popen(self.getStopCmd(), stdout=stdout, stderr=stderr)
ret = p.wait()
if ret == 0:
break
time.sleep(.1)
if ret != 0:
sys.stderr.write("Unable to stop squid with config file %s: %s\n" %
(self.configFile, ret))
# Try harder to kill it
sys.stderr.write("Killing squid process %d\n" % self.pid)
try:
os.kill(self.pid, 15)
time.sleep(1)
os.kill(self.pid, 9)
except OSError, e:
if e.errno != 3: # No such process
raise
if os.path.exists(self.pidFile):
os.unlink(self.pidFile)
self.stopped = True
def getFileSize(self, fname):
st = os.stat(fname)
if not st:
return 0
return st[stat.ST_SIZE]
def getAccessLogSize(self):
return self.getFileSize(self.accessLog)
def getAccessLogEntry(self, start):
# The log entry may not be flushed to disk yet
for i in range(5):
end = self.getAccessLogSize()
if end != start:
break
time.sleep(.1)
f = open(self.accessLog)
f.seek(start)
line = f.read(end - start)
f.close()
return line.split()
def isStarted(self):
return not self.stopped
class HTTPServerController(base_server.BaseServer):
def __init__(self, requestHandler, ssl=False):
# this is racy :-(
self.port = testhelp.findPorts(num = 1)[0]
self.ssl = ssl
self.childPid = os.fork()
if self.childPid > 0:
sock_utils.tryConnect("127.0.0.1", self.port)
return
try:
try:
if ssl:
klass = SecureHTTPServer
ctx = SSL.Context("sslv23")
if isinstance(ssl, tuple):
# keypair
sslCert, sslKey = ssl
else:
# defaults
sslCert, sslKey = 'ssl-cert.crt', 'ssl-cert.key'
sslCert = os.path.join(resources.get_archive(sslCert))
sslKey = os.path.join(resources.get_archive(sslKey))
ctx.load_cert_chain(sslCert, sslKey)
args = (ctx,)
else:
klass = BaseHTTPServer.HTTPServer
args = ()
# Sorry for modifying a stdlib class, but this is in a dead-end
# forked process after all! Need to bind to "IPv6 all" so that
# both IPv4 and IPv6 connections to "localhost" succeed.
klass.address_family = socket.AF_INET6
httpServer = klass(('::', self.port), requestHandler, *args)
httpServer.serve_forever()
os._exit(0)
except:
traceback.print_exc()
finally:
os._exit(1)
def kill(self):
if not self.childPid:
self.childPid = None
return
if os.environ.get('COVERAGE_DIR', None):
sendsig = signal.SIGUSR2
else:
sendsig = signal.SIGTERM
start = time.time()
while True:
now = time.time()
if now - start > 15:
break
os.kill(self.childPid, sendsig)
try:
pid = os.waitpid(self.childPid, os.WNOHANG)[0]
except OSError, err:
if err.errno == errno.EINTR:
# Interrupted.
continue
elif err.errno == errno.ECHILD:
# Process doesn't exist.
self.childPid = None
return
else:
raise
else:
if pid:
# Process existed but is now gone.
self.childPid = None
return
# Process exists and is still running.
time.sleep(2)
# Process still not dead.
os.kill(self.childPid, signal.SIGKILL)
os.waitpid(self.childPid, 0)
self.childPid = None
stop = close = kill
def url(self):
if self.ssl:
s = 's'
else:
s = ''
return "http%s://localhost:%d/" % (s, self.port)
def isStarted(self):
return self.childPid not in (None, 0)
def _cleanUp():
individual = _isIndividual()
global _servers
_servers.stopAllServers(clean=not individual)
if _proxy:
_proxy.stop()
# Clean up the proxy dir too
if not individual and hasattr(_proxy, 'reposDir'):
util.rmtree(_proxy.reposDir, ignore_errors = True)
# If nothing else lives in the parent for reposDir, go ahead and
# remove that directory too
try:
os.rmdir(os.path.dirname(_proxy.reposDir))
except OSError:
pass
def getOpenFiles():
procdir = "/proc/self/fd"
fdlist = os.listdir(procdir)
fdlist = ((x, os.path.join(procdir, x)) for x in fdlist)
fdlist = set((x[0], os.readlink(x[1])) for x in fdlist
if os.path.exists(x[1]))
return fdlist
notCleanedUpWarning = True
| {
"content_hash": "e4d9e48f2d489390b73921176b2136e7",
"timestamp": "",
"source": "github",
"line_count": 3749,
"max_line_length": 150,
"avg_line_length": 37.95812216591091,
"alnum_prop": 0.5288851410702364,
"repo_name": "fedora-conary/conary",
"id": "1833865a767df84b0f22944f28f41954fc529849",
"size": "142900",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "conary_test/rephelp.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "481681"
},
{
"name": "C++",
"bytes": "8244"
},
{
"name": "CSS",
"bytes": "3920"
},
{
"name": "Erlang",
"bytes": "477"
},
{
"name": "Perl",
"bytes": "45629"
},
{
"name": "Python",
"bytes": "10586616"
},
{
"name": "Shell",
"bytes": "4657"
},
{
"name": "Standard ML",
"bytes": "2756"
}
],
"symlink_target": ""
} |
'''
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
- Use sentry for error logging
'''
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.utils import six
import logging
from .common import * # noqa
# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ
SECRET_KEY = env("DJANGO_SECRET_KEY")
# This ensures that Django will be able to detect a secure connection
# properly on Heroku.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# django-secure
# ------------------------------------------------------------------------------
INSTALLED_APPS += ("djangosecure", )
# raven sentry client
# See https://docs.getsentry.com/hosted/clients/python/integrations/django/
INSTALLED_APPS += ('raven.contrib.django.raven_compat', )
SECURITY_MIDDLEWARE = (
'djangosecure.middleware.SecurityMiddleware',
)
RAVEN_MIDDLEWARE = ('raven.contrib.django.raven_compat.middleware.Sentry404CatchMiddleware',
'raven.contrib.django.raven_compat.middleware.SentryResponseErrorIdMiddleware',)
MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + \
RAVEN_MIDDLEWARE + MIDDLEWARE_CLASSES
# set this to 60 seconds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
"DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS", default=True)
SECURE_FRAME_DENY = env.bool("DJANGO_SECURE_FRAME_DENY", default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
"DJANGO_SECURE_CONTENT_TYPE_NOSNIFF", default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = False
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool("DJANGO_SECURE_SSL_REDIRECT", default=True)
# SITE CONFIGURATION
# ------------------------------------------------------------------------------
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
ALLOWED_HOSTS = ["*"]
# END SITE CONFIGURATION
INSTALLED_APPS += ("gunicorn", )
# STORAGE CONFIGURATION
# ------------------------------------------------------------------------------
# Uploaded Media Files
# ------------------------
# See: http://django-storages.readthedocs.org/en/latest/index.html
INSTALLED_APPS += (
'storages',
)
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME')
AWS_AUTO_CREATE_BUCKET = True
AWS_QUERYSTRING_AUTH = False
AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat()
# AWS cache settings, don't change unless you know what you're doing:
AWS_EXPIRY = 60 * 60 * 24 * 7
# TODO See: https://github.com/jschneier/django-storages/issues/47
# Revert the following and use str after the above-mentioned bug is fixed in
# either django-storage-redux or boto
AWS_HEADERS = {
'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % (
AWS_EXPIRY, AWS_EXPIRY))
}
# URL that handles the media served from MEDIA_ROOT, used for managing
# stored files.
MEDIA_URL = 'https://s3.amazonaws.com/%s/' % AWS_STORAGE_BUCKET_NAME
# Static Assests
# ------------------------
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'
# EMAIL
# ------------------------------------------------------------------------------
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default='verstandprj <noreply@hikint.com>')
EMAIL_BACKEND = 'django_mailgun.MailgunBackend'
MAILGUN_ACCESS_KEY = env('DJANGO_MAILGUN_API_KEY')
MAILGUN_SERVER_NAME = env('DJANGO_MAILGUN_SERVER_NAME')
EMAIL_SUBJECT_PREFIX = env("DJANGO_EMAIL_SUBJECT_PREFIX", default='[verstandprj] ')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
# See:
# https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader
TEMPLATES[0]['OPTIONS']['loaders'] = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]),
]
# DATABASE CONFIGURATION
# ------------------------------------------------------------------------------
# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
DATABASES['default'] = env.db("DATABASE_URL")
# CACHING
# ------------------------------------------------------------------------------
# Heroku URL does not pass the DB number, so we parse it in
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "{0}/{1}".format(env.cache_url('REDIS_URL', default="redis://127.0.0.1:6379"), 0),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"IGNORE_EXCEPTIONS": True, # mimics memcache behavior.
# http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior
}
}
}
# Sentry Configuration
SENTRY_CLIENT = env('DJANGO_SENTRY_CLIENT')
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'root': {
'level': 'WARNING',
'handlers': ['sentry'],
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
},
},
'handlers': {
'sentry': {
'level': 'ERROR',
'class': 'raven.contrib.django.raven_compat.handlers.SentryHandler',
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
}
},
'loggers': {
'django.db.backends': {
'level': 'ERROR',
'handlers': ['console'],
'propagate': False,
},
'raven': {
'level': 'DEBUG',
'handlers': ['console'],
'propagate': False,
},
'sentry.errors': {
'level': 'DEBUG',
'handlers': ['console'],
'propagate': False,
},
},
}
SENTRY_CELERY_LOGLEVEL = env('DJANGO_SENTRY_LOG_LEVEL', logging.INFO)
RAVEN_CONFIG = {
'CELERY_LOGLEVEL': env('DJANGO_SENTRY_LOG_LEVEL', logging.INFO)
}
# Your production stuff: Below this line define 3rd party library settings
| {
"content_hash": "3e3e35fa031d621bdda5d081394bc953",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 117,
"avg_line_length": 34.922680412371136,
"alnum_prop": 0.6022140221402214,
"repo_name": "gladgod/verstand-server",
"id": "38b237931976a16750a3da8079e5f95ca2eaef42",
"size": "6799",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "config/settings/production.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1370"
},
{
"name": "HTML",
"bytes": "20111"
},
{
"name": "JavaScript",
"bytes": "3507"
},
{
"name": "Nginx",
"bytes": "1095"
},
{
"name": "Python",
"bytes": "39962"
},
{
"name": "Shell",
"bytes": "4586"
}
],
"symlink_target": ""
} |
from abc import ABCMeta
from .utils.conformance import verify_conformance, verify_not_overridden
from .utils.docs import update_docs
from .utils.inspection import (
set_explicit_override,
set_forced_override,
set_quirk_docs_method,
set_quirk_docs_mro,
should_skip,
)
class InterfaceMeta(ABCMeta):
"""
A metaclass that helps subclasses of a class to conform to its API.
It also makes sure that documentation that might be useful to a user
is inherited appropriately, and provides a hook for class to handle
subclass operations.
"""
INTERFACE_EXPLICIT_OVERRIDES = True
INTERFACE_RAISE_ON_VIOLATION = False
INTERFACE_SKIPPED_NAMES = set()
def __init__(cls, name, bases, dct):
ABCMeta.__init__(cls, name, bases, dct)
# Register interface class for subclasses
if not hasattr(cls, "__interface__"):
cls.__interface__ = cls
# Read configuration
explicit_overrides = cls.__get_config(
bases, dct, "INTERFACE_EXPLICIT_OVERRIDES"
)
raise_on_violation = cls.__get_config(
bases, dct, "INTERFACE_RAISE_ON_VIOLATION"
)
skipped_names = cls.__get_config(bases, dct, "INTERFACE_SKIPPED_NAMES")
# Iterate over names in `dct` and check for conformance to interface
for key, value in dct.items():
# Skip any key corresponding to Python magic methods
if key.startswith("__") and key.endswith("__"):
continue
# Skip any key in skipped_names
if key in skipped_names or should_skip(value): # pragma: no cover
continue
# Identify the first instance of this key in the MRO, if it exists, and check conformance
is_override = False
for base in cls.__mro__[1:]:
if base is object:
continue
if key in base.__dict__:
is_override = True
cls.__verify_conformance(
key,
name,
value,
base.__name__,
base.__dict__[key],
explicit_overrides=explicit_overrides,
raise_on_violation=raise_on_violation,
)
break
if key in getattr(
base, "__annotations__", {}
): # Declared but as yet unspecified attributes
is_override = True
cls.__verify_conformance(
key,
name,
value,
name,
None,
explicit_overrides=explicit_overrides,
raise_on_violation=raise_on_violation,
)
break
if not is_override:
verify_not_overridden(
key, name, value, raise_on_violation=raise_on_violation
)
# Update documentation
cls.__update_docs(cls, name, bases, dct)
# Call subclass registration hook
cls.__register_implementation__()
def __register_implementation__(cls):
pass
@classmethod
def __get_config(mcls, bases, dct, key):
default = getattr(mcls, key, None)
if bases:
default = getattr(bases[0], key, default)
return dct.get(key, default)
@classmethod
def __verify_conformance(
mcls,
key,
name,
value,
base_name,
base_value,
explicit_overrides=True,
raise_on_violation=False,
):
return verify_conformance(
key,
name,
value,
base_name,
base_value,
explicit_overrides=explicit_overrides,
raise_on_violation=raise_on_violation,
)
@classmethod
def __update_docs(mcls, cls, name, bases, dct):
skipped_names = mcls.__get_config(bases, dct, "INTERFACE_SKIPPED_NAMES")
return update_docs(cls, name, bases, dct, skipped_names=skipped_names)
@classmethod
def inherit_docs(mcls, method=None, mro=True):
"""
Indicate to `InterfaceMeta` how the wrapped method should be documented.
Methods need not normally be decorated with this decorator, except in the
following cases:
- documentation for quirks should be lifted not from overrides to a
method, but from some other method (e.g. because subclasses or
implementations of the interface should override behaviour in a "private"
method rather than the top-level public method).
- the method has been nominated by the interface configuration to be
skipped, in which case decorating with this method will enable
documentation generation as if it were not.
Use this decorator as `@InterfaceMeta.inherit_docs([method=...], [mro=...])`
or `@<metaclass instance>.inherit_docs([method=...], [mro=...])`.
Args:
method (str, None): A method from which documentation for implementation
specific quirks should be extracted. [Useful when implementations
of an interface are supposed to change underlying methods rather
than the public method itself].
mro (bool): Whether to include documentation from all levels of the
MRO, starting from the most primitive class that implementated it.
All higher levels will be considered as "quirks" to the interface's
definition.
Returns:
function: A function wrapper that attaches attributes `_quirks_method` and
`_quirks_mro` to the method, for interpretation by `InterfaceMeta`.
"""
def doc_wrapper(f):
set_quirk_docs_method(f, method)
set_quirk_docs_mro(f, mro)
return f
return doc_wrapper
@classmethod
def override(mcls, func=None, force=False):
"""
Indicate to `InterfaceMeta` that this method has intentionally overridden an interface method.
This decorator also allows one to indicate that the method should be
overridden without warnings even when it does not conform to the API.
Use this decorator as `@InterfaceMeta.override`, `@InterMeta.override(force=True)`,
`@<metaclass instance>.override`, or `@<metaclass instance>.override(force=True)`.
A recommended convention is to use this decorator as the outermost decorator.
Args:
f (function, None): The function, if method is decorated by the decorator
without arguments (e.g. @override), else None.
force (bool): Whether to force override of method even if the API does
note match. Note that in this case, documentation is not inherited
from the MRO.
Returns:
function: The wrapped function of function wrapper depending on which
arguments are present.
"""
def override(f):
set_explicit_override(f)
set_forced_override(f, force)
return f
if func is not None:
return override(func)
return override
| {
"content_hash": "30d816414a3813bd477ee59d766eff3b",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 102,
"avg_line_length": 36.25853658536585,
"alnum_prop": 0.5735234763890757,
"repo_name": "matthewwardrop/interface_meta",
"id": "40cd0912c1c17c3394495f67cdbe71d43b90ed3a",
"size": "7433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "interface_meta/interface.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "40533"
}
],
"symlink_target": ""
} |
from __future__ import print_function
import numpy as np
import sys
import sqaod
from sqaod import algorithm as algo
from . import formulas
from sqaod.common import checkers, symmetrize
class DenseGraphBFSearcher :
""" Dense graph brute-force searcher"""
def __init__(self, W, optimize, prefdict) :
if W is not None :
self.set_qubo(W, optimize)
self._tile_size = 1024
self.set_preferences(prefdict)
def set_qubo(self, W, optimize = sqaod.minimize) :
""" set QUBO.
Args:
numpy.ndarray W :
QUBO matrix. W should be a sqaure matrix.
Upper/Lower triangular matrices or symmetric matrices are accepted.
optimize : optimize direction, `sqaod.maximize, sqaod.minimize <preference.html#sqaod-maximize-sqaod-minimize>` """
checkers.dense_graph.qubo(W)
W = symmetrize(W)
N = W.shape[0]
self._W = optimize.sign(W)
self._N = N
self._x = []
self._optimize = optimize
def _get_algorithm(self) :
return algo.brute_force_search
def set_preferences(self, prefdict=None, **prefs) :
""" set solver preferences.
Args:
prefdict(dict) : preference dictionary.
prefs(dict) : preference dictionary as \*\*kwargs.
References:
`preference <preference.html>`_
"""
if not prefdict is None :
self._set_prefdict(prefdict)
self._set_prefdict(prefs)
def _set_prefdict(self, prefdict) :
v = prefdict.get('tile_size')
if v is not None :
self._tile_size = v;
def get_problem_size(self) :
""" get problem size.
Problem size is defined as a number of bits of QUBO.
Returns:
tuple containing problem size, (N0, N1).
"""
return self._N
def get_preferences(self) :
""" get solver preferences.
Returns:
dict: preference dictionary.
References:
`preference <preference.html>`_
"""
prefs = {}
prefs['tile_size'] = self._tile_size
prefs['algorithm'] = self._get_algorithm()
return prefs
def get_optimize_dir(self) :
""" get optimize direction
Returns:
optimize direction, `sqaod.maximize, sqaod.minimize <preference.html#sqaod-maximize-sqaod-minimize>`_.
"""
return self._optimize
def get_E(self) :
""" get QUBO energy.
Returns:
array of floating point number : QUBO energy.
QUBO energy value is calculated for each trotter. so E is a vector whose length is m.
Notes:
You need to call calculate_E() or make_solution() before calling get_E().
CPU/CUDA versions of solvers automatically call calculate_E() in get_E()
"""
return self._E
def get_x(self) :
""" get bits.
Returns:
tuple of 2 numpy.int8 arrays : array of bit {0, 1}.
x0.shape and x1.shape are (m, N0) and (m, N1) repsectively, and m is number of trotters.
Note:
calculate_E() or make_solution() should be called before calling get_E().
( CPU/CUDA annealers automatically/internally call calculate_E().)
"""
return self._x
def prepare(self) :
""" preparation of internal resources.
Note:
prepare() should be called prior to run annealing loop.
"""
N = self._N
self._tile_size = min(1 << N, self._tile_size)
self._xMax = 1 << N
self._Emin = sys.float_info.max
self._xbegin = 0
def make_solution(self) :
""" calculate QUBO energy.
This method calculate QUBO energy, and caches it, does not return any value.
Note:
A call to this method can be asynchronous.
"""
self.calculate_E()
def calculate_E(self) :
""" calculate QUBO energy.
This method calculate QUBO energy, and caches it, does not return any value.
Note:
A call to this method can be asynchronous.
"""
nMinX = len(self._x)
self._E = np.empty((nMinX))
self._E[...] = self._optimize.sign(self._Emin)
def search_range(self) :
""" Search minimum of QUBO energy within a range.
Returns:
True if search completed, False otherwise.
This method enables stepwise minimum QUBO energy search.
One method call covers a range specified by 'tile_size'.
When a given problem is big, whole search takes very long time.
By using this method, you can do searches stepwise.
"""
xBegin = self._xbegin
xEnd = self._tile_size
N = self._N
W = self._W
xBegin = max(0, min(self._xMax, xBegin))
xEnd = max(0, min(self._xMax, xEnd))
x = sqaod.create_bitset_sequence(range(xBegin, xEnd), N)
Etmp = formulas.dense_graph_batch_calculate_E(W, x)
for i in range(xEnd - xBegin) :
if self._Emin < Etmp[i] :
continue
elif Etmp[i] < self._Emin :
self._Emin = Etmp[i]
self._x = [x[i]]
else :
self._x.append(x[i])
self._xbegin = xEnd
return self._xbegin == self._xMax
def search(self) :
""" One liner for brute-force search. """
self.prepare()
xStep = min(self._tile_size, self._xMax)
while not self.search_range() :
pass
self.make_solution()
def dense_graph_bf_searcher(W = None, optimize = sqaod.minimize, **prefs) :
""" factory function for sqaod.py.DenseGraphAnnealer.
Args:
numpy.ndarray : QUBO
optimize : specify optimize direction, `sqaod.maximize or sqaod.minimize <preference.html#sqaod-maximize-sqaod-minimize>`_.
prefs : `preference <preference.html>`_ as \*\*kwargs
Returns:
sqaod.py.DenseGraphBFSearcher: brute-force searcher instance
"""
return DenseGraphBFSearcher(W, optimize, prefs)
if __name__ == '__main__' :
W = np.array([[-32,4,4,4,4,4,4,4],
[4,-32,4,4,4,4,4,4],
[4,4,-32,4,4,4,4,4],
[4,4,4,-32,4,4,4,4],
[4,4,4,4,-32,4,4,4],
[4,4,4,4,4,-32,4,4],
[4,4,4,4,4,4,-32,4],
[4,4,4,4,4,4,4,-32]])
N = 8
bf = dense_graph_bf_searcher(W, sqaod.minimize)
bf.search()
E = bf.get_E()
x = bf.get_x()
print(E, len(x), x[0])
bf = dense_graph_bf_searcher(W, sqaod.maximize)
bf.search()
E = bf.get_E()
x = bf.get_x()
print(E, len(x), x[0])
| {
"content_hash": "d57a11c05e8af2510d4c8c1b34237c56",
"timestamp": "",
"source": "github",
"line_count": 230,
"max_line_length": 132,
"avg_line_length": 29.891304347826086,
"alnum_prop": 0.5460363636363637,
"repo_name": "shinmorino/quant_sandbox",
"id": "d9eec51ecfc8aea79b6164f61405746a3f236851",
"size": "6875",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sqaodpy/sqaod/py/dense_graph_bf_searcher.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "120151"
},
{
"name": "M4",
"bytes": "909"
},
{
"name": "Makefile",
"bytes": "1892"
},
{
"name": "Python",
"bytes": "61808"
},
{
"name": "Shell",
"bytes": "490"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
from django.db import migrations
from recipe.configuration.data.recipe_data import LegacyRecipeData
class Migration(migrations.Migration):
dependencies = [
('storage', '0002_workspace_is_move_enabled'),
('recipe', '0015_recipefile'),
]
def populate_recipe_file(apps, schema_editor):
# Go through all of the recipe models and create a recipe file model for each of the recipe input files
Recipe = apps.get_model('recipe', 'Recipe')
RecipeFile = apps.get_model('recipe', 'RecipeFile')
ScaleFile = apps.get_model('storage', 'ScaleFile')
total_count = Recipe.objects.all().count()
if not total_count:
return
print('\nCreating new recipe_file table rows: %i' % total_count)
done_count = 0
fail_count = 0
batch_size = 500
while done_count < total_count:
batch_end = done_count + batch_size
# Build a unique list of all valid input file ids
batch_file_ids = set()
recipes = Recipe.objects.all().order_by('id')[done_count:batch_end]
for recipe in recipes:
batch_file_ids.update(LegacyRecipeData(recipe.data).get_input_file_ids())
valid_file_ids = {scale_file.id for scale_file in ScaleFile.objects.filter(pk__in=batch_file_ids)}
# Create a model for each recipe input file
recipe_files = []
for recipe in recipes:
input_file_ids = LegacyRecipeData(recipe.data).get_input_file_ids()
for input_file_id in input_file_ids:
if input_file_id in valid_file_ids:
recipe_file = RecipeFile()
recipe_file.recipe_id = recipe.id
recipe_file.scale_file_id = input_file_id
recipe_file.created = recipe.created
recipe_files.append(recipe_file)
else:
fail_count += 1
print('Failed recipe: %i -> file: %i' % (recipe.id, input_file_id))
RecipeFile.objects.bulk_create(recipe_files)
done_count += len(recipes)
percent = (float(done_count) / float(total_count)) * 100.00
print('Progress: %i/%i (%.2f%%)' % (done_count, total_count, percent))
print ('Migration finished. Failed: %i' % fail_count)
operations = [
migrations.RunPython(populate_recipe_file),
]
| {
"content_hash": "507c9b8cff78d648c5d425277ed33e90",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 111,
"avg_line_length": 40.3968253968254,
"alnum_prop": 0.574852652259332,
"repo_name": "ngageoint/scale",
"id": "c2a6572f33fa66e0301080773cc494f1ef96afec",
"size": "2569",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scale/recipe/migrations/0016_recipefile_data.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "7219"
},
{
"name": "CSS",
"bytes": "12193"
},
{
"name": "Dockerfile",
"bytes": "14853"
},
{
"name": "HCL",
"bytes": "301"
},
{
"name": "HTML",
"bytes": "48818"
},
{
"name": "JavaScript",
"bytes": "503"
},
{
"name": "Makefile",
"bytes": "5852"
},
{
"name": "Python",
"bytes": "5295677"
},
{
"name": "Shell",
"bytes": "26650"
}
],
"symlink_target": ""
} |
import sublime, sublime_plugin
import re
def TagRemoveAttributesClean(data):
regexp = re.compile('(<([a-z0-9\:\-_]+)\s+>)');
data = regexp.sub('<\\2>', data);
return data
def TagRemoveAttributesAll(data, view):
return TagRemoveAttributesClean(re.sub('(<([a-z0-9\:\-_]+)\s+[^>]+>)', '<\\2>', data));
def TagRemoveAttributesSelected(data, attributes, view):
attributes = attributes.replace(',', ' ').replace(';', ' ').replace('|', ' ')+' '
for attribute in attributes.split(' '):
if attribute:
regexp = re.compile('(<([a-z0-9\:\-_]+\s+)([^>]*)\s*'+re.escape(attribute)+'="[^"]+"\s*([^>]*)>)')
data = regexp.sub('<\\2\\3\\4>', data);
data = TagRemoveAttributesClean(data);
return data;
class TagRemoveAllAttributesInSelectionCommand(sublime_plugin.TextCommand):
def run(self, edit):
for region in self.view.sel():
if region.empty():
continue
dataRegion = sublime.Region(region.begin(), region.end())
data = TagRemoveAttributesAll(self.view.substr(dataRegion), self.view)
self.view.replace(edit, dataRegion, data);
class TagRemoveAllAttributesInDocumentCommand(sublime_plugin.TextCommand):
def run(self, edit):
dataRegion = sublime.Region(0, self.view.size())
data = TagRemoveAttributesAll(self.view.substr(dataRegion), self.view)
self.view.replace(edit, dataRegion, data);
class TagRemovePickedAttributesInSelectionCommand(sublime_plugin.TextCommand):
def run(self, edit, attributes = False):
if not attributes:
import functools
self.view.window().run_command('hide_panel');
self.view.window().show_input_panel("Remove the following attributes:", '', functools.partial(self.on_done, edit), None, None)
else:
self.on_done(edit, attributes)
def on_done(self, edit, attributes):
for region in self.view.sel():
if region.empty():
continue
dataRegion = sublime.Region(region.begin(), region.end())
data = TagRemoveAttributesSelected(self.view.substr(dataRegion), attributes, self.view)
self.view.replace(edit, dataRegion, data);
class TagRemovePickedAttributesInDocumentCommand(sublime_plugin.TextCommand):
def run(self, edit, attributes = False):
if not attributes:
import functools
self.view.window().run_command('hide_panel');
self.view.window().show_input_panel("Remove the following attributes:", '', functools.partial(self.on_done, edit), None, None)
else:
self.on_done(edit, attributes)
def on_done(self, edit, attributes):
dataRegion = sublime.Region(0, self.view.size())
data = TagRemoveAttributesSelected(self.view.substr(dataRegion), attributes, self.view)
self.view.replace(edit, dataRegion, data); | {
"content_hash": "6c8d8a53977782ca52a41238cae255f5",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 129,
"avg_line_length": 40.261538461538464,
"alnum_prop": 0.7065341994650363,
"repo_name": "Iristyle/ChocolateyPackages",
"id": "3b64546f4646242118fd6065cb314f11c77e168d",
"size": "2617",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "EthanBrown.SublimeText2.WebPackages/tools/PackageCache/Tag/tag_remove_attributes.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "43"
},
{
"name": "C",
"bytes": "776"
},
{
"name": "CSS",
"bytes": "25672"
},
{
"name": "CoffeeScript",
"bytes": "445"
},
{
"name": "HTML",
"bytes": "13497"
},
{
"name": "JavaScript",
"bytes": "1157570"
},
{
"name": "PowerShell",
"bytes": "176361"
},
{
"name": "Python",
"bytes": "2764348"
},
{
"name": "Ruby",
"bytes": "1341"
}
],
"symlink_target": ""
} |
import requests
import uuid
from datetime import timedelta
from django.utils import datetime_safe
from keystoneclient.access import AccessInfo
from keystoneclient.service_catalog import ServiceCatalog
from keystoneclient.v3.domains import Domain, DomainManager
from keystoneclient.v3.roles import Role, RoleManager
from keystoneclient.v3.projects import Project, ProjectManager
from keystoneclient.v3.users import User, UserManager
class TestDataContainer(object):
""" Arbitrary holder for test data in an object-oriented fashion. """
pass
class TestResponse(requests.Response):
""" Class used to wrap requests.Response and provide some
convenience to initialize with a dict """
def __init__(self, data):
self._text = None
super(TestResponse, self)
if isinstance(data, dict):
self.status_code = data.get('status_code', None)
self.headers = data.get('headers', None)
# Fake the text attribute to streamline Response creation
self._text = data.get('text', None)
else:
self.status_code = data
def __eq__(self, other):
return self.__dict__ == other.__dict__
@property
def text(self):
return self._text
def generate_test_data():
''' Builds a set of test_data data as returned by Keystone V2. '''
test_data = TestDataContainer()
keystone_service = {
'type': 'identity',
'id': uuid.uuid4().hex,
'endpoints': [
{
'url': 'http://admin.localhost:35357/v3',
'region': 'RegionOne',
'interface': 'admin',
'id': uuid.uuid4().hex,
},
{
'url': 'http://internal.localhost:5000/v3',
'region': 'RegionOne',
'interface': 'internal',
'id': uuid.uuid4().hex
},
{
'url': 'http://public.localhost:5000/v3',
'region': 'RegionOne',
'interface': 'public',
'id': uuid.uuid4().hex
}
]
}
# Domains
domain_dict = {'id': uuid.uuid4().hex,
'name': 'domain',
'description': '',
'enabled': True}
test_data.domain = Domain(DomainManager(None), domain_dict, loaded=True)
# Users
user_dict = {'id': uuid.uuid4().hex,
'name': 'gabriel',
'email': 'gabriel@example.com',
'password': 'swordfish',
'domain_id': domain_dict['id'],
'token': '',
'enabled': True}
test_data.user = User(UserManager(None), user_dict, loaded=True)
# Projects
project_dict_1 = {'id': uuid.uuid4().hex,
'name': 'tenant_one',
'description': '',
'domain_id': domain_dict['id'],
'enabled': True}
project_dict_2 = {'id': uuid.uuid4().hex,
'name': '',
'description': '',
'domain_id': domain_dict['id'],
'enabled': False}
test_data.project_one = Project(ProjectManager(None),
project_dict_1,
loaded=True)
test_data.project_two = Project(ProjectManager(None),
project_dict_2,
loaded=True)
# Roles
role_dict = {'id': uuid.uuid4().hex,
'name': 'Member'}
test_data.role = Role(RoleManager, role_dict)
nova_service = {
'type': 'compute',
'id': uuid.uuid4().hex,
'endpoints': [
{
'url': 'http://nova-admin.localhost:8774/v2.0/%s' \
% (project_dict_1['id']),
'region': 'RegionOne',
'interface': 'admin',
'id': uuid.uuid4().hex,
},
{
'url': 'http://nova-internal.localhost:8774/v2.0/%s' \
% (project_dict_1['id']),
'region': 'RegionOne',
'interface': 'internal',
'id': uuid.uuid4().hex
},
{
'url': 'http://nova-public.localhost:8774/v2.0/%s' \
% (project_dict_1['id']),
'region': 'RegionOne',
'interface': 'public',
'id': uuid.uuid4().hex
},
{
'url': 'http://nova2-admin.localhost:8774/v2.0/%s' \
% (project_dict_1['id']),
'region': 'RegionTwo',
'interface': 'admin',
'id': uuid.uuid4().hex,
},
{
'url': 'http://nova2-internal.localhost:8774/v2.0/%s' \
% (project_dict_1['id']),
'region': 'RegionTwo',
'interface': 'internal',
'id': uuid.uuid4().hex
},
{
'url': 'http://nova2-public.localhost:8774/v2.0/%s' \
% (project_dict_1['id']),
'region': 'RegionTwo',
'interface': 'public',
'id': uuid.uuid4().hex
}
]
}
# Tokens
tomorrow = datetime_safe.datetime.now() + timedelta(days=1)
expiration = datetime_safe.datetime.isoformat(tomorrow)
auth_token = uuid.uuid4().hex
auth_response_headers = {
'X-Subject-Token': auth_token
}
auth_response = TestResponse({
"headers": auth_response_headers
})
scoped_token_dict = {
'token': {
'methods': ['password'],
'expires_at': expiration,
'project': {
'id': project_dict_1['id'],
'name': project_dict_1['name'],
'domain': {
'id': domain_dict['id'],
'name': domain_dict['name']
}
},
'user': {
'id': user_dict['id'],
'name': user_dict['name'],
'domain': {
'id': domain_dict['id'],
'name': domain_dict['name']
}
},
'roles': [role_dict],
'catalog': [keystone_service, nova_service]
}
}
test_data.scoped_access_info = AccessInfo.factory(
resp=auth_response,
body=scoped_token_dict
)
unscoped_token_dict = {
'token': {
'methods': ['password'],
'expires_at': expiration,
'user': {
'id': user_dict['id'],
'name': user_dict['name'],
'domain': {
'id': domain_dict['id'],
'name': domain_dict['name']
}
},
'catalog': [keystone_service]
}
}
test_data.unscoped_access_info = AccessInfo.factory(
resp=auth_response,
body=unscoped_token_dict
)
# Service Catalog
test_data.service_catalog = ServiceCatalog.factory({
'methods': ['password'],
'user': {},
'catalog': [keystone_service, nova_service],
}, token=auth_token)
return test_data
| {
"content_hash": "511107ff7e0dfd323af5bf2706bc3aed",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 76,
"avg_line_length": 31.685344827586206,
"alnum_prop": 0.45898517208543055,
"repo_name": "tylertian/Openstack",
"id": "4f13738b712504376f8dee27accb20964bb0c1a9",
"size": "7351",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "openstack F/django_openstack_auth/openstack_auth/tests/data_v3.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "239919"
},
{
"name": "JavaScript",
"bytes": "156942"
},
{
"name": "Python",
"bytes": "16949418"
},
{
"name": "Shell",
"bytes": "96743"
}
],
"symlink_target": ""
} |
class XContentTypeOptionsAnalyzer:
def __init__(self):
pass
def analyze(self, parse_results, headers, content):
results = parse_results["X-Content-Type-Options"]
parts = []
if results["status"] == "X_CONTENT_TYPE_OPTIONS_NONE":
parts.append({
"type" : "warning",
"message" : "X-Content-Type-Options is not specified. Browser can attempt to infer the response type based of the content, the URL or how it was requested. This may lead to indesirable behavior which can have a security impact."
})
return "X-Content-Type-Options Header", parts
| {
"content_hash": "79fd8da22a3e9df81a563e64138764ad",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 232,
"avg_line_length": 38,
"alnum_prop": 0.712280701754386,
"repo_name": "HoLyVieR/http-security-headers",
"id": "265aa65db5884421f5a92914883b9b774cc763b4",
"size": "570",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "analyzer/XContentTypeOptionsAnalyzer.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "33357"
}
],
"symlink_target": ""
} |
from taskflow.patterns import linear_flow as lf
from taskflow.task import FunctorTask
from jobrunner.utils import list_tasks_in_flow
from tests.testcase import TestCase
def noop():
pass
class TestListTasksInFlow(TestCase):
def setUp(self):
self.flow_1 = lf.Flow("flow1")
self.flow_2 = lf.Flow("flow2")
self.flow_2.add(
FunctorTask(
name='task1', execute=noop
)
)
self.flow_3 = lf.Flow("flow3")
self.flow_3.add(
FunctorTask(
name='task1', execute=noop
),
FunctorTask(
name='task2', execute=noop
)
)
def test_list_tasks_in_flow_returns_empty_list_for_empty_flow(self):
ret = list_tasks_in_flow(self.flow_1)
self.assertEqual(ret, list())
def test_list_tasks_in_flow_returns_one_item_if_one_item_in_flow(self):
ret = list_tasks_in_flow(self.flow_2)
expected_list = ['task1']
self.assertEqual(ret, expected_list)
def test_list_tasks_in_flow_returns_two_items_if_two_items_in_flow(self):
ret = list_tasks_in_flow(self.flow_3)
print(list(self.flow_3.iter_nodes()))
expected_list = ['task1', 'task2']
self.assertEqual(ret, expected_list)
| {
"content_hash": "79b4a55aa5038f57b0fefa3c64e04fe3",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 77,
"avg_line_length": 27.851063829787233,
"alnum_prop": 0.5882352941176471,
"repo_name": "vdloo/jobrunner",
"id": "666d91239cb1b9982da261adabe19c46dc8ae9f7",
"size": "1309",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/unit/jobrunner/utils/test_list_tasks_in_flow.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "102107"
},
{
"name": "Shell",
"bytes": "2630"
}
],
"symlink_target": ""
} |
import logging
from argparse import ArgumentParser
from .common import create_loggers
from ebu_tt_live.node.distributing import DistributingNode
from ebu_tt_live.clocks.local import LocalMachineClock
from ebu_tt_live.twisted import TwistedConsumer, UserInputServerProtocol, UserInputServerFactory, \
BroadcastServerFactory, TwistedPushProducer, BroadcastServerProtocol
from ebu_tt_live.carriage.filesystem import FilesystemProducerImpl
from ebu_tt_live.carriage.websocket import WebsocketConsumerCarriage, WebsocketProducerCarriage
from twisted.internet import reactor
log = logging.getLogger('ebu_simple_consumer')
parser = ArgumentParser()
parser.add_argument('-c', '--config', dest='config', metavar='CONFIG')
parser.add_argument('-u', '--websocket-url', dest='websocket_url',
help='URL for the websocket address to connect to',
default='ws://127.0.0.1:9001')
parser.add_argument('--folder-export', dest='folder_export',
help='export xml files to given folder',
type=str
)
def main():
args = parser.parse_args()
create_loggers()
do_export = False
if args.folder_export:
do_export = True
sub_consumer_impl = WebsocketConsumerCarriage()
sub_prod_impl = None
if do_export:
sub_prod_impl = FilesystemProducerImpl(args.folder_export)
else:
sub_prod_impl = WebsocketProducerCarriage()
reference_clock = LocalMachineClock()
reference_clock.clock_mode = 'local'
dist_node = DistributingNode(
node_id='distributing-node',
producer_carriage=sub_prod_impl,
consumer_carriage=sub_consumer_impl,
reference_clock=reference_clock
)
# This factory listens for incoming documents from the user input producer.
user_input_server_factory = UserInputServerFactory(
url=args.websocket_url,
consumer=TwistedConsumer(
custom_consumer=sub_consumer_impl
)
)
user_input_server_factory.protocol = UserInputServerProtocol
user_input_server_factory.listen()
if not do_export:
# This factory listens for any consumer to forward documents to.
broadcast_factory = BroadcastServerFactory("ws://127.0.0.1:9000")
broadcast_factory.protocol = BroadcastServerProtocol
broadcast_factory.listen()
TwistedPushProducer(
consumer=broadcast_factory,
custom_producer=sub_prod_impl
)
reactor.run()
| {
"content_hash": "095c9364e32a1b2493b5ac2856fdb4f7",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 99,
"avg_line_length": 33.54666666666667,
"alnum_prop": 0.6903815580286169,
"repo_name": "bbc/ebu-tt-live-toolkit",
"id": "adc14fc61c2557eef982520862485112dd934de5",
"size": "2585",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ebu_tt_live/scripts/ebu_user_input_forwarder.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "827"
},
{
"name": "CSS",
"bytes": "1835"
},
{
"name": "Gherkin",
"bytes": "184126"
},
{
"name": "HTML",
"bytes": "16970"
},
{
"name": "JavaScript",
"bytes": "156508"
},
{
"name": "Makefile",
"bytes": "1320"
},
{
"name": "Python",
"bytes": "665429"
}
],
"symlink_target": ""
} |
import datetime
from operator import attrgetter
import os
from pathlib import Path
from django.contrib.sites.models import Site
from django.core.urlresolvers import set_urlconf
from django.template import Context, Template
from django.test import TestCase
from releases.models import Release
from .models import Document, DocumentRelease
from .sitemaps import DocsSitemap
from .utils import get_doc_path
class ModelsTests(TestCase):
def test_dev_is_supported(self):
"""
Document for a release without a date ("dev") is supported.
"""
d = DocumentRelease.objects.create()
self.assertTrue(d.is_supported)
self.assertTrue(d.is_dev)
def test_current_is_supported(self):
"""
Document with a release without an EOL date is supported.
"""
today = datetime.date.today()
day = datetime.timedelta(1)
r = Release.objects.create(version='1.8',
date=today - 5 * day)
d = DocumentRelease.objects.create(release=r)
self.assertTrue(d.is_supported)
self.assertFalse(d.is_dev)
def test_previous_is_supported(self):
"""
Document with a release with an EOL date in the future is supported.
"""
today = datetime.date.today()
day = datetime.timedelta(1)
r = Release.objects.create(version='1.8',
date=today - 5 * day,
eol_date=today + 5 * day)
d = DocumentRelease.objects.create(release=r)
self.assertTrue(d.is_supported)
self.assertFalse(d.is_dev)
def test_old_is_unsupported(self):
"""
Document with a release with an EOL date in the past is insupported.
"""
today = datetime.date.today()
day = datetime.timedelta(1)
r = Release.objects.create(version='1.8',
date=today - 15 * day,
eol_date=today - 5 * day)
d = DocumentRelease.objects.create(release=r)
self.assertFalse(d.is_supported)
self.assertFalse(d.is_dev)
def test_most_recent_micro_release_considered(self):
"""
Dates are looked up on the latest micro release in a given series.
"""
today = datetime.date.today()
day = datetime.timedelta(1)
r = Release.objects.create(version='1.8',
date=today - 15 * day)
d = DocumentRelease.objects.create(release=r)
r2 = Release.objects.create(version='1.8.1',
date=today - 5 * day)
# The EOL date of the first release is set automatically.
r.refresh_from_db()
self.assertEqual(r.eol_date, r2.date)
# Since 1.8.1 is still supported, docs show up as supported.
self.assertTrue(d.is_supported)
self.assertFalse(d.is_dev)
class SearchFormTestCase(TestCase):
fixtures = ['doc_test_fixtures']
def setUp(self):
# We need to create an extra Site because docs have SITE_ID=2
Site.objects.create(name='Django test', domain="example2.com")
@classmethod
def tearDownClass(cls):
# cleanup URLconfs changed by django-hosts
set_urlconf(None)
super(SearchFormTestCase, cls).tearDownClass()
def test_empty_get(self):
response = self.client.get('/en/dev/search/',
HTTP_HOST='docs.djangoproject.dev:8000')
self.assertEqual(response.status_code, 200)
class TemplateTagTests(TestCase):
def test_pygments_template_tag(self):
template = Template('''
{% load docs %}
{% pygment 'python' %}
def band_listing(request):
"""A view of all bands."""
bands = models.Band.objects.all()
return render(request, 'bands/band_listing.html', {'bands': bands})
{% endpygment %}
''')
self.assertEqual(
template.render(Context()),
"\n\n<div class=\"highlight\"><pre><span class=\"k\">def</span> <span class=\"nf\">"
"band_listing</span><span class=\"p\">(</span><span class=\"n\">request</span><span "
"class=\"p\">):</span>\n <span class=\"sd\">"""A view of all bands"
"."""</span>\n <span class=\"n\">bands</span> <span class=\"o\">="
"</span> <span class=\"n\">models</span><span class=\"o\">.</span><span class=\"n\">"
"Band</span><span class=\"o\">.</span><span class=\"n\">objects</span><span "
"class=\"o\">.</span><span class=\"n\">all</span><span class=\"p\">()</span>\n "
"<span class=\"k\">return</span> <span class=\"n\">render</span><span class=\"p\">"
"(</span><span class=\"n\">request</span><span class=\"p\">,</span> <span class=\"s\">"
"'bands/band_listing.html'</span><span class=\"p\">,</span> <span class=\"p\">"
"{</span><span class=\"s\">'bands'</span><span class=\"p\">:</span> "
"<span class=\"n\">bands</span><span class=\"p\">})</span>\n</pre></div>\n\n"
)
class TestUtils(TestCase):
def test_get_doc_path(self):
# non-existent file
self.assertEqual(get_doc_path(Path('root'), 'subpath.txt'), None)
# existing file
path, filename = __file__.rsplit(os.path.sep, 1)
self.assertEqual(get_doc_path(Path(path), filename), None)
class UpdateDocTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.release = DocumentRelease.objects.create(version='dev')
def test_sync_to_db(self):
self.release.sync_to_db([{
'body': 'This is the body',
'title': 'This is the title',
'current_page_name': 'foo/bar',
}])
self.assertQuerysetEqual(self.release.documents.all(), ['<Document: en/dev/foo/bar>'])
def test_clean_path(self):
self.release.sync_to_db([{
'body': 'This is the body',
'title': 'This is the title',
'current_page_name': 'foo/bar/index',
}])
self.assertQuerysetEqual(self.release.documents.all(), ['<Document: en/dev/foo/bar>'])
def test_title_strip_tags(self):
self.release.sync_to_db([{
'body': 'This is the body',
'title': 'This is the <strong>title</strong>',
'current_page_name': 'foo/bar',
}])
self.assertQuerysetEqual(self.release.documents.all(), ['This is the title'], transform=attrgetter('title'))
def test_title_entities(self):
self.release.sync_to_db([{
'body': 'This is the body',
'title': 'Title & title',
'current_page_name': 'foo/bar',
}])
self.assertQuerysetEqual(self.release.documents.all(), ['Title & title'], transform=attrgetter('title'))
def test_empty_documents(self):
self.release.sync_to_db([
{'title': 'Empty body document', 'current_page_name': 'foo/1'},
{'body': 'Empty title document', 'current_page_name': 'foo/2'},
{'current_page_name': 'foo/3'},
])
self.assertQuerysetEqual(self.release.documents.all(), [])
class SitemapTests(TestCase):
def test_sitemap(self):
doc_release = DocumentRelease.objects.create()
document = Document.objects.create(release=doc_release)
sitemap = DocsSitemap()
urls = sitemap.get_urls()
self.assertEqual(len(urls), 1)
url_info = urls[0]
self.assertEqual(url_info['location'], document.get_absolute_url())
| {
"content_hash": "ab36faf6a996bbcd24049ef000b16668",
"timestamp": "",
"source": "github",
"line_count": 205,
"max_line_length": 116,
"avg_line_length": 37.141463414634146,
"alnum_prop": 0.5785395324402417,
"repo_name": "xavierdutreilh/djangoproject.com",
"id": "d499478f9df7d81aeb9f32abf3e492a129e818cf",
"size": "7614",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/tests.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "133549"
},
{
"name": "CoffeeScript",
"bytes": "24188"
},
{
"name": "HTML",
"bytes": "218462"
},
{
"name": "JavaScript",
"bytes": "808120"
},
{
"name": "Makefile",
"bytes": "1628"
},
{
"name": "Python",
"bytes": "522326"
},
{
"name": "Ruby",
"bytes": "19821"
},
{
"name": "Smalltalk",
"bytes": "1917"
}
],
"symlink_target": ""
} |
import re
import coredata
from glob import glob
from compilers import *
import configparser
build_filename = 'meson.build'
def find_coverage_tools():
gcovr_exe = 'gcovr'
lcov_exe = 'lcov'
genhtml_exe = 'genhtml'
if not mesonlib.exe_exists([gcovr_exe, '--version']):
gcovr_exe = None
if not mesonlib.exe_exists([lcov_exe, '--version']):
lcov_exe = None
if not mesonlib.exe_exists([genhtml_exe, '--version']):
genhtml_exe = None
return (gcovr_exe, lcov_exe, genhtml_exe)
def find_valgrind():
valgrind_exe = 'valgrind'
if not mesonlib.exe_exists([valgrind_exe, '--version']):
valgrind_exe = None
return valgrind_exe
def detect_ninja():
for n in ['ninja', 'ninja-build']:
try:
p = subprocess.Popen([n, '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except FileNotFoundError:
continue
p.communicate()
if p.returncode == 0:
return n
class Environment():
private_dir = 'meson-private'
log_dir = 'meson-logs'
coredata_file = os.path.join(private_dir, 'coredata.dat')
version_regex = '\d+(\.\d+)+(-[a-zA-Z0-9]+)?'
def __init__(self, source_dir, build_dir, main_script_file, options):
assert(os.path.isabs(main_script_file))
assert(not os.path.islink(main_script_file))
self.source_dir = source_dir
self.build_dir = build_dir
self.meson_script_file = main_script_file
self.scratch_dir = os.path.join(build_dir, Environment.private_dir)
self.log_dir = os.path.join(build_dir, Environment.log_dir)
os.makedirs(self.scratch_dir, exist_ok=True)
os.makedirs(self.log_dir, exist_ok=True)
try:
cdf = os.path.join(self.get_build_dir(), Environment.coredata_file)
self.coredata = coredata.load(cdf)
except FileNotFoundError:
self.coredata = coredata.CoreData(options)
if self.coredata.cross_file:
self.cross_info = CrossBuildInfo(self.coredata.cross_file)
else:
self.cross_info = None
self.cmd_line_options = options.projectoptions
# List of potential compilers.
if mesonlib.is_windows():
self.default_c = ['cl', 'cc', 'gcc']
self.default_cpp = ['cl', 'c++']
else:
self.default_c = ['cc']
self.default_cpp = ['c++']
self.default_objc = ['cc']
self.default_objcpp = ['c++']
self.default_fortran = ['gfortran', 'g95', 'f95', 'f90', 'f77']
self.default_static_linker = 'ar'
self.vs_static_linker = 'lib'
cross = self.is_cross_build()
if (not cross and mesonlib.is_windows()) \
or (cross and self.cross_info.has_host() and self.cross_info.config['host_machine']['name'] == 'windows'):
self.exe_suffix = 'exe'
self.import_lib_suffix = 'lib'
self.shared_lib_suffix = 'dll'
self.shared_lib_prefix = ''
self.static_lib_suffix = 'lib'
self.static_lib_prefix = ''
self.object_suffix = 'obj'
else:
self.exe_suffix = ''
if (not cross and mesonlib.is_osx()) or \
(cross and self.cross_info.has_host() and self.cross_info.config['host_machine']['name'] == 'darwin'):
self.shared_lib_suffix = 'dylib'
else:
self.shared_lib_suffix = 'so'
self.shared_lib_prefix = 'lib'
self.static_lib_suffix = 'a'
self.static_lib_prefix = 'lib'
self.object_suffix = 'o'
self.import_lib_suffix = self.shared_lib_suffix
def is_cross_build(self):
return self.cross_info is not None
def generating_finished(self):
cdf = os.path.join(self.get_build_dir(), Environment.coredata_file)
coredata.save(self.coredata, cdf)
def get_script_dir(self):
return os.path.dirname(self.meson_script_file)
def get_log_dir(self):
return self.log_dir
def get_coredata(self):
return self.coredata
def get_build_command(self):
return self.meson_script_file
def is_header(self, fname):
return is_header(fname)
def is_source(self, fname):
return is_source(fname)
def is_object(self, fname):
return is_object(fname)
def merge_options(self, options):
for (name, value) in options.items():
if name not in self.coredata.user_options:
self.coredata.user_options[name] = value
else:
oldval = self.coredata.user_options[name]
if type(oldval) != type(value):
self.coredata.user_options[name] = value
def detect_c_compiler(self, want_cross):
evar = 'CC'
if self.is_cross_build() and want_cross:
compilers = [self.cross_info.config['binaries']['c']]
ccache = []
is_cross = True
exe_wrap = self.cross_info.config['binaries'].get('exe_wrapper', None)
elif evar in os.environ:
compilers = os.environ[evar].split()
ccache = []
is_cross = False
exe_wrap = None
else:
compilers = self.default_c
ccache = self.detect_ccache()
is_cross = False
exe_wrap = None
for compiler in compilers:
try:
basename = os.path.basename(compiler).lower()
if basename == 'cl' or basename == 'cl.exe':
arg = '/?'
else:
arg = '--version'
p = subprocess.Popen([compiler] + [arg], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except OSError:
continue
(out, err) = p.communicate()
out = out.decode()
err = err.decode()
vmatch = re.search(Environment.version_regex, out)
if vmatch:
version = vmatch.group(0)
else:
version = 'unknown version'
if 'apple' in out and 'Free Software Foundation' in out:
return GnuCCompiler(ccache + [compiler], version, GCC_OSX, is_cross, exe_wrap)
if (out.startswith('cc') or 'gcc' in out) and \
'Free Software Foundation' in out:
return GnuCCompiler(ccache + [compiler], version, GCC_STANDARD, is_cross, exe_wrap)
if 'clang' in out:
return ClangCCompiler(ccache + [compiler], version, is_cross, exe_wrap)
if 'Microsoft' in out:
# Visual Studio prints version number to stderr but
# everything else to stdout. Why? Lord only knows.
version = re.search(Environment.version_regex, err).group()
return VisualStudioCCompiler([compiler], version, is_cross, exe_wrap)
raise EnvironmentException('Unknown compiler(s): "' + ', '.join(compilers) + '"')
def detect_fortran_compiler(self, want_cross):
evar = 'FC'
if self.is_cross_build() and want_cross:
compilers = [self.cross_info['fortran']]
is_cross = True
exe_wrap = self.cross_info.get('exe_wrapper', None)
elif evar in os.environ:
compilers = os.environ[evar].split()
is_cross = False
exe_wrap = None
else:
compilers = self.default_fortran
is_cross = False
exe_wrap = None
for compiler in compilers:
for arg in ['--version', '-V']:
try:
p = subprocess.Popen([compiler] + [arg],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except OSError:
continue
(out, err) = p.communicate()
out = out.decode()
err = err.decode()
version = 'unknown version'
vmatch = re.search(Environment.version_regex, out)
if vmatch:
version = vmatch.group(0)
if 'GNU Fortran' in out:
return GnuFortranCompiler([compiler], version, GCC_STANDARD, is_cross, exe_wrap)
if 'G95' in out:
return G95FortranCompiler([compiler], version, is_cross, exe_wrap)
if 'Sun Fortran' in err:
version = 'unknown version'
vmatch = re.search(Environment.version_regex, err)
if vmatch:
version = vmatch.group(0)
return SunFortranCompiler([compiler], version, is_cross, exe_wrap)
if 'ifort (IFORT)' in out:
return IntelFortranCompiler([compiler], version, is_cross, exe_wrap)
if 'PathScale EKOPath(tm)' in err:
return PathScaleFortranCompiler([compiler], version, is_cross, exe_wrap)
if 'pgf90' in out:
return PGIFortranCompiler([compiler], version, is_cross, exe_wrap)
if 'Open64 Compiler Suite' in err:
return Open64FortranCompiler([compiler], version, is_cross, exe_wrap)
if 'NAG Fortran' in err:
return NAGFortranCompiler([compiler], version, is_cross, exe_wrap)
raise EnvironmentException('Unknown compiler(s): "' + ', '.join(compilers) + '"')
def get_scratch_dir(self):
return self.scratch_dir
def get_depfixer(self):
path = os.path.split(__file__)[0]
return os.path.join(path, 'depfixer.py')
def detect_cpp_compiler(self, want_cross):
evar = 'CXX'
if self.is_cross_build() and want_cross:
compilers = [self.cross_info.config['binaries']['cpp']]
ccache = []
is_cross = True
exe_wrap = self.cross_info.config['binaries'].get('exe_wrapper', None)
elif evar in os.environ:
compilers = os.environ[evar].split()
ccache = []
is_cross = False
exe_wrap = None
else:
compilers = self.default_cpp
ccache = self.detect_ccache()
is_cross = False
exe_wrap = None
for compiler in compilers:
basename = os.path.basename(compiler).lower()
if basename == 'cl' or basename == 'cl.exe':
arg = '/?'
else:
arg = '--version'
try:
p = subprocess.Popen([compiler, arg],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except OSError:
continue
(out, err) = p.communicate()
out = out.decode()
err = err.decode()
vmatch = re.search(Environment.version_regex, out)
if vmatch:
version = vmatch.group(0)
else:
version = 'unknown version'
if 'apple' in out and 'Free Software Foundation' in out:
return GnuCPPCompiler(ccache + [compiler], version, GCC_OSX, is_cross, exe_wrap)
if (out.startswith('c++ ') or 'g++' in out or 'GCC' in out) and \
'Free Software Foundation' in out:
return GnuCPPCompiler(ccache + [compiler], version, GCC_STANDARD, is_cross, exe_wrap)
if 'clang' in out:
return ClangCPPCompiler(ccache + [compiler], version, is_cross, exe_wrap)
if 'Microsoft' in out:
version = re.search(Environment.version_regex, err).group()
return VisualStudioCPPCompiler([compiler], version, is_cross, exe_wrap)
raise EnvironmentException('Unknown compiler(s) "' + ', '.join(compilers) + '"')
def detect_objc_compiler(self, want_cross):
if self.is_cross_build() and want_cross:
exelist = [self.cross_info['objc']]
is_cross = True
exe_wrap = self.cross_info.get('exe_wrapper', None)
else:
exelist = self.get_objc_compiler_exelist()
is_cross = False
exe_wrap = None
try:
p = subprocess.Popen(exelist + ['--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
raise EnvironmentException('Could not execute ObjC compiler "%s"' % ' '.join(exelist))
(out, err) = p.communicate()
out = out.decode()
err = err.decode()
vmatch = re.search(Environment.version_regex, out)
if vmatch:
version = vmatch.group(0)
else:
version = 'unknown version'
if (out.startswith('cc ') or 'gcc' in out) and \
'Free Software Foundation' in out:
return GnuObjCCompiler(exelist, version, is_cross, exe_wrap)
if out.startswith('Apple LLVM'):
return ClangObjCCompiler(exelist, version, is_cross, exe_wrap)
if 'apple' in out and 'Free Software Foundation' in out:
return GnuObjCCompiler(exelist, version, is_cross, exe_wrap)
raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
def detect_objcpp_compiler(self, want_cross):
if self.is_cross_build() and want_cross:
exelist = [self.cross_info['objcpp']]
is_cross = True
exe_wrap = self.cross_info.get('exe_wrapper', None)
else:
exelist = self.get_objcpp_compiler_exelist()
is_cross = False
exe_wrap = None
try:
p = subprocess.Popen(exelist + ['--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
raise EnvironmentException('Could not execute ObjC++ compiler "%s"' % ' '.join(exelist))
(out, err) = p.communicate()
out = out.decode()
err = err.decode()
vmatch = re.search(Environment.version_regex, out)
if vmatch:
version = vmatch.group(0)
else:
version = 'unknown version'
if (out.startswith('c++ ') or out.startswith('g++')) and \
'Free Software Foundation' in out:
return GnuObjCPPCompiler(exelist, version, is_cross, exe_wrap)
if out.startswith('Apple LLVM'):
return ClangObjCPPCompiler(exelist, version, is_cross, exe_wrap)
if 'apple' in out and 'Free Software Foundation' in out:
return GnuObjCPPCompiler(exelist, version, is_cross, exe_wrap)
raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
def detect_java_compiler(self):
exelist = ['javac']
try:
p = subprocess.Popen(exelist + ['-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
raise EnvironmentException('Could not execute Java compiler "%s"' % ' '.join(exelist))
(out, err) = p.communicate()
out = out.decode()
err = err.decode()
vmatch = re.search(Environment.version_regex, err)
if vmatch:
version = vmatch.group(0)
else:
version = 'unknown version'
if 'javac' in err:
return JavaCompiler(exelist, version)
raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
def detect_cs_compiler(self):
exelist = ['mcs']
try:
p = subprocess.Popen(exelist + ['--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
raise EnvironmentException('Could not execute C# compiler "%s"' % ' '.join(exelist))
(out, err) = p.communicate()
out = out.decode()
err = err.decode()
vmatch = re.search(Environment.version_regex, out)
if vmatch:
version = vmatch.group(0)
else:
version = 'unknown version'
if 'Mono' in out:
return MonoCompiler(exelist, version)
raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
def detect_vala_compiler(self):
exelist = ['valac']
try:
p = subprocess.Popen(exelist + ['--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
raise EnvironmentException('Could not execute Vala compiler "%s"' % ' '.join(exelist))
(out, _) = p.communicate()
out = out.decode()
vmatch = re.search(Environment.version_regex, out)
if vmatch:
version = vmatch.group(0)
else:
version = 'unknown version'
if 'Vala' in out:
return ValaCompiler(exelist, version)
raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
def detect_rust_compiler(self):
exelist = ['rustc']
try:
p = subprocess.Popen(exelist + ['--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
raise EnvironmentException('Could not execute Rust compiler "%s"' % ' '.join(exelist))
(out, _) = p.communicate()
out = out.decode()
vmatch = re.search(Environment.version_regex, out)
if vmatch:
version = vmatch.group(0)
else:
version = 'unknown version'
if 'rustc' in out:
return RustCompiler(exelist, version)
raise EnvironmentException('Unknown compiler "' + ' '.join(exelist) + '"')
def detect_static_linker(self, compiler):
if compiler.is_cross:
linker = self.cross_info.config['binaries']['ar']
else:
evar = 'AR'
if evar in os.environ:
linker = os.environ[evar].strip()
if isinstance(compiler, VisualStudioCCompiler):
linker= self.vs_static_linker
else:
linker = self.default_static_linker
basename = os.path.basename(linker).lower()
if basename == 'lib' or basename == 'lib.exe':
arg = '/?'
else:
arg = '--version'
try:
p = subprocess.Popen([linker, arg], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
raise EnvironmentException('Could not execute static linker "%s".' % linker)
(out, err) = p.communicate()
out = out.decode()
err = err.decode()
if '/OUT:' in out or '/OUT:' in err:
return VisualStudioLinker([linker])
if p.returncode == 0:
return ArLinker([linker])
if p.returncode == 1 and err.startswith('usage'): # OSX
return ArLinker([linker])
raise EnvironmentException('Unknown static linker "%s"' % linker)
def detect_ccache(self):
try:
has_ccache = subprocess.call(['ccache', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError:
has_ccache = 1
if has_ccache == 0:
cmdlist = ['ccache']
else:
cmdlist = []
return cmdlist
def get_objc_compiler_exelist(self):
ccachelist = self.detect_ccache()
evar = 'OBJCC'
if evar in os.environ:
return os.environ[evar].split()
return ccachelist + self.default_objc
def get_objcpp_compiler_exelist(self):
ccachelist = self.detect_ccache()
evar = 'OBJCXX'
if evar in os.environ:
return os.environ[evar].split()
return ccachelist + self.default_objcpp
def get_source_dir(self):
return self.source_dir
def get_build_dir(self):
return self.build_dir
def get_exe_suffix(self):
return self.exe_suffix
# On Windows the library has suffix dll
# but you link against a file that has suffix lib.
def get_import_lib_suffix(self):
return self.import_lib_suffix
def get_shared_lib_prefix(self):
return self.shared_lib_prefix
def get_shared_lib_suffix(self):
return self.shared_lib_suffix
def get_static_lib_prefix(self):
return self.static_lib_prefix
def get_static_lib_suffix(self):
return self.static_lib_suffix
def get_object_suffix(self):
return self.object_suffix
def get_prefix(self):
return self.coredata.prefix
def get_libdir(self):
return self.coredata.libdir
def get_bindir(self):
return self.coredata.bindir
def get_includedir(self):
return self.coredata.includedir
def get_mandir(self):
return self.coredata.mandir
def get_datadir(self):
return self.coredata.datadir
def find_library(self, libname, dirs):
if dirs is None:
dirs = mesonlib.get_library_dirs()
suffixes = [self.get_shared_lib_suffix(), self.get_static_lib_suffix()]
prefix = self.get_shared_lib_prefix()
for d in dirs:
for suffix in suffixes:
trial = os.path.join(d, prefix + libname + '.' + suffix)
if os.path.isfile(trial):
return trial
def get_args_from_envvars(lang):
if lang == 'c':
compile_args = os.environ.get('CFLAGS', '').split()
link_args = compile_args + os.environ.get('LDFLAGS', '').split()
compile_args += os.environ.get('CPPFLAGS', '').split()
elif lang == 'cpp':
compile_args = os.environ.get('CXXFLAGS', '').split()
link_args = compile_args + os.environ.get('LDFLAGS', '').split()
compile_args += os.environ.get('CPPFLAGS', '').split()
elif lang == 'objc':
compile_args = os.environ.get('OBJCFLAGS', '').split()
link_args = compile_args + os.environ.get('LDFLAGS', '').split()
compile_args += os.environ.get('CPPFLAGS', '').split()
elif lang == 'objcpp':
compile_args = os.environ.get('OBJCXXFLAGS', '').split()
link_args = compile_args + os.environ.get('LDFLAGS', '').split()
compile_args += os.environ.get('CPPFLAGS', '').split()
elif lang == 'fortran':
compile_args = os.environ.get('FFLAGS', '').split()
link_args = compile_args + os.environ.get('LDFLAGS', '').split()
else:
compile_args = []
link_args = []
return (compile_args, link_args)
class CrossBuildInfo():
def __init__(self, filename):
self.config = {}
self.parse_datafile(filename)
if 'target_machine' in self.config:
return
if not 'host_machine' in self.config:
raise coredata.MesonException('Cross info file must have either host or a target machine.')
if not 'properties' in self.config:
raise coredata.MesonException('Cross file is missing "properties".')
if not 'binaries' in self.config:
raise coredata.MesonException('Cross file is missing "binaries".')
def ok_type(self, i):
return isinstance(i, str) or isinstance(i, int) or isinstance(i, bool)
def parse_datafile(self, filename):
config = configparser.ConfigParser()
config.read(filename)
# This is a bit hackish at the moment.
for s in config.sections():
self.config[s] = {}
for entry in config[s]:
value = config[s][entry]
if ' ' in entry or '\t' in entry or "'" in entry or '"' in entry:
raise EnvironmentException('Malformed variable name %s in cross file..' % varname)
try:
res = eval(value, {'true' : True, 'false' : False})
except Exception:
raise EnvironmentException('Malformed value in cross file variable %s.' % varname)
if self.ok_type(res):
self.config[s][entry] = res
elif isinstance(res, list):
for i in res:
if not self.ok_type(i):
raise EnvironmentException('Malformed value in cross file variable %s.' % varname)
self.items[varname] = res
else:
raise EnvironmentException('Malformed value in cross file variable %s.' % varname)
def has_host(self):
return 'host_machine' in self.config
def has_target(self):
return 'target_machine' in self.config
# Wehn compiling a cross compiler we use the native compiler for everything.
# But not when cross compiling a cross compiler.
def need_cross_compiler(self):
return 'host_machine' in self.config
| {
"content_hash": "9b7e999bf94f7ad5dbddc09738b6eecb",
"timestamp": "",
"source": "github",
"line_count": 624,
"max_line_length": 114,
"avg_line_length": 39.56730769230769,
"alnum_prop": 0.5582017010935602,
"repo_name": "amaniak/meson",
"id": "c594776846062965a2baecb35dc5e74a92ad6e68",
"size": "25283",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "environment.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "131"
},
{
"name": "C",
"bytes": "29980"
},
{
"name": "C#",
"bytes": "631"
},
{
"name": "C++",
"bytes": "9798"
},
{
"name": "Emacs Lisp",
"bytes": "1226"
},
{
"name": "FORTRAN",
"bytes": "667"
},
{
"name": "Groff",
"bytes": "175"
},
{
"name": "Inno Setup",
"bytes": "372"
},
{
"name": "Java",
"bytes": "302"
},
{
"name": "Lex",
"bytes": "110"
},
{
"name": "Objective-C",
"bytes": "388"
},
{
"name": "Objective-C++",
"bytes": "87"
},
{
"name": "Protocol Buffer",
"bytes": "46"
},
{
"name": "Python",
"bytes": "574119"
},
{
"name": "Rust",
"bytes": "376"
},
{
"name": "Shell",
"bytes": "2144"
},
{
"name": "Vala",
"bytes": "2730"
},
{
"name": "Yacc",
"bytes": "50"
}
],
"symlink_target": ""
} |
"""Module defining help types and providers for gsutil commands."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import collections
from gslib.exception import CommandException
ALL_HELP_TYPES = ['command_help', 'additional_help']
# Constants enforced by SanityCheck
# Mainly here for help output formatting purposes, can be changed if necessary.
MAX_HELP_NAME_LEN = 17
MIN_ONE_LINE_SUMMARY_LEN = 10
MAX_ONE_LINE_SUMMARY_LEN = 80 - MAX_HELP_NAME_LEN
DESCRIPTION_PREFIX = """
<B>DESCRIPTION</B>"""
SYNOPSIS_PREFIX = """
<B>SYNOPSIS</B>"""
class HelpProvider(object):
"""Interface for providing help."""
# Each subclass of HelpProvider define a property named 'help_spec' that is
# an instance of the following class.
HelpSpec = collections.namedtuple(
'HelpSpec',
[
# Name of command or auxiliary help info for which this help applies.
'help_name',
# List of help name aliases.
'help_name_aliases',
# Type of help.
'help_type',
# One line summary of this help.
'help_one_line_summary',
# The full help text.
'help_text',
# Help text for subcommands of the command's help being specified.
'subcommand_help_text',
])
# Each subclass must override this with an instance of HelpSpec.
help_spec = None
# This is a static helper instead of a class method because the help loader
# (gslib.commands.help._LoadHelpMaps()) operates on classes not instances.
def SanityCheck(help_provider, help_name_map):
"""Helper for checking that a HelpProvider has minimally adequate content."""
# Sanity check the content.
help_name_len = len(help_provider.help_spec.help_name)
assert (help_name_len > 1 and help_name_len < MAX_HELP_NAME_LEN
), 'The help name "{text}" must be less then {max}'.format(
text=help_provider.help_spec.help_name, max=MAX_HELP_NAME_LEN)
for hna in help_provider.help_spec.help_name_aliases:
assert hna
one_line_summary_len = len(help_provider.help_spec.help_one_line_summary)
assert (one_line_summary_len >= MIN_ONE_LINE_SUMMARY_LEN), (
'The one line summary "{text}" with a length of {length} must be ' +
'more then {min} characters').format(
text=help_provider.help_spec.help_one_line_summary,
length=one_line_summary_len,
min=MIN_ONE_LINE_SUMMARY_LEN)
assert (one_line_summary_len <= MAX_ONE_LINE_SUMMARY_LEN), (
'The one line summary "{text}" with a length of {length} must be ' +
'less then {max} characters').format(
text=help_provider.help_spec.help_one_line_summary,
length=one_line_summary_len,
max=MAX_ONE_LINE_SUMMARY_LEN)
assert len(help_provider.help_spec.help_text
) > 10, 'The length of "{text}" must be less then 10'.format(
text=help_provider.help_spec.help_text)
# Ensure there are no dupe help names or aliases across commands.
name_check_list = [help_provider.help_spec.help_name]
name_check_list.extend(help_provider.help_spec.help_name_aliases)
for name_or_alias in name_check_list:
if name_or_alias in help_name_map:
raise CommandException(
'Duplicate help name/alias "%s" found while loading help from %s. '
'That name/alias was already taken by %s' %
(name_or_alias, help_provider.__module__,
help_name_map[name_or_alias].__module__))
def CreateHelpText(synopsis, description):
"""Helper for adding help text headers given synopsis and description."""
return SYNOPSIS_PREFIX + synopsis + DESCRIPTION_PREFIX + description
| {
"content_hash": "2edcbcc9d407e3cc9d2607740e19f058",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 79,
"avg_line_length": 39.765957446808514,
"alnum_prop": 0.6741573033707865,
"repo_name": "endlessm/chromium-browser",
"id": "afe30eb12ce00b14c60a8420288f2b0cab372cc4",
"size": "4358",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "third_party/catapult/third_party/gsutil/gslib/help_provider.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
"""Templates package."""
import pkgutil
from anybadge.exceptions import UnknownBadgeTemplate
def get_template(name: str) -> str:
"""Get a template by name.
Examples:
>>> get_template('default') # doctest: +ELLIPSIS
'<?xml version="1.0" encoding="UTF-8...
"""
try:
data = pkgutil.get_data(__name__, name + ".svg")
except FileNotFoundError as e:
raise UnknownBadgeTemplate from e
if not data:
raise UnknownBadgeTemplate
return data.decode("utf-8")
| {
"content_hash": "9182513ebfd1b13a4c94bd58cb26ff11",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 57,
"avg_line_length": 21.791666666666668,
"alnum_prop": 0.6233269598470363,
"repo_name": "jongracecox/anybadge",
"id": "38e45aa6b9e1fb9a72c099a21140a0947df646dd",
"size": "523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "anybadge/templates/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "588"
},
{
"name": "Python",
"bytes": "78971"
},
{
"name": "Shell",
"bytes": "2838"
}
],
"symlink_target": ""
} |
from swgpy.object import *
def create(kernel):
result = Intangible()
result.template = "object/draft_schematic/space/reverse_engineering/shared_shields_analysis_tool.iff"
result.attribute_template_id = -1
result.stfName("string_id_table","")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result | {
"content_hash": "27e3899d2c2f10308199715c1e8008f0",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 102,
"avg_line_length": 25.46153846153846,
"alnum_prop": 0.7099697885196374,
"repo_name": "anhstudios/swganh",
"id": "abd9bb13211089ba81b7e254e25cd75576c795ac",
"size": "476",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "data/scripts/templates/object/draft_schematic/space/reverse_engineering/shared_shields_analysis_tool.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "11887"
},
{
"name": "C",
"bytes": "7699"
},
{
"name": "C++",
"bytes": "2357839"
},
{
"name": "CMake",
"bytes": "41264"
},
{
"name": "PLSQL",
"bytes": "42065"
},
{
"name": "Python",
"bytes": "7503510"
},
{
"name": "SQLPL",
"bytes": "42770"
}
],
"symlink_target": ""
} |
import pandas as pd
import os
os.chdir("../Module1/")
cwd = os.getcwd()
print(cwd)
# TODO: Load up the 'tutorial.csv' dataset
csv_df = pd.read_csv('tutorial.csv', sep=',')
# TODO: Print the results of the .describe() method
print(csv_df)
print(csv_df.describe())
print(csv_df.info())
print(csv_df.head(3)) # csv_df.iloc[:3, :] OR tail(); default no is 5
print(csv_df.columns) # display the name of the columns
print(csv_df.index)
print(csv_df.dtypes) # what data type Pandas assigned each column
# TODO: Figure out which indexing method you need to use in order to index your dataframe with: [2:4,'col3']:
print(csv_df.loc[2:4, 'col3']) # .ix uses hybrid approach of selecting by column label and column index
| {
"content_hash": "24a5c34d410cf1855ad64d2c5c6f0542",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 109,
"avg_line_length": 32.30434782608695,
"alnum_prop": 0.6823687752355316,
"repo_name": "kHarshit/DAT210x_Microsoft",
"id": "aad29cb6af1d7b08704a26cb185ffd221e99482d",
"size": "743",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Module2/assignment2.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "104580"
}
],
"symlink_target": ""
} |
from django.contrib.auth.models import User
import json
import requests
from readux import __version__
class GithubApiException(Exception):
pass
class GithubAccountNotFound(GithubApiException):
pass
class GithubApi(object):
'''Partial GitHub API access.
Does **NOT** implement the full API, only those portions currently
needed for readux export functionality.'''
url = 'https://api.github.com'
def __init__(self, token):
# initialize a request session that will pass the oauth token
# as an authorization header
self.session = requests.Session()
self.session.headers.update({
'Authorization': 'token %s' % token,
'Accept': 'application/vnd.github.v3+json',
'User-Agent': 'Readux %s / python-requests %s' % \
(__version__, requests.__version__),
})
@staticmethod
def github_account(user):
'''Static method to find a user's GitHub account (current or
linked account via python-social-auth); raises
:class:`GithubAccountNotFound` if none is found.'''
account = user.social_auth.filter(provider='github').first()
if account is None:
raise GithubAccountNotFound
return account
@staticmethod
def github_token(user):
'''Retrieve a GitHub user account's token'''
# TODO: handle no github account, check for appropriate scope
return GithubApi.github_account(user).tokens
@staticmethod
def github_username(user):
'''Retrieve the GitHub username for a linked GitHub social auth
account'''
return GithubApi.github_account(user).extra_data['login']
@classmethod
def connect_as_user(cls, user):
'''Initialize a new GithubApi connection for the specified user.
'''
return cls(cls.github_token(user))
def oauth_scopes(self):
'Get a list of scopes available for the current oauth token'
response = self.session.head('%s/user' % self.url)
if response.status_code == requests.codes.ok:
return response.headers['x-oauth-scopes'].split(',')
def create_repo(self, name, description=None, homepage=None):
'Create a new user repository with the specified name.'
repo_data = {'name': name}
if description:
repo_data['description'] = description
if homepage:
repo_data['homepage'] = homepage
# other options we might care about: homepage url, private/public,
# has_issues, has_wiki, has_downloads, license_template
response = self.session.post('%s/user/repos' % self.url,
data=json.dumps(repo_data))
return response.status_code == requests.codes.created
def list_repos(self, user):
'Get a list of a repositories by user'
# could get current user repos at: /user/repos
# but that includes org repos user has access to
# could specify type, but default of owner is probably fine for now
response = self.session.get('%s/users/%s/repos' % (self.url, user))
if response.status_code == requests.codes.ok:
return response.json()
def list_user_repos(self):
'''Get a list of the current user's repositories'''
response = self.session.get('%s/user/repos' % self.url)
if response.status_code == requests.codes.ok:
repos = response.json()
# repository list is paged; if there is a rel=next link,
# there is more content
while response.links.get('next', None):
# for now, assuming that if the first response is ok
# subsequent ones will be too
response = self.session.get(response.links['next']['url'])
repos.extend(response.json())
return repos
def create_pull_request(self, repo, title, head, base,
text=None):
'''Create a new pull request.
https://developer.github.com/v3/pulls/#create-a-pull-request
:param repo: repository where the pull request will be created,
in owner/repo format
:param title: title of the pull request
:param head: name of the branch with the changes to be pulled in
:param base: name of the branch where changes should will be
pulled into (e.g., master)
:param text: optional text body content for the pull request
'''
# pull request url is /repos/:owner/:repo/pulls
data = {'title': title, 'head': head, 'base': base}
if text is not None:
data['body'] = text
response = self.session.post('%s/repos/%s/pulls' % (self.url, repo),
data=json.dumps(data))
if response.status_code == requests.codes.created:
return response.json()
else:
error_message = 'Error creating pull request'
try:
error_message += ': %s' % response.json()['message']
except Exception:
pass
raise GithubApiException(error_message)
| {
"content_hash": "2b97d7a21257f9c53863fc113f6da907",
"timestamp": "",
"source": "github",
"line_count": 133,
"max_line_length": 76,
"avg_line_length": 38.81954887218045,
"alnum_prop": 0.610110400929692,
"repo_name": "emory-libraries/readux",
"id": "d4730adb67f63435ddc4abc2f9a20d4cab5a60d7",
"size": "5163",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "readux/books/github.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "110298"
},
{
"name": "HTML",
"bytes": "82431"
},
{
"name": "JavaScript",
"bytes": "666176"
},
{
"name": "Python",
"bytes": "553514"
},
{
"name": "XSLT",
"bytes": "13269"
}
],
"symlink_target": ""
} |
class Solution:
# @return a list of lists of string
def solveNQueens(self, n):
self.solutions = []
self.n = n
self.recursiveSolve([], [], [])
drawings = []
for solution in self.solutions:
drawings.append(self.drawSolutions(solution))
return drawings
def drawSolutions(self, solution):
draw = []
for r in range(self.n):
draw.append('.' * solution[r] + 'Q' + '.' * (self.n - 1 - solution[r]))
return draw
def recursiveSolve(self, partial, diag, anti_diag):
idx = len(partial)
if idx == self.n:
self.solutions.append(partial[:])
return
for val in range(self.n):
if val not in partial \
and val - idx not in diag \
and val + idx not in anti_diag:
partial.append(val)
diag.append(val - idx)
anti_diag.append(val + idx)
self.recursiveSolve(partial, diag, anti_diag)
partial.pop()
diag.pop()
anti_diag.pop()
if __name__ == '__main__':
print(Solution().solveNQueens(4))
print(Solution().solveNQueens(8))
| {
"content_hash": "72641d09672e608f7c71d3d787211fe1",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 83,
"avg_line_length": 30.121951219512194,
"alnum_prop": 0.5060728744939271,
"repo_name": "feigaochn/leetcode",
"id": "f6fe54567fd032ae36ecd21ed88edef4e2f81b0a",
"size": "1895",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "p51_n_queens.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "303056"
}
],
"symlink_target": ""
} |
from ..models.Testcase import CodechefTestcase as Testcase
from bs4 import BeautifulSoup
from termicoder.utils.logging import logger
# Many corner cases are being handled in extracting testcases
# maybe we can implement our own parser here instead of using
# beautiful soup. Most type of problems should be extracted
def extract(html):
logger.debug("extract is being called")
soup = BeautifulSoup(html, "html.parser")
testcases = []
pre_tag_elements = soup.find_all('pre')
try:
io = _extract_io(pre_tag_elements)
logger.debug(io)
except BaseException:
logger.error("Extraction of testcase for the problem failed")
return []
if(len(pre_tag_elements) >= 1):
for i in range(len(io[0])):
inp = io[0][i]
ans = io[1][i]
testcases.append(Testcase(inp=inp, ans=ans, code=i))
logger.debug("inp\n" + inp + "\n\n")
logger.debug("ans\n" + ans + "\n\n")
return testcases
else:
logger.error("Extraction of testcase for the problem failed")
def _sanitize(io):
"""
removes ":" "1:" etc if any in front of the io
"""
# trim begining and ending spaces
io = io.strip()
# if Output: Input: etc.
if(io[0] == ":"):
io = io[1:]
# if Output1: Input1: etc
elif(len(io) > 1 and io[1] == ":"):
io = io[2:]
return io.strip()+"\n"
def _extract_io(pre_tag_elements):
"""
extracts all input and output from pre tags and returns as tuple
"""
sample_inputs = []
sample_outputs = []
for sample_io in pre_tag_elements:
# finding heading / previous sibling of pre
sibling = sample_io.previous_sibling
while(not str(sibling).strip()):
sibling = sibling.previous_sibling
# converting sample_io to text
if sibling is None:
sibling = sample_io.parent.previous_sibling
while(not str(sibling).strip()):
sibling = sibling.previous_sibling
iotext = str(sample_io.text)
# standard codechef problems with input and output in same pre tag
# OR sometimes input just above pre tag and output in pretag
if(("input" in iotext.lower() or "input" in str(sibling).lower()) and
"output" in iotext.lower()):
in_index, out_index = iotext.lower().find(
"input"), iotext.lower().find("output")
ki = 1 if (in_index == -1) else 5
sample_input = _sanitize(iotext[in_index+ki: out_index])
sample_output = _sanitize(iotext[out_index + 6:])
if(len(sample_inputs) != len(sample_outputs)):
sample_inputs = []
sample_outputs = []
sample_inputs.append(sample_input)
sample_outputs.append(sample_output)
# problem with input only like challenge problems
# or input and output in separate pre tags
elif("input" in str(sample_io.text).lower() or
"input" in str(sibling).lower()):
in_index = iotext.lower().find("input")
ki = 1 if (in_index == -1) else 5
sample_input = _sanitize(iotext[in_index+ki:])
sample_input = _sanitize(sample_input)
sample_inputs.append(sample_input)
# problem with output only like printing 100! etc
# or input and output in separate pre tags
elif("output" in str(sample_io.text).lower() or
"output" in str(sibling).lower()):
out_index = iotext.lower().find("output")
ko = 1 if (out_index == -1) else 6
sample_output = _sanitize(iotext[out_index+ko:])
sample_output = _sanitize(sample_output)
sample_outputs.append(sample_output)
return sample_inputs, sample_outputs
| {
"content_hash": "6ad08177b155e695765ec4faeb3c510c",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 77,
"avg_line_length": 37.14563106796116,
"alnum_prop": 0.5893883951907998,
"repo_name": "termicoder/termicoder",
"id": "a89b52df4dee469bacf2f7fa084dfc78da821ba1",
"size": "3826",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "termicoder/judges/codechef/utils/testcases.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1748"
},
{
"name": "Python",
"bytes": "99801"
},
{
"name": "Roff",
"bytes": "14761"
}
],
"symlink_target": ""
} |
def Help(inp):
print("sorry this help does not exist.")
| {
"content_hash": "d3a4b934e79368d6de693920bb093b40",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 44,
"avg_line_length": 30,
"alnum_prop": 0.6666666666666666,
"repo_name": "ScratchOs/hungryStack",
"id": "68ce08b9be1495f5f94ad89f3a5519b487983c7d",
"size": "60",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/compilerHelp.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "3637"
}
],
"symlink_target": ""
} |
from flask import render_template
from indico.core.notifications import email_sender, make_email
@email_sender
def notify_request(owner, blocking, blocked_rooms):
"""
Notifies room owner about blockings he has to approve.
Expects only blockings for rooms owned by the specified owner
"""
subject = 'Confirm room blockings'
body = render_template('rb/emails/blockings/awaiting_confirmation_email_to_manager.txt',
owner=owner, blocking=blocking, blocked_rooms=blocked_rooms)
return make_email(owner.email, subject=subject, body=body)
@email_sender
def notify_request_response(blocked_room):
"""
Notifies blocking creator about approval/rejection of his
blocking request for a room
"""
to = blocked_room.blocking.created_by_user.email
verb = blocked_room.State(blocked_room.state).title.upper()
subject = 'Room blocking {}'.format(verb)
body = render_template('rb/emails/blockings/state_email_to_user.txt',
blocking=blocked_room.blocking, blocked_room=blocked_room, verb=verb)
return make_email(to, subject=subject, body=body)
| {
"content_hash": "f6aed755a3616cb1ca1e78b51cd180ca",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 96,
"avg_line_length": 39.55172413793103,
"alnum_prop": 0.7061900610287707,
"repo_name": "OmeGak/indico",
"id": "a8809be56cb4064c19a3a9d4b605af8ed9ef44ac",
"size": "1361",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "indico/modules/rb/notifications/blockings.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "547418"
},
{
"name": "HTML",
"bytes": "1366687"
},
{
"name": "JavaScript",
"bytes": "1678182"
},
{
"name": "Mako",
"bytes": "1340"
},
{
"name": "Python",
"bytes": "4488419"
},
{
"name": "Shell",
"bytes": "2724"
},
{
"name": "TeX",
"bytes": "23051"
},
{
"name": "XSLT",
"bytes": "1504"
}
],
"symlink_target": ""
} |
"""
Reactor-based Services
Here are services to run clients, servers and periodic services using
the reactor.
If you want to run a server service, L{StreamServerEndpointService} defines a
service that can wrap an arbitrary L{IStreamServerEndpoint
<twisted.internet.interfaces.IStreamServerEndpoint>}
as an L{IService}. See also L{twisted.application.strports.service} for
constructing one of these directly from a descriptive string.
Additionally, this module (dynamically) defines various Service subclasses that
let you represent clients and servers in a Service hierarchy. Endpoints APIs
should be preferred for stream server services, but since those APIs do not yet
exist for clients or datagram services, many of these are still useful.
They are as follows::
TCPServer, TCPClient,
UNIXServer, UNIXClient,
SSLServer, SSLClient,
UDPServer,
UNIXDatagramServer, UNIXDatagramClient,
MulticastServer
These classes take arbitrary arguments in their constructors and pass
them straight on to their respective reactor.listenXXX or
reactor.connectXXX calls.
For example, the following service starts a web server on port 8080:
C{TCPServer(8080, server.Site(r))}. See the documentation for the
reactor.listen/connect* methods for more information.
"""
from twisted.python import log
from twisted.python.deprecate import deprecatedModuleAttribute
from twisted.python.versions import Version
from twisted.application import service
from twisted.internet import task
from twisted.internet.defer import CancelledError
def _maybeGlobalReactor(maybeReactor):
"""
@return: the argument, or the global reactor if the argument is C{None}.
"""
if maybeReactor is None:
from twisted.internet import reactor
return reactor
else:
return maybeReactor
class _VolatileDataService(service.Service):
volatile = []
def __getstate__(self):
d = service.Service.__getstate__(self)
for attr in self.volatile:
if attr in d:
del d[attr]
return d
class _AbstractServer(_VolatileDataService):
"""
@cvar volatile: list of attribute to remove from pickling.
@type volatile: C{list}
@ivar method: the type of method to call on the reactor, one of B{TCP},
B{UDP}, B{SSL} or B{UNIX}.
@type method: C{str}
@ivar reactor: the current running reactor.
@type reactor: a provider of C{IReactorTCP}, C{IReactorUDP},
C{IReactorSSL} or C{IReactorUnix}.
@ivar _port: instance of port set when the service is started.
@type _port: a provider of L{twisted.internet.interfaces.IListeningPort}.
"""
volatile = ['_port']
method = None
reactor = None
_port = None
def __init__(self, *args, **kwargs):
self.args = args
if 'reactor' in kwargs:
self.reactor = kwargs.pop("reactor")
self.kwargs = kwargs
def privilegedStartService(self):
service.Service.privilegedStartService(self)
self._port = self._getPort()
def startService(self):
service.Service.startService(self)
if self._port is None:
self._port = self._getPort()
def stopService(self):
service.Service.stopService(self)
# TODO: if startup failed, should shutdown skip stopListening?
# _port won't exist
if self._port is not None:
d = self._port.stopListening()
del self._port
return d
def _getPort(self):
"""
Wrapper around the appropriate listen method of the reactor.
@return: the port object returned by the listen method.
@rtype: an object providing
L{twisted.internet.interfaces.IListeningPort}.
"""
return getattr(_maybeGlobalReactor(self.reactor),
'listen%s' % (self.method,))(*self.args, **self.kwargs)
class _AbstractClient(_VolatileDataService):
"""
@cvar volatile: list of attribute to remove from pickling.
@type volatile: C{list}
@ivar method: the type of method to call on the reactor, one of B{TCP},
B{UDP}, B{SSL} or B{UNIX}.
@type method: C{str}
@ivar reactor: the current running reactor.
@type reactor: a provider of C{IReactorTCP}, C{IReactorUDP},
C{IReactorSSL} or C{IReactorUnix}.
@ivar _connection: instance of connection set when the service is started.
@type _connection: a provider of L{twisted.internet.interfaces.IConnector}.
"""
volatile = ['_connection']
method = None
reactor = None
_connection = None
def __init__(self, *args, **kwargs):
self.args = args
if 'reactor' in kwargs:
self.reactor = kwargs.pop("reactor")
self.kwargs = kwargs
def startService(self):
service.Service.startService(self)
self._connection = self._getConnection()
def stopService(self):
service.Service.stopService(self)
if self._connection is not None:
self._connection.disconnect()
del self._connection
def _getConnection(self):
"""
Wrapper around the appropriate connect method of the reactor.
@return: the port object returned by the connect method.
@rtype: an object providing L{twisted.internet.interfaces.IConnector}.
"""
return getattr(_maybeGlobalReactor(self.reactor),
'connect%s' % (self.method,))(*self.args, **self.kwargs)
_doc={
'Client':
"""Connect to %(tran)s
Call reactor.connect%(tran)s when the service starts, with the
arguments given to the constructor.
""",
'Server':
"""Serve %(tran)s clients
Call reactor.listen%(tran)s when the service starts, with the
arguments given to the constructor. When the service stops,
stop listening. See twisted.internet.interfaces for documentation
on arguments to the reactor method.
""",
}
import types
for tran in 'TCP UNIX SSL UDP UNIXDatagram Multicast'.split():
for side in 'Server Client'.split():
if tran == "Multicast" and side == "Client":
continue
base = globals()['_Abstract'+side]
doc = _doc[side] % vars()
klass = types.ClassType(tran+side, (base,),
{'method': tran, '__doc__': doc})
globals()[tran+side] = klass
deprecatedModuleAttribute(
Version("Twisted", 13, 1, 0),
"It relies upon IReactorUDP.connectUDP "
"which was removed in Twisted 10. "
"Use twisted.application.internet.UDPServer instead.",
"twisted.application.internet", "UDPClient")
class TimerService(_VolatileDataService):
"""
Service to periodically call a function
Every C{step} seconds call the given function with the given arguments.
The service starts the calls when it starts, and cancels them
when it stops.
@ivar clock: Source of time. This defaults to L{None} which is
causes L{twisted.internet.reactor} to be used.
Feel free to set this to something else, but it probably ought to be
set *before* calling L{startService}.
@type clock: L{IReactorTime<twisted.internet.interfaces.IReactorTime>}
@ivar call: Function and arguments to call periodically.
@type call: L{tuple} of C{(callable, args, kwargs)}
"""
volatile = ['_loop', '_loopFinished']
def __init__(self, step, callable, *args, **kwargs):
"""
@param step: The number of seconds between calls.
@type step: L{float}
@param callable: Function to call
@type callable: L{callable}
@param args: Positional arguments to pass to function
@param kwargs: Keyword arguments to pass to function
"""
self.step = step
self.call = (callable, args, kwargs)
self.clock = None
def startService(self):
service.Service.startService(self)
callable, args, kwargs = self.call
# we have to make a new LoopingCall each time we're started, because
# an active LoopingCall remains active when serialized. If
# LoopingCall were a _VolatileDataService, we wouldn't need to do
# this.
self._loop = task.LoopingCall(callable, *args, **kwargs)
self._loop.clock = _maybeGlobalReactor(self.clock)
self._loopFinished = self._loop.start(self.step, now=True)
self._loopFinished.addErrback(self._failed)
def _failed(self, why):
# make a note that the LoopingCall is no longer looping, so we don't
# try to shut it down a second time in stopService. I think this
# should be in LoopingCall. -warner
self._loop.running = False
log.err(why)
def stopService(self):
"""
Stop the service.
@rtype: L{Deferred<defer.Deferred>}
@return: a L{Deferred<defer.Deferred>} which is fired when the
currently running call (if any) is finished.
"""
if self._loop.running:
self._loop.stop()
self._loopFinished.addCallback(lambda _:
service.Service.stopService(self))
return self._loopFinished
class CooperatorService(service.Service):
"""
Simple L{service.IService} which starts and stops a L{twisted.internet.task.Cooperator}.
"""
def __init__(self):
self.coop = task.Cooperator(started=False)
def coiterate(self, iterator):
return self.coop.coiterate(iterator)
def startService(self):
self.coop.start()
def stopService(self):
self.coop.stop()
class StreamServerEndpointService(service.Service, object):
"""
A L{StreamServerEndpointService} is an L{IService} which runs a server on a
listening port described by an L{IStreamServerEndpoint
<twisted.internet.interfaces.IStreamServerEndpoint>}.
@ivar factory: A server factory which will be used to listen on the
endpoint.
@ivar endpoint: An L{IStreamServerEndpoint
<twisted.internet.interfaces.IStreamServerEndpoint>} provider
which will be used to listen when the service starts.
@ivar _waitingForPort: a Deferred, if C{listen} has yet been invoked on the
endpoint, otherwise None.
@ivar _raiseSynchronously: Defines error-handling behavior for the case
where C{listen(...)} raises an exception before C{startService} or
C{privilegedStartService} have completed.
@type _raiseSynchronously: C{bool}
@since: 10.2
"""
_raiseSynchronously = None
def __init__(self, endpoint, factory):
self.endpoint = endpoint
self.factory = factory
self._waitingForPort = None
def privilegedStartService(self):
"""
Start listening on the endpoint.
"""
service.Service.privilegedStartService(self)
self._waitingForPort = self.endpoint.listen(self.factory)
raisedNow = []
def handleIt(err):
if self._raiseSynchronously:
raisedNow.append(err)
elif not err.check(CancelledError):
log.err(err)
self._waitingForPort.addErrback(handleIt)
if raisedNow:
raisedNow[0].raiseException()
def startService(self):
"""
Start listening on the endpoint, unless L{privilegedStartService} got
around to it already.
"""
service.Service.startService(self)
if self._waitingForPort is None:
self.privilegedStartService()
def stopService(self):
"""
Stop listening on the port if it is already listening, otherwise,
cancel the attempt to listen.
@return: a L{Deferred<twisted.internet.defer.Deferred>} which fires
with C{None} when the port has stopped listening.
"""
self._waitingForPort.cancel()
def stopIt(port):
if port is not None:
return port.stopListening()
d = self._waitingForPort.addCallback(stopIt)
def stop(passthrough):
self.running = False
return passthrough
d.addBoth(stop)
return d
__all__ = (['TimerService', 'CooperatorService', 'MulticastServer',
'StreamServerEndpointService'] +
[tran+side
for tran in 'TCP UNIX SSL UDP UNIXDatagram'.split()
for side in 'Server Client'.split()])
| {
"content_hash": "6d5d6d6ae5398e245dde699f16cdfc41",
"timestamp": "",
"source": "github",
"line_count": 402,
"max_line_length": 92,
"avg_line_length": 31.781094527363184,
"alnum_prop": 0.6314182842830307,
"repo_name": "timkrentz/SunTracker",
"id": "cc72dcd54bc6ffe5ffbd1f73adfd6f5741c6bfc6",
"size": "12975",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "IMU/VTK-6.2.0/ThirdParty/Twisted/twisted/application/internet.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "185699"
},
{
"name": "Assembly",
"bytes": "38582"
},
{
"name": "Batchfile",
"bytes": "110"
},
{
"name": "C",
"bytes": "48362836"
},
{
"name": "C++",
"bytes": "70478135"
},
{
"name": "CMake",
"bytes": "1755036"
},
{
"name": "CSS",
"bytes": "147795"
},
{
"name": "Cuda",
"bytes": "30026"
},
{
"name": "D",
"bytes": "2152"
},
{
"name": "GAP",
"bytes": "14495"
},
{
"name": "GLSL",
"bytes": "190912"
},
{
"name": "Groff",
"bytes": "66799"
},
{
"name": "HTML",
"bytes": "295090"
},
{
"name": "Java",
"bytes": "203238"
},
{
"name": "JavaScript",
"bytes": "1146098"
},
{
"name": "Lex",
"bytes": "47145"
},
{
"name": "Makefile",
"bytes": "5461"
},
{
"name": "Objective-C",
"bytes": "74727"
},
{
"name": "Objective-C++",
"bytes": "265817"
},
{
"name": "Pascal",
"bytes": "3407"
},
{
"name": "Perl",
"bytes": "178176"
},
{
"name": "Prolog",
"bytes": "4556"
},
{
"name": "Python",
"bytes": "16497901"
},
{
"name": "Shell",
"bytes": "48835"
},
{
"name": "Smarty",
"bytes": "1368"
},
{
"name": "Tcl",
"bytes": "1955829"
},
{
"name": "Yacc",
"bytes": "180651"
}
],
"symlink_target": ""
} |
from py_paddle import swig_paddle
import util
import numpy as np
import unittest
class TestIVector(unittest.TestCase):
def test_createZero(self):
m = swig_paddle.IVector.createZero(10, False)
self.assertIsNotNone(m)
for i in xrange(10):
self.assertEqual(m[i], 0)
m[i] = i
self.assertEqual(m[i], i)
m = swig_paddle.IVector.createZero(10)
self.assertEqual(m.isGpu(), swig_paddle.isUsingGpu())
self.assertEqual(m.getData(), [0] * 10)
def test_create(self):
m = swig_paddle.IVector.create(range(10), False)
self.assertIsNotNone(m)
for i in xrange(10):
self.assertEqual(m[i], i)
m = swig_paddle.IVector.create(range(10))
self.assertEqual(m.isGpu(), swig_paddle.isUsingGpu())
self.assertEqual(m.getData(), range(10))
def test_cpu_numpy(self):
vec = np.array([1, 3, 4, 65, 78, 1, 4], dtype="int32")
iv = swig_paddle.IVector.createCpuVectorFromNumpy(vec, copy=False)
self.assertEqual(vec.shape[0], int(iv.__len__()))
vec[4] = 832
for i in xrange(len(iv)):
self.assertEqual(vec[i], iv[i])
vec2 = iv.toNumpyArrayInplace()
vec2[1] = 384
for i in xrange(len(iv)):
self.assertEqual(vec[i], iv[i])
self.assertEqual(vec2[i], iv[i])
def test_gpu_numpy(self):
if swig_paddle.isGpuVersion():
vec = swig_paddle.IVector.create(range(0, 10), True)
assert isinstance(vec, swig_paddle.IVector)
self.assertTrue(vec.isGpu())
self.assertEqual(vec.getData(), range(0, 10))
num_arr = vec.copyToNumpyArray()
assert isinstance(num_arr, np.ndarray) # for code hint.
num_arr[4] = 7
self.assertEquals(vec.getData(), range(0, 10))
vec.copyFromNumpyArray(num_arr)
expect_vec = range(0, 10)
expect_vec[4] = 7
self.assertEqual(vec.getData(), expect_vec)
def test_numpy(self):
vec = np.array([1, 3, 4, 65, 78, 1, 4], dtype="int32")
iv = swig_paddle.IVector.createVectorFromNumpy(vec)
self.assertEqual(iv.isGpu(), swig_paddle.isUsingGpu())
self.assertEqual(iv.getData(), list(vec))
class TestVector(unittest.TestCase):
def testCreateZero(self):
v = swig_paddle.Vector.createZero(10, False)
self.assertIsNotNone(v)
for i in xrange(len(v)):
self.assertTrue(util.doubleEqual(v[i], 0))
v[i] = i
self.assertTrue(util.doubleEqual(v[i], i))
v = swig_paddle.Vector.createZero(10)
self.assertEqual(v.isGpu(), swig_paddle.isUsingGpu())
self.assertEqual(v.getData(), [0] * 10)
def testCreate(self):
v = swig_paddle.Vector.create([x / 100.0 for x in xrange(100)], False)
self.assertIsNotNone(v)
for i in xrange(len(v)):
self.assertTrue(util.doubleEqual(v[i], i / 100.0))
self.assertEqual(100, len(v))
v = swig_paddle.Vector.create([x / 100.0 for x in xrange(100)])
self.assertEqual(v.isGpu(), swig_paddle.isUsingGpu())
self.assertEqual(100, len(v))
vdata = v.getData()
for i in xrange(len(v)):
self.assertTrue(util.doubleEqual(vdata[i], i / 100.0))
def testCpuNumpy(self):
numpy_arr = np.array([1.2, 2.3, 3.4, 4.5], dtype="float32")
vec = swig_paddle.Vector.createCpuVectorFromNumpy(numpy_arr, copy=False)
assert isinstance(vec, swig_paddle.Vector)
numpy_arr[0] = 0.1
for n, v in zip(numpy_arr, vec):
self.assertTrue(util.doubleEqual(n, v))
numpy_2 = vec.toNumpyArrayInplace()
vec[0] = 1.3
for x, y in zip(numpy_arr, numpy_2):
self.assertTrue(util.doubleEqual(x, y))
for x, y in zip(numpy_arr, vec):
self.assertTrue(util.doubleEqual(x, y))
numpy_3 = vec.copyToNumpyArray()
numpy_3[0] = 0.4
self.assertTrue(util.doubleEqual(vec[0], 1.3))
self.assertTrue(util.doubleEqual(numpy_3[0], 0.4))
for i in xrange(1, len(numpy_3)):
util.doubleEqual(numpy_3[i], vec[i])
def testNumpy(self):
numpy_arr = np.array([1.2, 2.3, 3.4, 4.5], dtype="float32")
vec = swig_paddle.Vector.createVectorFromNumpy(numpy_arr)
self.assertEqual(vec.isGpu(), swig_paddle.isUsingGpu())
vecData = vec.getData()
for n, v in zip(numpy_arr, vecData):
self.assertTrue(util.doubleEqual(n, v))
def testCopyFromNumpy(self):
vec = swig_paddle.Vector.createZero(1, False)
arr = np.array([1.3, 3.2, 2.4], dtype="float32")
vec.copyFromNumpyArray(arr)
for i in xrange(len(vec)):
self.assertTrue(util.doubleEqual(vec[i], arr[i]))
if __name__ == '__main__':
swig_paddle.initPaddle("--use_gpu=0")
suite = unittest.TestLoader().loadTestsFromTestCase(TestVector)
unittest.TextTestRunner().run(suite)
if swig_paddle.isGpuVersion():
swig_paddle.setUseGpu(True)
unittest.main()
| {
"content_hash": "9886e96a4d6f6db83c787080fc4f9d04",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 80,
"avg_line_length": 36.935251798561154,
"alnum_prop": 0.5895987534086482,
"repo_name": "dayhaha/Paddle",
"id": "1ab095c1d3d0d2c84d2d2f95a03f172b901de209",
"size": "5744",
"binary": false,
"copies": "4",
"ref": "refs/heads/develop",
"path": "paddle/api/test/testVector.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "234502"
},
{
"name": "C++",
"bytes": "2954224"
},
{
"name": "CMake",
"bytes": "115130"
},
{
"name": "CSS",
"bytes": "21642"
},
{
"name": "Cuda",
"bytes": "476992"
},
{
"name": "HTML",
"bytes": "9018"
},
{
"name": "JavaScript",
"bytes": "1025"
},
{
"name": "Perl",
"bytes": "11452"
},
{
"name": "Protocol Buffer",
"bytes": "40879"
},
{
"name": "Python",
"bytes": "1039844"
},
{
"name": "Shell",
"bytes": "72419"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
import json
import os
import requests
from collections import OrderedDict
try:
from urllib import urlencode
except Exception as e:
from urllib.parse import urlencode
def _sort_dictionary(dictionary):
output = OrderedDict()
for key in sorted(dictionary):
output[key] = dictionary[key]
return output
def get_metadata(cluster='euskadi'):
if cluster != 'euskadi':
return []
data_file_path = os.path.join(os.path.dirname(__file__), 'data', 'metadata.json')
with open(data_file_path, 'r') as data_file:
metadata = json.loads(data_file.read())
return metadata
class Client:
endpoint = 'https://www.euskadi.eus/r01hSearchResultWar/r01hPresentationXML.jsp'
def __init__(self, families=None, content_types=None, **kwargs):
"""Initializes the Open Data Euskadi REST API Client.
Check http://opendata.euskadi.eus/contenidos-generales/-/familias-y-tipos-de-contenido-de-euskadi-net/
for the available families and content_types."""
cluster = kwargs.get('cluster', 'euskadi')
families = families or []
content_types = content_types or []
self.cluster, self.families, self.content_types = self.__check_typology(cluster, families, content_types)
self.metadata = [] if cluster != 'euskadi' else self.__get_metadata()
self.search_text = None
self.codified_query_params = {
'tC': [self.cluster],
'tF': self.families,
'tT': self.content_types,
'm': [],
'mA': [],
'cO': [],
'p': [],
'pp': ['r01PageSize.100'],
'o': []
}
@staticmethod
def __check_typology(cluster, families, content_types):
"""Massages the `family` and `content_type` values and returns the values back."""
families = [families] if isinstance(families, str) else families
content_types = [content_types] if isinstance(content_types, str) else content_types
if len(families) > 1 and content_types:
raise ValueError('You can\'t call the API for multiple content_types and multiple families. '
'Possible combinations are: multiple families and no content_types, or multiple '
'content_types for one family.')
return cluster, families, content_types
def __check_metadata(self, metadata):
"""Raises an Exception if a metadata is not valid for the selected family + content_type combo."""
if metadata not in self.metadata:
raise ValueError('Please use a valid metadata: {0}'.format(', '.join(self.metadata)))
return
def __get_metadata(self):
"""Returns a list of valid metadata for the current family + content_type combo.
It also checks if `family` and `content_type` exist in the metadata collection, and raises an
exception if not. Checks are only made against the 'euskadi' cluster.
"""
metadata = get_metadata(self.cluster)
metadata_output = metadata['__euskadi__']
try:
for family in self.families:
metadata_output = metadata_output + metadata[family]
for content_type in self.content_types:
# This will only work if only one family is present
metadata_output = metadata_output + metadata['{0}.{1}'.format(family, content_type)]
except KeyError:
raise ValueError('Please use a valid family + content_type combo.')
metadata_output.sort()
return metadata_output
def __get_codified_query(self):
"""Returns a `r01kQry` compatible codified query."""
blocks = []
for key, value in _sort_dictionary(self.codified_query_params).items():
if value:
blocks.append('{}:{}'.format(key, ','.join(value)))
return ';'.join(blocks)
def filter(self, metadata_array, operator='AND'):
"""Builds the filter that will be used when getting the data.
It needs an array of metadata filters in the format specified by the Open Data Euskadi REST API:
`metadata.OPERATOR.value`. An optional second value can be passed (AND|OR), to determine if the filter
should match all metadata conditions (ALL) or only one of them (OR). If the operator is not valid a
ValueError is raised.
This method also checks if the metadata is valid, comparing it with the metadata collection
for every typology (family + content_type combo). If the metadata is not valid a ValueError is raised.
Usage::
>>> from irekia import Client
>>> c = Client('eventos', 'evento').filter(['eventEndDate.EQ.TODAY'])
<Client>
"""
if operator not in ['AND', 'OR']:
raise ValueError('Please use a valid operator: AND | OR')
op = 'mA' if operator == 'AND' else 'cO'
self.codified_query_params[op] = [metadata_array] if isinstance(metadata_array, str) else metadata_array
for metadata_filter in self.codified_query_params[op]:
self.__check_metadata(metadata_filter.split('.')[0])
return self
def get(self, **kwargs):
"""Returns a requests.Response object for the specified query.
This method should be called after the `filter()` and `order_by()` methods and accepts these **kwargs:
lang: language of the query, 'es' by default
page: page number to request, 1 by default
debug: use True to get a response with extra information for debugging
url_only: use True to get only a URL
Usage::
>>> from irekia import Client
>>> res = Client('eventos', 'evento').filter(['eventEndDate.GTE.TODAY', 'eventTown.EQ.079']).get(lang='eu')
<requests.Response [200]>
"""
language = kwargs.get('lang', 'es')
self.codified_query_params['m'] = ['documentLanguage.EQ.{0}'.format(language)]
query_params = {'r01kLang': language}
# Complete query params for search() or filter() queries
if self.search_text:
query_params.update(_sort_dictionary({
'fullText': self.search_text,
'resultsSource': 'fullText'
}))
else:
query_params.update({'r01kQry': self.__get_codified_query()})
# Complete query params with pagination, if needed
page = int(kwargs.get('page', 1))
if page > 1:
query_params.update(_sort_dictionary({
'r01kPgCmd': 'next',
'r01kSrchSrcId': 'contenidos.inter',
'r01kTgtPg': page
}))
# Set special debug param
if kwargs.get('debug', False):
query_params['r01kDebug'] = 'true'
url = '{}{}{}'.format(self.endpoint, '?', urlencode(_sort_dictionary(query_params)))
if kwargs.get('url_only', False):
return url
return requests.get(url)
def limit(self, limit=100):
"""Sets the number of results that will be shown per page.
Usage::
>>> from irekia import Client
>>> c = Client('eventos', 'evento').limit(30)
<Client>
"""
self.codified_query_params['pp'] = ['r01PageSize.{0}'.format(limit)]
return self
def order_by(self, *args):
"""Sets an order for the query from metadata *args.
A `DESC` order can be specified adding a min sign (-) to the metadata name: '-eventStartDate'.
Usage::
>>> from irekia import Client
>>> c = Client('eventos', 'evento').order_by('eventTown', '-eventStartDate')
<Client>
"""
for arg in args:
order = '.'.join([arg[1:], 'DESC']) if arg.startswith('-') else '.'.join([arg, 'ASC'])
self.__check_metadata(order.split('.')[0])
self.codified_query_params['o'].append(order)
return self
def search(self, search_text):
"""Builds a full text query.
Usage::
>>> from irekia import Client
>>> c = Client().search('OpenData')
<Client>
"""
self.search_text = search_text
return self
| {
"content_hash": "a5294c0432c2ee51c41f98e232f10356",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 115,
"avg_line_length": 36.31004366812227,
"alnum_prop": 0.5962717979555021,
"repo_name": "eillarra/irekia",
"id": "46a69ea08498e10f7f891038118a47f4a76c0b41",
"size": "8315",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "irekia/client.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "14716"
}
],
"symlink_target": ""
} |
import cv2
import numpy as np
import sys
# this script will find lines and circles in an image
# constrained to find medium-sized circles (for bike wheels)
# and near-vertical lines for identifying buses
# to invoke:
# python /path/to/hough_opencv.py /path/to/input_image.jpg
# there are several python packages that need to be installed
# follow instructions in
# http://docs.opencv.org/doc/tutorials/introduction/windows_install/windows_install.html
# code adapted from
# http://www.janeriksolem.net/2012/08/reading-gauges-detecting-lines-and.html
# load grayscale image
im = cv2.imread(sys.argv[1])
gray_im = cv2.cvtColor(im, cv2.COLOR_RGB2GRAY)
# create version to draw on and blurred version
draw_im = cv2.cvtColor(gray_im, cv2.COLOR_GRAY2BGR)
blur = cv2.GaussianBlur(gray_im, (0,0), 5)
m,n = gray_im.shape
# Hough transform for circles
circles = cv2.HoughCircles(gray_im, cv2.cv.CV_HOUGH_GRADIENT, .25, 150,
np.array([]), 40, 20, minRadius=50,maxRadius=200)[0]
# Hough transform for lines (regular and probabilistic)
edges = cv2.Canny(blur, 20, 60)
lines = cv2.HoughLines(edges, 2, np.pi/90, 40)[0]
plines = cv2.HoughLinesP(edges, 1, np.pi/180, 20, np.array([]), 10, 400)[0]
# draw
for c in circles[:25]:
# green for circles
cv2.circle(draw_im, (c[0],c[1]), c[2], (0,255,0), 2)
for (rho, theta) in lines[:500]:
# blue for infinite lines
boundary = 5 * np.pi / 180 # only vertical lines (+/- 5 degrees)
if theta > boundary and theta < ( np.pi - boundary ):
continue
x0 = np.cos(theta)*rho
y0 = np.sin(theta)*rho
pt1 = ( int(x0 + (m+n)*(-np.sin(theta))), int(y0 + (m+n)*np.cos(theta)) )
pt2 = ( int(x0 - (m+n)*(-np.sin(theta))), int(y0 - (m+n)*np.cos(theta)) )
cv2.line(draw_im, pt1, pt2, (255,0,0), 2)
for l in plines[:25]:
# red for line segments
cv2.line(draw_im, (l[0],l[1]), (l[2],l[3]), (0,0,255), 2)
cv2.imshow("output",draw_im)
cv2.waitKey()
# save the resulting image
cv2.imwrite("output.jpg",draw_im)
| {
"content_hash": "81b5dad31c79c2a13b21a74f581859ab",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 88,
"avg_line_length": 29.82089552238806,
"alnum_prop": 0.6676676676676677,
"repo_name": "mgolub2/bikeraxx",
"id": "45c89597582bae5bd21dbe34202cf01e3725d76e",
"size": "1998",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "compVis/hough_opencv.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "100"
},
{
"name": "C#",
"bytes": "5286"
},
{
"name": "CSS",
"bytes": "258"
},
{
"name": "HTML",
"bytes": "4717"
},
{
"name": "PowerShell",
"bytes": "37644"
},
{
"name": "Python",
"bytes": "5745"
},
{
"name": "Shell",
"bytes": "236"
}
],
"symlink_target": ""
} |
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import swagger_fuzzer
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Swagger Fuzzer'
copyright = u'2016, Boris Feld'
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = swagger_fuzzer.__version__
# The full version, including alpha/beta/rc tags.
release = swagger_fuzzer.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a <link> tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'swagger_fuzzerdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'swagger_fuzzer.tex',
u'Swagger Fuzzer Documentation',
u'Boris Feld', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'swagger_fuzzer',
u'Swagger Fuzzer Documentation',
[u'Boris Feld'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'swagger_fuzzer',
u'Swagger Fuzzer Documentation',
u'Boris Feld',
'swagger_fuzzer',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| {
"content_hash": "5d23ee875defff75123d61ba4ee7b676",
"timestamp": "",
"source": "github",
"line_count": 260,
"max_line_length": 76,
"avg_line_length": 30.85,
"alnum_prop": 0.7032788929061214,
"repo_name": "Lothiraldan/swagger-fuzzer",
"id": "e5dd32ac25cc508204cf8548bb1c4174eb76d037",
"size": "8470",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/conf.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "2109"
},
{
"name": "Python",
"bytes": "15437"
}
],
"symlink_target": ""
} |
"""Settings for adding noise to the action and measurements."""
import numpy as np
from numpy import random
from fusion_tcv import tcv_common
class Noise:
"""Class for adding noise to the action and measurements."""
def __init__(self,
action_mean=None,
action_std=None,
measurements_mean=None,
measurements_std=None,
seed=None):
"""Initializes the class.
Args:
action_mean: mean of the Gaussian noise (action bias).
action_std: std of the Gaussian action noise.
measurements_mean: mean of the Gaussian noise (measurement bias).
measurements_std: Dictionary mapping the tcv measurement names to noise.
seed: seed for the random number generator. If none seed is unset.
"""
# Check all of the shapes are present and correct.
assert action_std.shape == (tcv_common.NUM_ACTIONS,)
assert action_mean.shape == (tcv_common.NUM_ACTIONS,)
for name, num in tcv_common.TCV_MEASUREMENTS.items():
assert name in measurements_std
assert measurements_mean[name].shape == (num,)
assert measurements_std[name].shape == (num,)
self._action_mean = action_mean
self._action_std = action_std
self._meas_mean = measurements_mean
self._meas_std = measurements_std
self._meas_mean_vec = tcv_common.dict_to_measurement(self._meas_mean)
self._meas_std_vec = tcv_common.dict_to_measurement(self._meas_std)
self._gen = random.RandomState(seed)
@classmethod
def use_zero_noise(cls):
no_noise_mean = dict()
no_noise_std = dict()
for name, num in tcv_common.TCV_MEASUREMENTS.items():
no_noise_mean[name] = np.zeros((num,))
no_noise_std[name] = np.zeros((num,))
return cls(
action_mean=np.zeros((tcv_common.NUM_ACTIONS)),
action_std=np.zeros((tcv_common.NUM_ACTIONS)),
measurements_mean=no_noise_mean,
measurements_std=no_noise_std)
@classmethod
def use_default_noise(cls, scale=1):
"""Returns the default observation noise parameters."""
# There is no noise added to the actions, because the noise should be added
# to the action after/as part of the power supply model as opposed to the
# input to the power supply model.
action_noise_mean = np.zeros((tcv_common.NUM_ACTIONS))
action_noise_std = np.zeros((tcv_common.NUM_ACTIONS))
meas_noise_mean = dict()
for key, l in tcv_common.TCV_MEASUREMENTS.items():
meas_noise_mean[key] = np.zeros((l,))
meas_noise_std = dict(
clint_vloop=np.array([0]),
clint_rvloop=np.array([scale * 1e-4] * 37),
bm=np.array([scale * 1e-4] * 38),
IE=np.array([scale * 20] * 8),
IF=np.array([scale * 5] * 8),
IOH=np.array([scale * 20] *2),
Bdot=np.array([scale * 0.05] * 20),
DIOH=np.array([scale * 30]),
FIR_FRINGE=np.array([0]),
IG=np.array([scale * 2.5]),
ONEMM=np.array([0]),
vloop=np.array([scale * 0.3]),
IPHI=np.array([0]),
)
return cls(
action_mean=action_noise_mean,
action_std=action_noise_std,
measurements_mean=meas_noise_mean,
measurements_std=meas_noise_std)
def add_action_noise(self, action):
errs = self._gen.normal(size=action.shape,
loc=self._action_mean,
scale=self._action_std)
return action + errs
def add_measurement_noise(self, measurement_vec):
errs = self._gen.normal(size=measurement_vec.shape,
loc=self._meas_mean_vec,
scale=self._meas_std_vec)
# Make the IOH measurements consistent. The "real" measurements are IOH
# and DIOH, so use those.
errs = tcv_common.measurements_to_dict(errs)
errs["IOH"][1] = errs["IOH"][0] + errs["DIOH"][0]
errs = tcv_common.dict_to_measurement(errs)
return measurement_vec + errs
| {
"content_hash": "8e12f87ac8088f82e70b4678ab4b6c3b",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 79,
"avg_line_length": 37.88461538461539,
"alnum_prop": 0.6210659898477158,
"repo_name": "deepmind/deepmind-research",
"id": "c8363d75f08fe052053bdd9b4466aa425755b469",
"size": "4535",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fusion_tcv/noise.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1002"
},
{
"name": "C++",
"bytes": "5765"
},
{
"name": "Jupyter Notebook",
"bytes": "12330730"
},
{
"name": "Lua",
"bytes": "76186"
},
{
"name": "OpenEdge ABL",
"bytes": "15630"
},
{
"name": "PureBasic",
"bytes": "8"
},
{
"name": "Python",
"bytes": "3419119"
},
{
"name": "Racket",
"bytes": "226692"
},
{
"name": "Shell",
"bytes": "84450"
},
{
"name": "Starlark",
"bytes": "3463"
}
],
"symlink_target": ""
} |
from django.contrib import admin
from basic.music.models import *
class GenreAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Genre, GenreAdmin)
class LabelAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Label, LabelAdmin)
class BandAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Band, BandAdmin)
class AlbumAdmin(admin.ModelAdmin):
list_display = ('title', 'band',)
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Album, AlbumAdmin)
class TrackAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Track, TrackAdmin) | {
"content_hash": "dd1983435a3d49f7183831f4579c3e13",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 46,
"avg_line_length": 22,
"alnum_prop": 0.7107438016528925,
"repo_name": "blampe/M2M",
"id": "90e436f6230567720cb6da2ce42c1eb32539733a",
"size": "726",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "basic/music/admin.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "754736"
},
{
"name": "Java",
"bytes": "6333"
},
{
"name": "JavaScript",
"bytes": "21268"
},
{
"name": "PHP",
"bytes": "18"
},
{
"name": "Python",
"bytes": "6374305"
},
{
"name": "Shell",
"bytes": "4721"
}
],
"symlink_target": ""
} |
"""
flaskbb.forum.views
~~~~~~~~~~~~~~~~~~~~
This module handles the forum logic like creating and viewing
topics and posts.
:copyright: (c) 2014 by the FlaskBB Team.
:license: BSD, see LICENSE for more details.
"""
import datetime
from flask import (Blueprint, redirect, url_for, current_app,
request, flash, jsonify)
from flask_login import login_required, current_user
from flask_babelex import gettext as _
from flaskbb.extensions import db
from flaskbb.utils.settings import flaskbb_config
from flaskbb.utils.helpers import (get_online_users, time_diff, format_quote,
render_template, do_topic_action)
from flaskbb.utils.permissions import (can_post_reply, can_post_topic,
can_delete_topic, can_delete_post,
can_edit_post, can_moderate)
from flaskbb.forum.models import (Category, Forum, Topic, Post, ForumsRead,
TopicsRead)
from flaskbb.forum.forms import (QuickreplyForm, ReplyForm, NewTopicForm,
ReportForm, UserSearchForm, SearchPageForm)
from flaskbb.user.models import User
forum = Blueprint("forum", __name__)
@forum.route("/")
def index():
categories = Category.get_all(user=current_user)
# Fetch a few stats about the forum
user_count = User.query.count()
topic_count = Topic.query.count()
post_count = Post.query.count()
newest_user = User.query.order_by(User.id.desc()).first()
# Check if we use redis or not
if not current_app.config["REDIS_ENABLED"]:
online_users = User.query.filter(User.lastseen >= time_diff()).count()
# Because we do not have server side sessions, we cannot check if there
# are online guests
online_guests = None
else:
online_users = len(get_online_users())
online_guests = len(get_online_users(guest=True))
return render_template("forum/index.html",
categories=categories,
user_count=user_count,
topic_count=topic_count,
post_count=post_count,
newest_user=newest_user,
online_users=online_users,
online_guests=online_guests)
@forum.route("/category/<int:category_id>")
@forum.route("/category/<int:category_id>-<slug>")
def view_category(category_id, slug=None):
category, forums = Category.\
get_forums(category_id=category_id, user=current_user)
return render_template("forum/category.html", forums=forums,
category=category)
@forum.route("/forum/<int:forum_id>")
@forum.route("/forum/<int:forum_id>-<slug>")
def view_forum(forum_id, slug=None):
page = request.args.get('page', 1, type=int)
forum_instance, forumsread = Forum.get_forum(forum_id=forum_id,
user=current_user)
if forum_instance.external:
return redirect(forum_instance.external)
topics = Forum.get_topics(
forum_id=forum_instance.id, user=current_user, page=page,
per_page=flaskbb_config["TOPICS_PER_PAGE"]
)
return render_template(
"forum/forum.html", forum=forum_instance,
topics=topics, forumsread=forumsread,
)
@forum.route("/topic/<int:topic_id>", methods=["POST", "GET"])
@forum.route("/topic/<int:topic_id>-<slug>", methods=["POST", "GET"])
def view_topic(topic_id, slug=None):
page = request.args.get('page', 1, type=int)
# Fetch some information about the topic
topic = Topic.get_topic(topic_id=topic_id, user=current_user)
# Count the topic views
topic.views += 1
topic.save()
# fetch the posts in the topic
posts = Post.query.\
join(User, Post.user_id == User.id).\
filter(Post.topic_id == topic.id).\
add_entity(User).\
order_by(Post.id.asc()).\
paginate(page, flaskbb_config['POSTS_PER_PAGE'], False)
# Update the topicsread status if the user hasn't read it
forumsread = None
if current_user.is_authenticated():
forumsread = ForumsRead.query.\
filter_by(user_id=current_user.id,
forum_id=topic.forum.id).first()
topic.update_read(current_user, topic.forum, forumsread)
form = None
if can_post_reply(user=current_user, topic=topic):
form = QuickreplyForm()
if form.validate_on_submit():
post = form.save(current_user, topic)
return view_post(post.id)
return render_template("forum/topic.html", topic=topic, posts=posts,
last_seen=time_diff(), form=form)
@forum.route("/post/<int:post_id>")
def view_post(post_id):
post = Post.query.filter_by(id=post_id).first_or_404()
count = post.topic.post_count
page = count / flaskbb_config["POSTS_PER_PAGE"]
if count > flaskbb_config["POSTS_PER_PAGE"]:
page += 1
else:
page = 1
return redirect(post.topic.url + "?page=%d#pid%s" % (page, post.id))
@forum.route("/<int:forum_id>/topic/new", methods=["POST", "GET"])
@forum.route("/<int:forum_id>-<slug>/topic/new", methods=["POST", "GET"])
@login_required
def new_topic(forum_id, slug=None):
forum_instance = Forum.query.filter_by(id=forum_id).first_or_404()
if not can_post_topic(user=current_user, forum=forum_instance):
flash(_("You do not have the permissions to create a new topic."),
"danger")
return redirect(forum.url)
form = NewTopicForm()
if request.method == "POST":
if "preview" in request.form and form.validate():
return render_template(
"forum/new_topic.html", forum=forum_instance,
form=form, preview=form.content.data
)
if "submit" in request.form and form.validate():
topic = form.save(current_user, forum_instance)
# redirect to the new topic
return redirect(url_for('forum.view_topic', topic_id=topic.id))
return render_template(
"forum/new_topic.html", forum=forum_instance, form=form
)
@forum.route("/topic/<int:topic_id>/delete", methods=["POST"])
@forum.route("/topic/<int:topic_id>-<slug>/delete", methods=["POST"])
@login_required
def delete_topic(topic_id=None, slug=None):
topic = Topic.query.filter_by(id=topic_id).first_or_404()
if not can_delete_topic(user=current_user, topic=topic):
flash(_("You do not have the permissions to delete this topic."),
"danger")
return redirect(topic.forum.url)
involved_users = User.query.filter(Post.topic_id == topic.id,
User.id == Post.user_id).all()
topic.delete(users=involved_users)
return redirect(url_for("forum.view_forum", forum_id=topic.forum_id))
@forum.route("/topic/<int:topic_id>/lock", methods=["POST"])
@forum.route("/topic/<int:topic_id>-<slug>/lock", methods=["POST"])
@login_required
def lock_topic(topic_id=None, slug=None):
topic = Topic.query.filter_by(id=topic_id).first_or_404()
if not can_moderate(user=current_user, forum=topic.forum):
flash(_("You do not have the permissions to lock this topic."),
"danger")
return redirect(topic.url)
topic.locked = True
topic.save()
return redirect(topic.url)
@forum.route("/topic/<int:topic_id>/unlock", methods=["POST"])
@forum.route("/topic/<int:topic_id>-<slug>/unlock", methods=["POST"])
@login_required
def unlock_topic(topic_id=None, slug=None):
topic = Topic.query.filter_by(id=topic_id).first_or_404()
if not can_moderate(user=current_user, forum=topic.forum):
flash(_("You do not have the permissions to unlock this topic."),
"danger")
return redirect(topic.url)
topic.locked = False
topic.save()
return redirect(topic.url)
@forum.route("/topic/<int:topic_id>/highlight", methods=["POST"])
@forum.route("/topic/<int:topic_id>-<slug>/highlight", methods=["POST"])
@login_required
def highlight_topic(topic_id=None, slug=None):
topic = Topic.query.filter_by(id=topic_id).first_or_404()
if not can_moderate(user=current_user, forum=topic.forum):
flash(_("You do not have the permissions to highlight this topic."),
"danger")
return redirect(topic.url)
topic.important = True
topic.save()
return redirect(topic.url)
@forum.route("/topic/<int:topic_id>/trivialize", methods=["POST"])
@forum.route("/topic/<int:topic_id>-<slug>/trivialize", methods=["POST"])
@login_required
def trivialize_topic(topic_id=None, slug=None):
topic = Topic.query.filter_by(id=topic_id).first_or_404()
# Unlock is basically the same as lock
if not can_moderate(user=current_user, forum=topic.forum):
flash(_("You do not have the permissions to trivialize this topic."),
"danger")
return redirect(topic.url)
topic.important = False
topic.save()
return redirect(topic.url)
@forum.route("/forum/<int:forum_id>/edit", methods=["POST", "GET"])
@forum.route("/forum/<int:forum_id>-<slug>/edit", methods=["POST", "GET"])
@login_required
def manage_forum(forum_id, slug=None):
page = request.args.get('page', 1, type=int)
forum_instance, forumsread = Forum.get_forum(forum_id=forum_id,
user=current_user)
# remove the current forum from the select field (move).
available_forums = Forum.query.order_by(Forum.position).all()
available_forums.remove(forum_instance)
if not can_moderate(current_user, forum=forum_instance):
flash(_("You do not have the permissions to moderate this forum."),
"danger")
return redirect(forum_instance.url)
if forum_instance.external:
return redirect(forum_instance.external)
topics = Forum.get_topics(
forum_id=forum_instance.id, user=current_user, page=page,
per_page=flaskbb_config["TOPICS_PER_PAGE"]
)
mod_forum_url = url_for("forum.manage_forum", forum_id=forum_instance.id,
slug=forum_instance.slug)
# the code is kind of the same here but it somehow still looks cleaner than
# doin some magic
if request.method == "POST":
ids = request.form.getlist("rowid")
tmp_topics = Topic.query.filter(Topic.id.in_(ids)).all()
# locking/unlocking
if "lock" in request.form:
changed = do_topic_action(topics=tmp_topics, user=current_user,
action="locked", reverse=False)
flash(_("%(count)s Topics locked.", count=changed), "success")
return redirect(mod_forum_url)
elif "unlock" in request.form:
changed = do_topic_action(topics=tmp_topics, user=current_user,
action="locked", reverse=True)
flash(_("%(count)s Topics unlocked.", count=changed), "success")
return redirect(mod_forum_url)
# highlighting/trivializing
elif "highlight" in request.form:
changed = do_topic_action(topics=tmp_topics, user=current_user,
action="important", reverse=False)
flash(_("%(count)s Topics highlighted.", count=changed), "success")
return redirect(mod_forum_url)
elif "trivialize" in request.form:
changed = do_topic_action(topics=tmp_topics, user=current_user,
action="important", reverse=True)
flash(_("%(count)s Topics trivialized.", count=changed), "success")
return redirect(mod_forum_url)
# deleting
elif "delete" in request.form:
changed = do_topic_action(topics=tmp_topics, user=current_user,
action="delete", reverse=False)
flash(_("%(count)s Topics deleted.", count=changed), "success")
return redirect(mod_forum_url)
# moving
elif "move" in request.form:
new_forum_id = request.form.get("forum")
if not new_forum_id:
flash(_("Please choose a new forum for the topics."), "info")
return redirect(mod_forum_url)
new_forum = Forum.query.filter_by(id=new_forum_id).first_or_404()
# check the permission in the current forum and in the new forum
if not can_moderate(current_user, forum_instance) or \
not can_moderate(current_user, new_forum):
flash(_("You do not have the permissions to move this topic."),
"danger")
return redirect(mod_forum_url)
new_forum.move_topics_to(tmp_topics)
return redirect(mod_forum_url)
return render_template(
"forum/edit_forum.html", forum=forum_instance, topics=topics,
available_forums=available_forums, forumsread=forumsread,
)
@forum.route("/topic/<int:topic_id>/post/new", methods=["POST", "GET"])
@forum.route("/topic/<int:topic_id>-<slug>/post/new", methods=["POST", "GET"])
@login_required
def new_post(topic_id, slug=None):
topic = Topic.query.filter_by(id=topic_id).first_or_404()
if not can_post_reply(user=current_user, topic=topic):
flash(_("You do not have the permissions to post in this topic."),
"danger")
return redirect(topic.forum.url)
form = ReplyForm()
if form.validate_on_submit():
if "preview" in request.form:
return render_template(
"forum/new_post.html", topic=topic,
form=form, preview=form.content.data
)
else:
post = form.save(current_user, topic)
return view_post(post.id)
return render_template("forum/new_post.html", topic=topic, form=form)
@forum.route(
"/topic/<int:topic_id>/post/<int:post_id>/reply", methods=["POST", "GET"]
)
@login_required
def reply_post(topic_id, post_id):
topic = Topic.query.filter_by(id=topic_id).first_or_404()
post = Post.query.filter_by(id=post_id).first_or_404()
if not can_post_reply(user=current_user, topic=topic):
flash(_("You do not have the permissions to post in this topic."),
"danger")
return redirect(topic.forum.url)
form = ReplyForm()
if form.validate_on_submit():
if "preview" in request.form:
return render_template(
"forum/new_post.html", topic=topic,
form=form, preview=form.content.data
)
else:
form.save(current_user, topic)
return redirect(post.topic.url)
else:
form.content.data = format_quote(post.username, post.content)
return render_template("forum/new_post.html", topic=post.topic, form=form)
@forum.route("/post/<int:post_id>/edit", methods=["POST", "GET"])
@login_required
def edit_post(post_id):
post = Post.query.filter_by(id=post_id).first_or_404()
if not can_edit_post(user=current_user, post=post):
flash(_("You do not have the permissions to edit this post."),
"danger")
return redirect(post.topic.url)
form = ReplyForm()
if form.validate_on_submit():
if "preview" in request.form:
return render_template(
"forum/new_post.html", topic=post.topic,
form=form, preview=form.content.data
)
else:
form.populate_obj(post)
post.date_modified = datetime.datetime.utcnow()
post.modified_by = current_user.username
post.save()
return redirect(post.topic.url)
else:
form.content.data = post.content
return render_template("forum/new_post.html", topic=post.topic, form=form)
@forum.route("/post/<int:post_id>/delete", methods=["POST"])
@login_required
def delete_post(post_id):
post = Post.query.filter_by(id=post_id).first_or_404()
# TODO: Bulk delete
if not can_delete_post(user=current_user, post=post):
flash(_("You do not have the permissions to delete this post."),
"danger")
return redirect(post.topic.url)
first_post = post.first_post
topic_url = post.topic.url
forum_url = post.topic.forum.url
post.delete()
# If the post was the first post in the topic, redirect to the forums
if first_post:
return redirect(forum_url)
return redirect(topic_url)
@forum.route("/post/<int:post_id>/report", methods=["GET", "POST"])
@login_required
def report_post(post_id):
post = Post.query.filter_by(id=post_id).first_or_404()
form = ReportForm()
if form.validate_on_submit():
form.save(current_user, post)
flash(_("Thanks for reporting."), "success")
return render_template("forum/report_post.html", form=form)
@forum.route("/post/<int:post_id>/raw", methods=["POST", "GET"])
@login_required
def raw_post(post_id):
post = Post.query.filter_by(id=post_id).first_or_404()
return format_quote(username=post.username, content=post.content)
@forum.route("/<int:forum_id>/markread", methods=["POST"])
@forum.route("/<int:forum_id>-<slug>/markread", methods=["POST"])
@login_required
def markread(forum_id=None, slug=None):
# Mark a single forum as read
if forum_id:
forum_instance = Forum.query.filter_by(id=forum_id).first_or_404()
forumsread = ForumsRead.query.filter_by(
user_id=current_user.id, forum_id=forum_instance.id
).first()
TopicsRead.query.filter_by(user_id=current_user.id,
forum_id=forum_instance.id).delete()
if not forumsread:
forumsread = ForumsRead()
forumsread.user_id = current_user.id
forumsread.forum_id = forum_instance.id
forumsread.last_read = datetime.datetime.utcnow()
forumsread.cleared = datetime.datetime.utcnow()
db.session.add(forumsread)
db.session.commit()
flash(_("Forum %(forum)s marked as read.", forum=forum_instance.title),
"success")
return redirect(forum_instance.url)
# Mark all forums as read
ForumsRead.query.filter_by(user_id=current_user.id).delete()
TopicsRead.query.filter_by(user_id=current_user.id).delete()
forums = Forum.query.all()
forumsread_list = []
for forum_instance in forums:
forumsread = ForumsRead()
forumsread.user_id = current_user.id
forumsread.forum_id = forum_instance.id
forumsread.last_read = datetime.datetime.utcnow()
forumsread.cleared = datetime.datetime.utcnow()
forumsread_list.append(forumsread)
db.session.add_all(forumsread_list)
db.session.commit()
flash(_("All forums marked as read."), "success")
return redirect(url_for("forum.index"))
@forum.route("/who-is-online")
def who_is_online():
if current_app.config['REDIS_ENABLED']:
online_users = get_online_users()
else:
online_users = User.query.filter(User.lastseen >= time_diff()).all()
return render_template("forum/online_users.html",
online_users=online_users)
@forum.route("/memberlist", methods=['GET', 'POST'])
def memberlist():
page = request.args.get('page', 1, type=int)
search_form = UserSearchForm()
if search_form.validate():
users = search_form.get_results().\
paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template("forum/memberlist.html", users=users,
search_form=search_form)
else:
users = User.query.\
paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template("forum/memberlist.html", users=users,
search_form=search_form)
@forum.route("/topictracker")
@login_required
def topictracker():
page = request.args.get("page", 1, type=int)
topics = current_user.tracked_topics.\
outerjoin(TopicsRead,
db.and_(TopicsRead.topic_id == Topic.id,
TopicsRead.user_id == current_user.id)).\
add_entity(TopicsRead).\
order_by(Topic.last_updated.desc()).\
paginate(page, flaskbb_config['TOPICS_PER_PAGE'], True)
return render_template("forum/topictracker.html", topics=topics)
@forum.route("/topictracker/<int:topic_id>/add", methods=["POST"])
@forum.route("/topictracker/<int:topic_id>-<slug>/add", methods=["POST"])
@login_required
def track_topic(topic_id, slug=None):
topic = Topic.query.filter_by(id=topic_id).first_or_404()
current_user.track_topic(topic)
current_user.save()
return redirect(topic.url)
@forum.route("/topictracker/<int:topic_id>/delete", methods=["POST"])
@forum.route("/topictracker/<int:topic_id>-<slug>/delete", methods=["POST"])
@login_required
def untrack_topic(topic_id, slug=None):
topic = Topic.query.filter_by(id=topic_id).first_or_404()
current_user.untrack_topic(topic)
current_user.save()
return redirect(topic.url)
@forum.route("/search", methods=['GET', 'POST'])
def search():
form = SearchPageForm()
if form.validate_on_submit():
result = form.get_results()
return render_template('forum/search_result.html', form=form,
result=result)
return render_template('forum/search_form.html', form=form)
| {
"content_hash": "ad72c30c08ec88a2e59c9a9d177ecc46",
"timestamp": "",
"source": "github",
"line_count": 605,
"max_line_length": 79,
"avg_line_length": 35.67768595041322,
"alnum_prop": 0.6164466064396572,
"repo_name": "lucius-feng/flaskbb",
"id": "081ec2c281338448fde883026c4a088b51a2bb29",
"size": "21609",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "flaskbb/forum/views.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "10337"
},
{
"name": "HTML",
"bytes": "161501"
},
{
"name": "JavaScript",
"bytes": "33042"
},
{
"name": "Makefile",
"bytes": "537"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Python",
"bytes": "300002"
}
],
"symlink_target": ""
} |
import sys
sys.path.insert(1, "../../../")
import h2o, tests
def perfectSeparation_unbalanced():
print("Read in synthetic unbalanced dataset")
data = h2o.import_file(h2o.locate("smalldata/synthetic_perfect_separation/unbalanced.csv"))
print("Fit model on dataset.")
model = h2o.glm(x=data[["x1", "x2"]], y=data["y"], family="binomial", lambda_search=True, alpha=[0.5], Lambda=[0])
print("Extract models' coefficients and assert reasonable values (ie. no greater than 50)")
print("Unbalanced dataset")
coef = [c[1] for c in model._model_json['output']['coefficients_table'].cell_values if c[0] != "Intercept"]
for c in coef:
assert c < 50, "coefficient is too large"
if __name__ == "__main__":
tests.run_test(sys.argv, perfectSeparation_unbalanced)
| {
"content_hash": "c2f0254e4c4d3afe9dfc40c019746c98",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 118,
"avg_line_length": 36.68181818181818,
"alnum_prop": 0.6592317224287485,
"repo_name": "printedheart/h2o-3",
"id": "30d14b0c0b5ab84286e682c26b7581529bab5fbe",
"size": "807",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "h2o-py/tests/testdir_algos/glm/pyunit_perfectSeparation_unbalancedGLM.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5090"
},
{
"name": "CSS",
"bytes": "163561"
},
{
"name": "CoffeeScript",
"bytes": "262107"
},
{
"name": "Emacs Lisp",
"bytes": "8927"
},
{
"name": "Groovy",
"bytes": "78"
},
{
"name": "HTML",
"bytes": "147257"
},
{
"name": "Java",
"bytes": "5417378"
},
{
"name": "JavaScript",
"bytes": "38932"
},
{
"name": "Makefile",
"bytes": "34005"
},
{
"name": "Python",
"bytes": "2098211"
},
{
"name": "R",
"bytes": "1831996"
},
{
"name": "Rebol",
"bytes": "7059"
},
{
"name": "Ruby",
"bytes": "3506"
},
{
"name": "Scala",
"bytes": "16336"
},
{
"name": "Shell",
"bytes": "47017"
},
{
"name": "TeX",
"bytes": "588475"
}
],
"symlink_target": ""
} |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['None'] , ['MovingMedian'] , ['NoCycle'] , ['MLP'] ); | {
"content_hash": "73b6257bc8ae53eec9e56460c6585c06",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 75,
"avg_line_length": 37,
"alnum_prop": 0.6959459459459459,
"repo_name": "antoinecarme/pyaf",
"id": "c283f737d0e90daf68d597f3df29df3a356f0600",
"size": "148",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/model_control/detailed/transf_None/model_control_one_enabled_None_MovingMedian_NoCycle_MLP.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "6773299"
},
{
"name": "Procfile",
"bytes": "24"
},
{
"name": "Python",
"bytes": "54209093"
},
{
"name": "R",
"bytes": "807"
},
{
"name": "Shell",
"bytes": "3619"
}
],
"symlink_target": ""
} |
"""cl.utils"""
from __future__ import absolute_import
import operator
from importlib import import_module
from itertools import imap, ifilter
from kombu.utils import cached_property # noqa
__all__ = ["force_list", "flatten", "get_cls_by_name",
"instantiate", "cached_property"]
def force_list(obj):
if not hasattr(obj, "__iter__"):
return [obj]
return obj
def flatten(it):
if it:
try:
return reduce(operator.add,
imap(force_list, ifilter(None, it)))
except TypeError:
return []
return it
def first(it, default=None):
try:
it.next()
except StopIteration:
return default
def first_or_raise(it, exc):
for reply in it:
if not isinstance(reply, Exception):
return reply
raise exc
def get_cls_by_name(name, aliases={}, imp=None):
"""Get class by name.
The name should be the full dot-separated path to the class::
modulename.ClassName
Example::
celery.concurrency.processes.TaskPool
^- class name
If `aliases` is provided, a dict containing short name/long name
mappings, the name is looked up in the aliases first.
Examples:
>>> get_cls_by_name("celery.concurrency.processes.TaskPool")
<class 'celery.concurrency.processes.TaskPool'>
>>> get_cls_by_name("default", {
... "default": "celery.concurrency.processes.TaskPool"})
<class 'celery.concurrency.processes.TaskPool'>
# Does not try to look up non-string names.
>>> from celery.concurrency.processes import TaskPool
>>> get_cls_by_name(TaskPool) is TaskPool
True
"""
if imp is None:
imp = import_module
if not isinstance(name, basestring):
return name # already a class
name = aliases.get(name) or name
module_name, _, cls_name = name.rpartition(".")
try:
module = imp(module_name)
except ValueError, exc:
raise ValueError("Couldn't import %r: %s" % (name, exc))
return getattr(module, cls_name)
def instantiate(name, *args, **kwargs):
"""Instantiate class by name.
See :func:`get_cls_by_name`.
"""
return get_cls_by_name(name)(*args, **kwargs)
def abbr(S, max, ellipsis="..."):
if S and len(S) > max:
return ellipsis and (S[:max - len(ellipsis)] + ellipsis) or S[:max]
return S
def shortuuid(u):
if '-' in u:
return u[:u.index('-')]
return abbr(u, 16)
| {
"content_hash": "bc3b13c1b0a930f5b0ab200571688a03",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 75,
"avg_line_length": 23.73394495412844,
"alnum_prop": 0.5887127947429455,
"repo_name": "pexip/os-python-cl",
"id": "91e98cc554fe49da11f92cc9554a37576fdb7a5d",
"size": "2587",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cl/utils/__init__.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "49222"
}
],
"symlink_target": ""
} |
FAILEDOPERATION_APPLYBLACKLISTDATAERROR = 'FailedOperation.ApplyBlackListDataError'
# 提交黑名单出错。
FAILEDOPERATION_APPLYBLACKLISTERROR = 'FailedOperation.ApplyBlackListError'
# 提交信审申请出错。
FAILEDOPERATION_APPLYCREDITAUDITERROR = 'FailedOperation.ApplyCreditAuditError'
# 机器人任务作业状态更新出错。
FAILEDOPERATION_CHANGEBOTCALLSTATUSERROR = 'FailedOperation.ChangeBotCallStatusError'
# 机器人任务状态更新出错。
FAILEDOPERATION_CHANGEBOTSTATUSERROR = 'FailedOperation.ChangeBotStatusError'
# 创建机器人任务出错。
FAILEDOPERATION_CREATEBOTTASKERROR = 'FailedOperation.CreateBotTaskError'
# 获取黑名单数据列表出错。
FAILEDOPERATION_DESCRIBEBLACKLISTDATAERROR = 'FailedOperation.DescribeBlacklistDataError'
# 查询机器人对话流出错。
FAILEDOPERATION_DESCRIBEBOTFLOWERROR = 'FailedOperation.DescribeBotFlowError'
# 查询机器人文件模板出错。
FAILEDOPERATION_DESCRIBEFILEMODELERROR = 'FailedOperation.DescribeFileModelError'
# 获取产品列表出错。
FAILEDOPERATION_DESCRIBEPRODUCTSERROR = 'FailedOperation.DescribeProductsError'
# 获取录音列表出错。
FAILEDOPERATION_DESCRIBERECORDSERROR = 'FailedOperation.DescribeRecordsError'
# 查询任务状态出错。
FAILEDOPERATION_DESCRIBETASKSTATUSERROR = 'FailedOperation.DescribeTaskStatusError'
# 录音列表下载出错。
FAILEDOPERATION_DOWNLOADRECORDLISTERROR = 'FailedOperation.DownloadRecordListError'
# 报告下载出错。
FAILEDOPERATION_DOWNLOADREPORTERROR = 'FailedOperation.DownloadReportError'
# 导出机器人数据失败。
FAILEDOPERATION_EXPORTBOTDATAERROR = 'FailedOperation.ExportBotDataError'
# 获取信审结果出错。
FAILEDOPERATION_GETCREDITAUDITERROR = 'FailedOperation.GetCreditAuditError'
# 查询黑名单出错。
FAILEDOPERATION_QUERYBLACKLISTDATAERROR = 'FailedOperation.QueryBlackListDataError'
# 查询机器人列表出错。
FAILEDOPERATION_QUERYBOTLISTERROR = 'FailedOperation.QueryBotListError'
# 查询任务失败。
FAILEDOPERATION_QUERYCALLLISTERROR = 'FailedOperation.QueryCallListError'
# 查询录音列表出错。
FAILEDOPERATION_QUERYRECORDLISTERROR = 'FailedOperation.QueryRecordListError'
# 修改机器人任务出错。
FAILEDOPERATION_UPDATEBOTTASKERROR = 'FailedOperation.UpdateBotTaskError'
# 上传机器人文件出错。
FAILEDOPERATION_UPLOADBOTFILE = 'FailedOperation.UploadBotFile'
# 上传数据出错。
FAILEDOPERATION_UPLOADDATAERROR = 'FailedOperation.UploadDataError'
# 内部错误。
INTERNALERROR = 'InternalError'
# 内部未知错误。
INTERNALERROR_UNKNOWNERROR = 'InternalError.UnknownError'
# 找不到Module 或 Operation。
MISSINGPARAMETER_MOERROR = 'MissingParameter.MOError'
# 黑名单数据不存在。
RESOURCENOTFOUND_BLACKLISTDATANOTFOUND = 'ResourceNotFound.BlacklistDataNotFound'
# 企业不存在。
RESOURCENOTFOUND_COMPANYNOTFOUND = 'ResourceNotFound.CompanyNotFound'
# 录音列表不存在。
RESOURCENOTFOUND_RECORDLISTNOTFOUND = 'ResourceNotFound.RecordListNotFound'
# 报告不存在。
RESOURCENOTFOUND_REPORTNOTFOUND = 'ResourceNotFound.ReportNotFound'
# 任务不存在。
RESOURCENOTFOUND_TASKNOTFOUND = 'ResourceNotFound.TaskNotFound'
# 企业已欠费或已被回收。
RESOURCEUNAVAILABLE_COMPANYUNAVAILABLE = 'ResourceUnavailable.CompanyUnavailable'
# 账户不存在或未开通金融联络机器人。
UNAUTHORIZEDOPERATION_ACCOUNTNOTFOUND = 'UnauthorizedOperation.AccountNotFound'
| {
"content_hash": "ab9244c28155722ee6ee138ab564c2f7",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 89,
"avg_line_length": 29.855670103092784,
"alnum_prop": 0.8535911602209945,
"repo_name": "tzpBingo/github-trending",
"id": "469c5bcb7a47dcb1010c1bc54b938945526b1c27",
"size": "4158",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "codespace/python/tencentcloud/cr/v20180321/errorcodes.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "11470"
},
{
"name": "HTML",
"bytes": "1543"
},
{
"name": "Python",
"bytes": "49985109"
},
{
"name": "Shell",
"bytes": "18039"
}
],
"symlink_target": ""
} |
"""
This module provides more sophisticated flow tracking and provides filtering and interception facilities.
"""
from __future__ import absolute_import
from abc import abstractmethod, ABCMeta
import hashlib
import Cookie
import cookielib
import os
import re
import urlparse
from netlib import wsgi
from netlib.exceptions import HttpException
from netlib.http import CONTENT_MISSING, Headers, http1
import netlib.http
from . import controller, tnetstring, filt, script, version
from .onboarding import app
from .proxy.config import HostMatcher
from .protocol.http_replay import RequestReplayThread
from .protocol import Kill
from .models import ClientConnection, ServerConnection, HTTPResponse, HTTPFlow, HTTPRequest
class AppRegistry:
def __init__(self):
self.apps = {}
def add(self, app, domain, port):
"""
Add a WSGI app to the registry, to be served for requests to the
specified domain, on the specified port.
"""
self.apps[(domain, port)] = wsgi.WSGIAdaptor(
app,
domain,
port,
version.NAMEVERSION
)
def get(self, request):
"""
Returns an WSGIAdaptor instance if request matches an app, or None.
"""
if (request.host, request.port) in self.apps:
return self.apps[(request.host, request.port)]
if "host" in request.headers:
host = request.headers["host"]
return self.apps.get((host, request.port), None)
class ReplaceHooks:
def __init__(self):
self.lst = []
def set(self, r):
self.clear()
for i in r:
self.add(*i)
def add(self, fpatt, rex, s):
"""
add a replacement hook.
fpatt: a string specifying a filter pattern.
rex: a regular expression.
s: the replacement string
returns true if hook was added, false if the pattern could not be
parsed.
"""
cpatt = filt.parse(fpatt)
if not cpatt:
return False
try:
re.compile(rex)
except re.error:
return False
self.lst.append((fpatt, rex, s, cpatt))
return True
def get_specs(self):
"""
Retrieve the hook specifcations. Returns a list of (fpatt, rex, s)
tuples.
"""
return [i[:3] for i in self.lst]
def count(self):
return len(self.lst)
def run(self, f):
for _, rex, s, cpatt in self.lst:
if cpatt(f):
if f.response:
f.response.replace(rex, s)
else:
f.request.replace(rex, s)
def clear(self):
self.lst = []
class SetHeaders:
def __init__(self):
self.lst = []
def set(self, r):
self.clear()
for i in r:
self.add(*i)
def add(self, fpatt, header, value):
"""
Add a set header hook.
fpatt: String specifying a filter pattern.
header: Header name.
value: Header value string
Returns True if hook was added, False if the pattern could not be
parsed.
"""
cpatt = filt.parse(fpatt)
if not cpatt:
return False
self.lst.append((fpatt, header, value, cpatt))
return True
def get_specs(self):
"""
Retrieve the hook specifcations. Returns a list of (fpatt, rex, s)
tuples.
"""
return [i[:3] for i in self.lst]
def count(self):
return len(self.lst)
def clear(self):
self.lst = []
def run(self, f):
for _, header, value, cpatt in self.lst:
if cpatt(f):
if f.response:
f.response.headers.pop(header, None)
else:
f.request.headers.pop(header, None)
for _, header, value, cpatt in self.lst:
if cpatt(f):
if f.response:
f.response.headers.fields.append((header, value))
else:
f.request.headers.fields.append((header, value))
class StreamLargeBodies(object):
def __init__(self, max_size):
self.max_size = max_size
def run(self, flow, is_request):
r = flow.request if is_request else flow.response
expected_size = http1.expected_http_body_size(
flow.request, flow.response if not is_request else None
)
if not (0 <= expected_size <= self.max_size):
# r.stream may already be a callable, which we want to preserve.
r.stream = r.stream or True
class ClientPlaybackState:
def __init__(self, flows, exit):
self.flows, self.exit = flows, exit
self.current = None
self.testing = False # Disables actual replay for testing.
def count(self):
return len(self.flows)
def done(self):
if len(self.flows) == 0 and not self.current:
return True
return False
def clear(self, flow):
"""
A request has returned in some way - if this is the one we're
servicing, go to the next flow.
"""
if flow is self.current:
self.current = None
def tick(self, master):
if self.flows and not self.current:
self.current = self.flows.pop(0).copy()
if not self.testing:
master.replay_request(self.current)
else:
self.current.reply = controller.DummyReply()
master.handle_request(self.current)
if self.current.response:
master.handle_response(self.current)
class ServerPlaybackState:
def __init__(
self,
headers,
flows,
exit,
nopop,
ignore_params,
ignore_content,
ignore_payload_params,
ignore_host):
"""
headers: Case-insensitive list of request headers that should be
included in request-response matching.
"""
self.headers = headers
self.exit = exit
self.nopop = nopop
self.ignore_params = ignore_params
self.ignore_content = ignore_content
self.ignore_payload_params = ignore_payload_params
self.ignore_host = ignore_host
self.fmap = {}
for i in flows:
if i.response:
l = self.fmap.setdefault(self._hash(i), [])
l.append(i)
def count(self):
return sum(len(i) for i in self.fmap.values())
def _hash(self, flow):
"""
Calculates a loose hash of the flow request.
"""
r = flow.request
_, _, path, _, query, _ = urlparse.urlparse(r.url)
queriesArray = urlparse.parse_qsl(query, keep_blank_values=True)
# scheme should match the client connection to be able to replay
# although r.scheme may have been changed to http to connect to upstream server
scheme = "https" if flow.client_conn and flow.client_conn.ssl_established else "http"
key = [
str(r.port),
str(scheme),
str(r.method),
str(path),
]
if not self.ignore_content:
form_contents = r.get_form()
if self.ignore_payload_params and form_contents:
key.extend(
p for p in form_contents
if p[0] not in self.ignore_payload_params
)
else:
key.append(str(r.content))
if not self.ignore_host:
key.append(r.host)
filtered = []
ignore_params = self.ignore_params or []
for p in queriesArray:
if p[0] not in ignore_params:
filtered.append(p)
for p in filtered:
key.append(p[0])
key.append(p[1])
if self.headers:
headers = []
for i in self.headers:
v = r.headers.get(i)
headers.append((i, v))
key.append(headers)
return hashlib.sha256(repr(key)).digest()
def next_flow(self, request):
"""
Returns the next flow object, or None if no matching flow was
found.
"""
l = self.fmap.get(self._hash(request))
if not l:
return None
if self.nopop:
return l[0]
else:
return l.pop(0)
class StickyCookieState:
def __init__(self, flt):
"""
flt: Compiled filter.
"""
self.jar = {}
self.flt = flt
def ckey(self, m, f):
"""
Returns a (domain, port, path) tuple.
"""
return (
m["domain"] or f.request.host,
f.request.port,
m["path"] or "/"
)
def domain_match(self, a, b):
if cookielib.domain_match(a, b):
return True
elif cookielib.domain_match(a, b.strip(".")):
return True
return False
def handle_response(self, f):
for i in f.response.headers.get_all("set-cookie"):
# FIXME: We now know that Cookie.py screws up some cookies with
# valid RFC 822/1123 datetime specifications for expiry. Sigh.
c = Cookie.SimpleCookie(str(i))
for m in c.values():
k = self.ckey(m, f)
if self.domain_match(f.request.host, k[0]):
self.jar[k] = m
def handle_request(self, f):
l = []
if f.match(self.flt):
for i in self.jar.keys():
match = [
self.domain_match(f.request.host, i[0]),
f.request.port == i[1],
f.request.path.startswith(i[2])
]
if all(match):
l.append(self.jar[i].output(header="").strip())
if l:
f.request.stickycookie = True
f.request.headers.set_all("cookie",l)
class StickyAuthState:
def __init__(self, flt):
"""
flt: Compiled filter.
"""
self.flt = flt
self.hosts = {}
def handle_request(self, f):
host = f.request.host
if "authorization" in f.request.headers:
self.hosts[host] = f.request.headers["authorization"]
elif f.match(self.flt):
if host in self.hosts:
f.request.headers["authorization"] = self.hosts[host]
class FlowList(object):
__metaclass__ = ABCMeta
def __iter__(self):
return iter(self._list)
def __contains__(self, item):
return item in self._list
def __getitem__(self, item):
return self._list[item]
def __nonzero__(self):
return bool(self._list)
def __len__(self):
return len(self._list)
def index(self, f):
return self._list.index(f)
@abstractmethod
def _add(self, f):
return
@abstractmethod
def _update(self, f):
return
@abstractmethod
def _remove(self, f):
return
class FlowView(FlowList):
def __init__(self, store, filt=None):
self._list = []
if not filt:
filt = lambda flow: True
self._build(store, filt)
self.store = store
self.store.views.append(self)
def _close(self):
self.store.views.remove(self)
def _build(self, flows, filt=None):
if filt:
self.filt = filt
self._list = list(filter(self.filt, flows))
def _add(self, f):
if self.filt(f):
self._list.append(f)
def _update(self, f):
if f not in self._list:
self._add(f)
elif not self.filt(f):
self._remove(f)
def _remove(self, f):
if f in self._list:
self._list.remove(f)
def _recalculate(self, flows):
self._build(flows)
class FlowStore(FlowList):
"""
Responsible for handling flows in the state:
Keeps a list of all flows and provides views on them.
"""
def __init__(self):
self._list = []
self._set = set() # Used for O(1) lookups
self.views = []
self._recalculate_views()
def get(self, flow_id):
for f in self._list:
if f.id == flow_id:
return f
def __contains__(self, f):
return f in self._set
def _add(self, f):
"""
Adds a flow to the state.
The flow to add must not be present in the state.
"""
self._list.append(f)
self._set.add(f)
for view in self.views:
view._add(f)
def _update(self, f):
"""
Notifies the state that a flow has been updated.
The flow must be present in the state.
"""
if f in self:
for view in self.views:
view._update(f)
def _remove(self, f):
"""
Deletes a flow from the state.
The flow must be present in the state.
"""
self._list.remove(f)
self._set.remove(f)
for view in self.views:
view._remove(f)
# Expensive bulk operations
def _extend(self, flows):
"""
Adds a list of flows to the state.
The list of flows to add must not contain flows that are already in the state.
"""
self._list.extend(flows)
self._set.update(flows)
self._recalculate_views()
def _clear(self):
self._list = []
self._set = set()
self._recalculate_views()
def _recalculate_views(self):
"""
Expensive operation: Recalculate all the views after a bulk change.
"""
for view in self.views:
view._recalculate(self)
# Utility functions.
# There are some common cases where we need to argue about all flows
# irrespective of filters on the view etc (i.e. on shutdown).
def active_count(self):
c = 0
for i in self._list:
if not i.response and not i.error:
c += 1
return c
# TODO: Should accept_all operate on views or on all flows?
def accept_all(self, master):
for f in self._list:
f.accept_intercept(master)
def kill_all(self, master):
for f in self._list:
f.kill(master)
class State(object):
def __init__(self):
self.flows = FlowStore()
self.view = FlowView(self.flows, None)
# These are compiled filt expressions:
self.intercept = None
@property
def limit_txt(self):
return getattr(self.view.filt, "pattern", None)
def flow_count(self):
return len(self.flows)
# TODO: All functions regarding flows that don't cause side-effects should
# be moved into FlowStore.
def index(self, f):
return self.flows.index(f)
def active_flow_count(self):
return self.flows.active_count()
def add_flow(self, f):
"""
Add a request to the state.
"""
self.flows._add(f)
return f
def update_flow(self, f):
"""
Add a response to the state.
"""
self.flows._update(f)
return f
def delete_flow(self, f):
self.flows._remove(f)
def load_flows(self, flows):
self.flows._extend(flows)
def set_limit(self, txt):
if txt == self.limit_txt:
return
if txt:
f = filt.parse(txt)
if not f:
return "Invalid filter expression."
self.view._close()
self.view = FlowView(self.flows, f)
else:
self.view._close()
self.view = FlowView(self.flows, None)
def set_intercept(self, txt):
if txt:
f = filt.parse(txt)
if not f:
return "Invalid filter expression."
self.intercept = f
else:
self.intercept = None
@property
def intercept_txt(self):
return getattr(self.intercept, "pattern", None)
def clear(self):
self.flows._clear()
def accept_all(self, master):
self.flows.accept_all(master)
def backup(self, f):
f.backup()
self.update_flow(f)
def revert(self, f):
f.revert()
self.update_flow(f)
def killall(self, master):
self.flows.kill_all(master)
class FlowMaster(controller.Master):
def __init__(self, server, state):
controller.Master.__init__(self, server)
self.state = state
self.server_playback = None
self.client_playback = None
self.kill_nonreplay = False
self.scripts = []
self.pause_scripts = False
self.stickycookie_state = False
self.stickycookie_txt = None
self.stickyauth_state = False
self.stickyauth_txt = None
self.anticache = False
self.anticomp = False
self.stream_large_bodies = False
self.refresh_server_playback = False
self.replacehooks = ReplaceHooks()
self.setheaders = SetHeaders()
self.replay_ignore_params = False
self.replay_ignore_content = None
self.replay_ignore_host = False
self.stream = None
self.apps = AppRegistry()
def start_app(self, host, port):
self.apps.add(
app.mapp,
host,
port
)
def add_event(self, e, level="info"):
"""
level: debug, info, error
"""
pass
def unload_scripts(self):
for s in self.scripts[:]:
self.unload_script(s)
def unload_script(self, script_obj):
try:
script_obj.unload()
except script.ScriptError as e:
self.add_event("Script error:\n" + str(e), "error")
self.scripts.remove(script_obj)
def load_script(self, command):
"""
Loads a script. Returns an error description if something went
wrong.
"""
try:
s = script.Script(command, self)
except script.ScriptError as v:
return v.args[0]
self.scripts.append(s)
def _run_single_script_hook(self, script_obj, name, *args, **kwargs):
if script_obj and not self.pause_scripts:
try:
script_obj.run(name, *args, **kwargs)
except script.ScriptError as e:
self.add_event("Script error:\n" + str(e), "error")
def run_script_hook(self, name, *args, **kwargs):
for script_obj in self.scripts:
self._run_single_script_hook(script_obj, name, *args, **kwargs)
def get_ignore_filter(self):
return self.server.config.check_ignore.patterns
def set_ignore_filter(self, host_patterns):
self.server.config.check_ignore = HostMatcher(host_patterns)
def get_tcp_filter(self):
return self.server.config.check_tcp.patterns
def set_tcp_filter(self, host_patterns):
self.server.config.check_tcp = HostMatcher(host_patterns)
def set_stickycookie(self, txt):
if txt:
flt = filt.parse(txt)
if not flt:
return "Invalid filter expression."
self.stickycookie_state = StickyCookieState(flt)
self.stickycookie_txt = txt
else:
self.stickycookie_state = None
self.stickycookie_txt = None
def set_stream_large_bodies(self, max_size):
if max_size is not None:
self.stream_large_bodies = StreamLargeBodies(max_size)
else:
self.stream_large_bodies = False
def set_stickyauth(self, txt):
if txt:
flt = filt.parse(txt)
if not flt:
return "Invalid filter expression."
self.stickyauth_state = StickyAuthState(flt)
self.stickyauth_txt = txt
else:
self.stickyauth_state = None
self.stickyauth_txt = None
def start_client_playback(self, flows, exit):
"""
flows: List of flows.
"""
self.client_playback = ClientPlaybackState(flows, exit)
def stop_client_playback(self):
self.client_playback = None
def start_server_playback(
self,
flows,
kill,
headers,
exit,
nopop,
ignore_params,
ignore_content,
ignore_payload_params,
ignore_host):
"""
flows: List of flows.
kill: Boolean, should we kill requests not part of the replay?
ignore_params: list of parameters to ignore in server replay
ignore_content: true if request content should be ignored in server replay
ignore_payload_params: list of content params to ignore in server replay
ignore_host: true if request host should be ignored in server replay
"""
self.server_playback = ServerPlaybackState(
headers,
flows,
exit,
nopop,
ignore_params,
ignore_content,
ignore_payload_params,
ignore_host)
self.kill_nonreplay = kill
def stop_server_playback(self):
if self.server_playback.exit:
self.shutdown()
self.server_playback = None
def do_server_playback(self, flow):
"""
This method should be called by child classes in the handle_request
handler. Returns True if playback has taken place, None if not.
"""
if self.server_playback:
rflow = self.server_playback.next_flow(flow)
if not rflow:
return None
response = HTTPResponse.from_state(rflow.response.get_state())
response.is_replay = True
if self.refresh_server_playback:
response.refresh()
flow.reply(response)
if self.server_playback.count() == 0:
self.stop_server_playback()
return True
return None
def tick(self, q, timeout):
if self.client_playback:
e = [
self.client_playback.done(),
self.client_playback.exit,
self.state.active_flow_count() == 0
]
if all(e):
self.shutdown()
self.client_playback.tick(self)
if self.client_playback.done():
self.client_playback = None
return super(FlowMaster, self).tick(q, timeout)
def duplicate_flow(self, f):
return self.load_flow(f.copy())
def create_request(self, method, scheme, host, port, path):
"""
this method creates a new artificial and minimalist request also adds it to flowlist
"""
c = ClientConnection.from_state(dict(
address=dict(address=(host, port), use_ipv6=False),
clientcert=None
))
s = ServerConnection.from_state(dict(
address=dict(address=(host, port), use_ipv6=False),
state=[],
source_address=None,
# source_address=dict(address=(host, port), use_ipv6=False),
cert=None,
sni=host,
ssl_established=True
))
f = HTTPFlow(c, s)
headers = Headers()
req = HTTPRequest(
"absolute",
method,
scheme,
host,
port,
path,
b"HTTP/1.1",
headers,
None,
None,
None,
None)
f.request = req
return self.load_flow(f)
def load_flow(self, f):
"""
Loads a flow, and returns a new flow object.
"""
if self.server and self.server.config.mode == "reverse":
f.request.host = self.server.config.upstream_server.address.host
f.request.port = self.server.config.upstream_server.address.port
f.request.scheme = re.sub("^https?2", "", self.server.config.upstream_server.scheme)
f.reply = controller.DummyReply()
if f.request:
self.handle_request(f)
if f.response:
self.handle_responseheaders(f)
self.handle_response(f)
if f.error:
self.handle_error(f)
return f
def load_flows(self, fr):
"""
Load flows from a FlowReader object.
"""
cnt = 0
for i in fr.stream():
cnt += 1
self.load_flow(i)
return cnt
def load_flows_file(self, path):
path = os.path.expanduser(path)
try:
f = file(path, "rb")
freader = FlowReader(f)
except IOError as v:
raise FlowReadError(v.strerror)
return self.load_flows(freader)
def process_new_request(self, f):
if self.stickycookie_state:
self.stickycookie_state.handle_request(f)
if self.stickyauth_state:
self.stickyauth_state.handle_request(f)
if self.anticache:
f.request.anticache()
if self.anticomp:
f.request.anticomp()
if self.server_playback:
pb = self.do_server_playback(f)
if not pb:
if self.kill_nonreplay:
f.kill(self)
else:
f.reply()
def process_new_response(self, f):
if self.stickycookie_state:
self.stickycookie_state.handle_response(f)
def replay_request(self, f, block=False, run_scripthooks=True):
"""
Returns None if successful, or error message if not.
"""
if f.live and run_scripthooks:
return "Can't replay live request."
if f.intercepted:
return "Can't replay while intercepting..."
if f.request.content == CONTENT_MISSING:
return "Can't replay request with missing content..."
if f.request:
f.backup()
f.request.is_replay = True
if f.request.content:
f.request.headers["Content-Length"] = str(len(f.request.content))
f.response = None
f.error = None
self.process_new_request(f)
rt = RequestReplayThread(
self.server.config,
f,
self.masterq if run_scripthooks else False,
self.should_exit
)
rt.start() # pragma: no cover
if block:
rt.join()
def handle_log(self, l):
self.add_event(l.msg, l.level)
l.reply()
def handle_clientconnect(self, root_layer):
self.run_script_hook("clientconnect", root_layer)
root_layer.reply()
def handle_clientdisconnect(self, root_layer):
self.run_script_hook("clientdisconnect", root_layer)
root_layer.reply()
def handle_serverconnect(self, server_conn):
self.run_script_hook("serverconnect", server_conn)
server_conn.reply()
def handle_serverdisconnect(self, server_conn):
self.run_script_hook("serverdisconnect", server_conn)
server_conn.reply()
def handle_next_layer(self, top_layer):
self.run_script_hook("next_layer", top_layer)
top_layer.reply()
def handle_error(self, f):
self.state.update_flow(f)
self.run_script_hook("error", f)
if self.client_playback:
self.client_playback.clear(f)
f.reply()
return f
def handle_request(self, f):
if f.live:
app = self.apps.get(f.request)
if app:
err = app.serve(
f,
f.client_conn.wfile,
**{"mitmproxy.master": self}
)
if err:
self.add_event("Error in wsgi app. %s" % err, "error")
f.reply(Kill)
return
if f not in self.state.flows: # don't add again on replay
self.state.add_flow(f)
self.replacehooks.run(f)
self.setheaders.run(f)
self.run_script_hook("request", f)
self.process_new_request(f)
return f
def handle_responseheaders(self, f):
self.run_script_hook("responseheaders", f)
try:
if self.stream_large_bodies:
self.stream_large_bodies.run(f, False)
except HttpException:
f.reply(Kill)
return
f.reply()
return f
def handle_response(self, f):
self.state.update_flow(f)
self.replacehooks.run(f)
self.setheaders.run(f)
self.run_script_hook("response", f)
if self.client_playback:
self.client_playback.clear(f)
self.process_new_response(f)
if self.stream:
self.stream.add(f)
return f
def handle_intercept(self, f):
self.state.update_flow(f)
def handle_accept_intercept(self, f):
self.state.update_flow(f)
def shutdown(self):
self.unload_scripts()
controller.Master.shutdown(self)
if self.stream:
for i in self.state.flows:
if not i.response:
self.stream.add(i)
self.stop_stream()
def start_stream(self, fp, filt):
self.stream = FilteredFlowWriter(fp, filt)
def stop_stream(self):
self.stream.fo.close()
self.stream = None
def read_flows_from_paths(paths):
"""
Given a list of filepaths, read all flows and return a list of them.
From a performance perspective, streaming would be advisable -
however, if there's an error with one of the files, we want it to be raised immediately.
If an error occurs, a FlowReadError will be raised.
"""
try:
flows = []
for path in paths:
path = os.path.expanduser(path)
with file(path, "rb") as f:
flows.extend(FlowReader(f).stream())
except IOError as e:
raise FlowReadError(e.strerror)
return flows
class FlowWriter:
def __init__(self, fo):
self.fo = fo
def add(self, flow):
d = flow.get_state()
tnetstring.dump(d, self.fo)
class FlowReadError(Exception):
@property
def strerror(self):
return self.args[0]
class FlowReader:
def __init__(self, fo):
self.fo = fo
def stream(self):
"""
Yields Flow objects from the dump.
"""
off = 0
try:
while True:
data = tnetstring.load(self.fo)
if tuple(data["version"][:2]) != version.IVERSION[:2]:
v = ".".join(str(i) for i in data["version"])
raise FlowReadError(
"Incompatible serialized data version: %s" % v
)
off = self.fo.tell()
yield HTTPFlow.from_state(data)
except ValueError as v:
# Error is due to EOF
if self.fo.tell() == off and self.fo.read() == '':
return
raise FlowReadError("Invalid data format.")
class FilteredFlowWriter:
def __init__(self, fo, filt):
self.fo = fo
self.filt = filt
def add(self, f):
if self.filt and not f.match(self.filt):
return
d = f.get_state()
tnetstring.dump(d, self.fo)
| {
"content_hash": "de45e14d10e3f0b3511ce9cd7d21dee6",
"timestamp": "",
"source": "github",
"line_count": 1114,
"max_line_length": 109,
"avg_line_length": 28.45152603231598,
"alnum_prop": 0.5369616658778987,
"repo_name": "ccccccccccc/mitmproxy",
"id": "d735b9eced709fe2786c8e5e6c0052e41f6e63c6",
"size": "31695",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libmproxy/flow.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "425"
},
{
"name": "CSS",
"bytes": "188807"
},
{
"name": "HTML",
"bytes": "2824"
},
{
"name": "JavaScript",
"bytes": "1728466"
},
{
"name": "Python",
"bytes": "654649"
},
{
"name": "Shell",
"bytes": "2337"
}
],
"symlink_target": ""
} |
"""Additional help text for anonymous access."""
from __future__ import absolute_import
from gslib.help_provider import HelpProvider
_DETAILED_HELP_TEXT = ("""
<B>OVERVIEW</B>
gsutil users can access publicly readable data without obtaining
credentials. For example, the gs://uspto-pair bucket contains a number
of publicly readable objects, so any user can run the following command
without first obtaining credentials:
gsutil ls gs://uspto-pair/applications/0800401*
Users can similarly download objects they find via the above gsutil ls
command.
See "gsutil help acls" for more details about data protection.
<B>Configuring/Using Credentials via Cloud SDK Distribution of gsutil</B>
If a user without credentials attempts to access protected data using gsutil,
they will be prompted to run gcloud init to obtain credentials.
<B>Configuring/Using Credentials via Standalone gsutil Distribution</B>
If a user without credentials attempts to access protected data using gsutil,
they will be prompted to run gsutil config to obtain credentials.
""")
class CommandOptions(HelpProvider):
"""Additional help text for anonymous access."""
# Help specification. See help_provider.py for documentation.
help_spec = HelpProvider.HelpSpec(
help_name='anon',
help_name_aliases=['anonymous', 'public'],
help_type='additional_help',
help_one_line_summary='Accessing Public Data Without Credentials',
help_text=_DETAILED_HELP_TEXT,
subcommand_help_text={},
)
| {
"content_hash": "bfdf1d5812ece759f793ef121d9e2836",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 79,
"avg_line_length": 36.357142857142854,
"alnum_prop": 0.7531106745252129,
"repo_name": "KaranToor/MA450",
"id": "79c5a66abfa13fb07bcb89945ab8d70e9254707d",
"size": "2147",
"binary": false,
"copies": "10",
"ref": "refs/heads/master",
"path": "google-cloud-sdk/.install/.backup/platform/gsutil/gslib/addlhelp/anon.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3162"
},
{
"name": "CSS",
"bytes": "1930"
},
{
"name": "HTML",
"bytes": "13381"
},
{
"name": "Java",
"bytes": "151442"
},
{
"name": "JavaScript",
"bytes": "4906"
},
{
"name": "Makefile",
"bytes": "1636"
},
{
"name": "Objective-C",
"bytes": "13335"
},
{
"name": "PHP",
"bytes": "9086"
},
{
"name": "Pascal",
"bytes": "62"
},
{
"name": "Python",
"bytes": "19710731"
},
{
"name": "Roff",
"bytes": "2069494"
},
{
"name": "Ruby",
"bytes": "690"
},
{
"name": "Shell",
"bytes": "32272"
},
{
"name": "Smarty",
"bytes": "4968"
},
{
"name": "SourcePawn",
"bytes": "616"
},
{
"name": "Swift",
"bytes": "14225"
}
],
"symlink_target": ""
} |
from scrapy.contrib.spiders import Spider
from scrapy.selector import Selector
from scrapy.http import Request
from Movie.items import MovieComment
class CommentSpider(Spider):
name = "moviecomment"
start_urls = [
]
def parse(self, response):
comments = list()
selector = Selector(response)
items = selector.css('#comments div.comment-item > div.comment') # div并不一定是#comments的孩子
for item in items:
comment = MovieComment()
comment['id'] = item.css('h3 > span.comment-info > a ::attr(href)').re(r'[\d]+')
comment['author'] = item.css('h3 > span.comment-info > a ::text').extract()
comment['rating'] = item.css('h3 > span.comment-info > span.rating ::attr(class)').re(r'[1-5]')
comment['time'] = item.css('h3 > span.comment-info > span ::text').extract()
comment['content'] = item.css('p ::text').extract()
comment['vote'] = item.css('h3 > span.comment-vote > span ::text').extract()
comments.append(comment)
# yield comments
params = selector.css('#paginator > a ::attr(href)').extract()
if params:
raw_url = response.url.split('?')
url = raw_url[0] + params[0]
yield Request(url=url, callback=parse)
| {
"content_hash": "48a1e682439621700a75b09b181b60f1",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 108,
"avg_line_length": 42.645161290322584,
"alnum_prop": 0.586232980332829,
"repo_name": "time-river/wander",
"id": "21423d5281e0a16511d498a1525fd448de6488b5",
"size": "1384",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scrapy/Movie/Movie/spiders/comments.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "100268"
}
],
"symlink_target": ""
} |
import unittest
from EXRReader import *
from TIFFReader import *
from ImagePrimitive import *
from JPEGReader import *
from CINReader import *
| {
"content_hash": "3d24124cf54ea5bce0462f994ed3d687",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 28,
"avg_line_length": 20.571428571428573,
"alnum_prop": 0.8055555555555556,
"repo_name": "hradec/cortex",
"id": "28e06a36af74997c81f0985297413c7b4e294dbd",
"size": "1928",
"binary": false,
"copies": "12",
"ref": "refs/heads/testing",
"path": "test/IECore/ImageTests.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "70350"
},
{
"name": "C++",
"bytes": "11602345"
},
{
"name": "CMake",
"bytes": "14161"
},
{
"name": "GLSL",
"bytes": "31098"
},
{
"name": "Mathematica",
"bytes": "255937"
},
{
"name": "Objective-C",
"bytes": "21989"
},
{
"name": "Python",
"bytes": "5076729"
},
{
"name": "Slash",
"bytes": "8583"
},
{
"name": "Tcl",
"bytes": "1796"
}
],
"symlink_target": ""
} |
'''
Fantastic 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 program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import urllib, urlparse, re
from resources.lib.modules import cleantitle
from resources.lib.modules import client
from resources.lib.modules import source_utils
from resources.lib.modules import dom_parser
from resources.lib.modules import trakt
class source:
def __init__(self):
self.priority = 1
self.language = ['gr']
self.domains = ['tainiomania.ucoz.com']
self.base_link = 'http://tainiomania.ucoz.com'
self.search_link = 'search/?q=%s'
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = self.__search([localtitle] + source_utils.aliases_to_array(aliases), year)
if not url and title != localtitle: url = self.__search([title] + source_utils.aliases_to_array(
aliases),year)
if not url: url = self.__search(trakt.getMovieTranslation(imdb, 'el'), year)
return url
except:
return
def __search(self, titles, year):
try:
query = self.search_link % (urllib.quote_plus(cleantitle.getsearch(titles[0]+' '+year)))
query = urlparse.urljoin(self.base_link, query)
t = [cleantitle.get(i) for i in set(titles) if i][0]
r = client.request(query)
r = dom_parser.parse_dom(r, 'div', attrs={'class': 'v_pict'})
for i in r:
title = re.findall('alt="(.+?)"',i[1], re.DOTALL)[0]
y = re.findall('(\d{4})', title, re.DOTALL)[0]
title = re.sub('<\w+>|</\w+>','',title)
title = cleantitle.get(title)
title = re.findall('(\w+)', cleantitle.get(title))[0]
if title in t and year == y:
url = re.findall('href="(.+?)"',i[1], re.DOTALL)[0]
return source_utils.strip_domain(url)
return
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if not url:
return sources
query = urlparse.urljoin(self.base_link, url)
data = client.request(query)
url = re.findall('file:"([^"]+)"', data, re.DOTALL)[0]
quality = 'SD'
lang, info = 'gr', 'SUB'
if url.endswith('.mp4'): direct = True
else: direct = False
sources.append({'source': 'tainiomania', 'quality': quality, 'language': lang, 'url': url, 'info': info,
'direct':direct,'debridonly': False})
return sources
except:
return sources
def resolve(self, url):
return url | {
"content_hash": "f73c5d3a8658c46d33b8d09a7c575b0c",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 116,
"avg_line_length": 34.10204081632653,
"alnum_prop": 0.5739078396169958,
"repo_name": "TheWardoctor/Wardoctors-repo",
"id": "110ac820e5a4c180c65220c9de3e413378b73fd4",
"size": "3367",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "script.module.fantastic/lib/resources/lib/sources/gr/tainiomania.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3208"
},
{
"name": "JavaScript",
"bytes": "115722"
},
{
"name": "Python",
"bytes": "34405207"
},
{
"name": "Shell",
"bytes": "914"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from sentry.constants import ObjectStatus
from sentry.models import Repository
class RepositoryMixin(object):
def get_repositories(self):
"""
Get a list of availble repositories for an installation
>>> def get_repositories(self):
>>> return self.get_client().get_repositories()
return [{
'name': display_name,
'identifier': external_repo_id,
}]
"""
raise NotImplementedError
def reinstall_repositories(self):
"""
reinstalls repositories associated with the integration
"""
organizations = self.model.organizations.all()
Repository.objects.filter(
organization_id__in=organizations.values_list('id', flat=True),
provider='integrations:%s' % self.model.provider,
integration_id=self.model.id,
).update(status=ObjectStatus.VISIBLE)
| {
"content_hash": "c8a3fddbfe46551aa58c904cc9b4aa98",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 75,
"avg_line_length": 29.96875,
"alnum_prop": 0.6256517205422315,
"repo_name": "looker/sentry",
"id": "89e335657434708dd02f2242cda934bfd43606f8",
"size": "959",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/sentry/integrations/repositories.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "289931"
},
{
"name": "HTML",
"bytes": "241322"
},
{
"name": "JavaScript",
"bytes": "3112298"
},
{
"name": "Lua",
"bytes": "65795"
},
{
"name": "Makefile",
"bytes": "7048"
},
{
"name": "Python",
"bytes": "36341504"
},
{
"name": "Ruby",
"bytes": "204"
},
{
"name": "Shell",
"bytes": "5701"
}
],
"symlink_target": ""
} |
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.25
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes.client.configuration import Configuration
class V1SELinuxOptions(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'level': 'str',
'role': 'str',
'type': 'str',
'user': 'str'
}
attribute_map = {
'level': 'level',
'role': 'role',
'type': 'type',
'user': 'user'
}
def __init__(self, level=None, role=None, type=None, user=None, local_vars_configuration=None): # noqa: E501
"""V1SELinuxOptions - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._level = None
self._role = None
self._type = None
self._user = None
self.discriminator = None
if level is not None:
self.level = level
if role is not None:
self.role = role
if type is not None:
self.type = type
if user is not None:
self.user = user
@property
def level(self):
"""Gets the level of this V1SELinuxOptions. # noqa: E501
Level is SELinux level label that applies to the container. # noqa: E501
:return: The level of this V1SELinuxOptions. # noqa: E501
:rtype: str
"""
return self._level
@level.setter
def level(self, level):
"""Sets the level of this V1SELinuxOptions.
Level is SELinux level label that applies to the container. # noqa: E501
:param level: The level of this V1SELinuxOptions. # noqa: E501
:type: str
"""
self._level = level
@property
def role(self):
"""Gets the role of this V1SELinuxOptions. # noqa: E501
Role is a SELinux role label that applies to the container. # noqa: E501
:return: The role of this V1SELinuxOptions. # noqa: E501
:rtype: str
"""
return self._role
@role.setter
def role(self, role):
"""Sets the role of this V1SELinuxOptions.
Role is a SELinux role label that applies to the container. # noqa: E501
:param role: The role of this V1SELinuxOptions. # noqa: E501
:type: str
"""
self._role = role
@property
def type(self):
"""Gets the type of this V1SELinuxOptions. # noqa: E501
Type is a SELinux type label that applies to the container. # noqa: E501
:return: The type of this V1SELinuxOptions. # noqa: E501
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this V1SELinuxOptions.
Type is a SELinux type label that applies to the container. # noqa: E501
:param type: The type of this V1SELinuxOptions. # noqa: E501
:type: str
"""
self._type = type
@property
def user(self):
"""Gets the user of this V1SELinuxOptions. # noqa: E501
User is a SELinux user label that applies to the container. # noqa: E501
:return: The user of this V1SELinuxOptions. # noqa: E501
:rtype: str
"""
return self._user
@user.setter
def user(self, user):
"""Sets the user of this V1SELinuxOptions.
User is a SELinux user label that applies to the container. # noqa: E501
:param user: The user of this V1SELinuxOptions. # noqa: E501
:type: str
"""
self._user = user
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1SELinuxOptions):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1SELinuxOptions):
return True
return self.to_dict() != other.to_dict()
| {
"content_hash": "2178812677f26750166e5cd53d976b0e",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 124,
"avg_line_length": 28.127450980392158,
"alnum_prop": 0.5629139072847682,
"repo_name": "kubernetes-client/python",
"id": "67a7ff7571b738c0dc848f1fa2598d2b1f3a9f7c",
"size": "5755",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kubernetes/client/models/v1_se_linux_options.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "356"
},
{
"name": "Python",
"bytes": "11454299"
},
{
"name": "Shell",
"bytes": "43108"
}
],
"symlink_target": ""
} |
import gzip
import numpy
from bigdl.dllib.feature.dataset import base
from bigdl.dllib.feature.dataset.transformer import *
from bigdl.dllib.utils.log4Error import *
SOURCE_URL = 'https://ossci-datasets.s3.amazonaws.com/mnist/'
TRAIN_MEAN = 0.13066047740239506 * 255
TRAIN_STD = 0.3081078 * 255
TEST_MEAN = 0.13251460696903547 * 255
TEST_STD = 0.31048024 * 255
def _read32(bytestream):
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_images(f):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth].
:param: f: A file object that can be passed into a gzip reader.
:return: data: A 4D unit8 numpy array [index, y, x, depth].
:raise: ValueError: If the bytestream does not start with 2051.
"""
print('Extracting', f.name)
with gzip.GzipFile(fileobj=f) as bytestream:
magic = _read32(bytestream)
if magic != 2051:
invalidInputError(False,
'Invalid magic number %d in MNIST image file: %s' %
(magic, f.name))
num_images = _read32(bytestream)
rows = _read32(bytestream)
cols = _read32(bytestream)
buf = bytestream.read(rows * cols * num_images)
data = numpy.frombuffer(buf, dtype=numpy.uint8)
data = data.reshape(num_images, rows, cols, 1)
return data
def extract_labels(f):
print('Extracting', f.name)
with gzip.GzipFile(fileobj=f) as bytestream:
magic = _read32(bytestream)
if magic != 2049:
invalidInputError(False,
'Invalid magic number %d in MNIST label file: %s' %
(magic, f.name))
num_items = _read32(bytestream)
buf = bytestream.read(num_items)
labels = numpy.frombuffer(buf, dtype=numpy.uint8)
return labels
def read_data_sets(train_dir, data_type="train"):
"""
Parse or download mnist data if train_dir is empty.
:param: train_dir: The directory storing the mnist data
:param: data_type: Reading training set or testing set.It can be either "train" or "test"
:return:
``` (ndarray, ndarray) representing (features, labels) features is a 4D unit8 numpy array [
index, y, x, depth] representing each pixel valued from 0 to 255. labels is 1D unit8 nunpy
array representing the label valued from 0 to 9. ```
"""
TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
if data_type == "train":
local_file = base.maybe_download(TRAIN_IMAGES, train_dir,
SOURCE_URL + TRAIN_IMAGES)
with open(local_file, 'rb') as f:
train_images = extract_images(f)
local_file = base.maybe_download(TRAIN_LABELS, train_dir,
SOURCE_URL + TRAIN_LABELS)
with open(local_file, 'rb') as f:
train_labels = extract_labels(f)
return train_images, train_labels
else:
local_file = base.maybe_download(TEST_IMAGES, train_dir,
SOURCE_URL + TEST_IMAGES)
with open(local_file, 'rb') as f:
test_images = extract_images(f)
local_file = base.maybe_download(TEST_LABELS, train_dir,
SOURCE_URL + TEST_LABELS)
with open(local_file, 'rb') as f:
test_labels = extract_labels(f)
return test_images, test_labels
def load_data(location="/tmp/mnist"):
(train_images, train_labels) = read_data_sets(location, "train")
(test_images, test_labels) = read_data_sets(location, "test")
X_train = normalizer(train_images, TRAIN_MEAN, TRAIN_STD)
X_test = normalizer(test_images, TRAIN_MEAN, TRAIN_STD)
Y_train = train_labels + 1
Y_test = test_labels + 1
return (X_train, Y_train), (X_test, Y_test)
if __name__ == "__main__":
train, _ = read_data_sets("/tmp/mnist/", "train")
test, _ = read_data_sets("/tmp/mnist", "test")
invalidInputError(numpy.abs(numpy.mean(train) - TRAIN_MEAN) / TRAIN_MEAN < 1e-7,
f"mean of train data doesn't match ${TRAIN_MEAN}")
invalidInputError(numpy.abs(numpy.std(train) - TRAIN_STD) / TRAIN_STD < 1e-7,
f"std of train data doesn't match ${TRAIN_STD}")
invalidInputError(numpy.abs(numpy.mean(test) - TEST_MEAN) / TEST_MEAN < 1e-7,
f"mean of test data doesn't match ${TEST_MEAN}")
invalidInputError(numpy.abs(numpy.std(test) - TEST_STD) / TEST_STD < 1e-7,
f"std of test data doesn't match ${TEST_STD_STD}")
| {
"content_hash": "53e438415a7b566bb9eb9daf6c4d3dc7",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 95,
"avg_line_length": 38.17460317460318,
"alnum_prop": 0.603950103950104,
"repo_name": "intel-analytics/BigDL",
"id": "1c8919efa0edbb8eba62ea4f8129d30165306062",
"size": "5444",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "python/dllib/src/bigdl/dllib/feature/dataset/mnist.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "5342"
},
{
"name": "Dockerfile",
"bytes": "139304"
},
{
"name": "Java",
"bytes": "1321348"
},
{
"name": "Jupyter Notebook",
"bytes": "54112822"
},
{
"name": "Lua",
"bytes": "1904"
},
{
"name": "Makefile",
"bytes": "19253"
},
{
"name": "PowerShell",
"bytes": "1137"
},
{
"name": "PureBasic",
"bytes": "593"
},
{
"name": "Python",
"bytes": "8825782"
},
{
"name": "RobotFramework",
"bytes": "16117"
},
{
"name": "Scala",
"bytes": "13216148"
},
{
"name": "Shell",
"bytes": "848241"
}
],
"symlink_target": ""
} |
"""Tests for the conversion functions."""
import pytest
from sc.conversions import UNITS, _to_dp, _from_dp
@pytest.mark.parametrize('unit', UNITS)
def test_conversion_bidirectional(unit):
to_ = _from_dp[unit]
from_ = _to_dp[unit]
assert to_(from_(100)) == 100
| {
"content_hash": "8ea161265f1c358093ac54c958d38742",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 50,
"avg_line_length": 23,
"alnum_prop": 0.6739130434782609,
"repo_name": "joshfriend/screencalc",
"id": "76c9cd991541ec3b9c8273f03b9a9fa217525f06",
"size": "299",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/test_conversions.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "6045"
},
{
"name": "Python",
"bytes": "11104"
}
],
"symlink_target": ""
} |
"""Unit tests for the API endpoint"""
import random
import StringIO
import boto
from boto.ec2 import regioninfo
from boto import exception as boto_exc
# newer versions of boto use their own wrapper on top of httplib.HTTPResponse
try:
from boto.connection import HTTPResponse
except ImportError:
from httplib import HTTPResponse
import webob
from nova.api import auth
from nova.api import ec2
from nova.api.ec2 import apirequest
from nova.api.ec2 import ec2utils
from nova import block_device
from nova import context
from nova import exception
from nova import flags
from nova.openstack.common import timeutils
from nova import test
FLAGS = flags.FLAGS
class FakeHttplibSocket(object):
"""a fake socket implementation for httplib.HTTPResponse, trivial"""
def __init__(self, response_string):
self.response_string = response_string
self._buffer = StringIO.StringIO(response_string)
def makefile(self, _mode, _other):
"""Returns the socket's internal buffer"""
return self._buffer
class FakeHttplibConnection(object):
"""A fake httplib.HTTPConnection for boto to use
requests made via this connection actually get translated and routed into
our WSGI app, we then wait for the response and turn it back into
the HTTPResponse that boto expects.
"""
def __init__(self, app, host, is_secure=False):
self.app = app
self.host = host
def request(self, method, path, data, headers):
req = webob.Request.blank(path)
req.method = method
req.body = data
req.headers = headers
req.headers['Accept'] = 'text/html'
req.host = self.host
# Call the WSGI app, get the HTTP response
resp = str(req.get_response(self.app))
# For some reason, the response doesn't have "HTTP/1.0 " prepended; I
# guess that's a function the web server usually provides.
resp = "HTTP/1.0 %s" % resp
self.sock = FakeHttplibSocket(resp)
self.http_response = HTTPResponse(self.sock)
# NOTE(vish): boto is accessing private variables for some reason
self._HTTPConnection__response = self.http_response
self.http_response.begin()
def getresponse(self):
return self.http_response
def getresponsebody(self):
return self.sock.response_string
def close(self):
"""Required for compatibility with boto/tornado"""
pass
class XmlConversionTestCase(test.TestCase):
"""Unit test api xml conversion"""
def test_number_conversion(self):
conv = ec2utils._try_convert
self.assertEqual(conv('None'), None)
self.assertEqual(conv('True'), True)
self.assertEqual(conv('TRUE'), True)
self.assertEqual(conv('true'), True)
self.assertEqual(conv('False'), False)
self.assertEqual(conv('FALSE'), False)
self.assertEqual(conv('false'), False)
self.assertEqual(conv('0'), 0)
self.assertEqual(conv('42'), 42)
self.assertEqual(conv('3.14'), 3.14)
self.assertEqual(conv('-57.12'), -57.12)
self.assertEqual(conv('0x57'), 0x57)
self.assertEqual(conv('-0x57'), -0x57)
self.assertEqual(conv('-'), '-')
self.assertEqual(conv('-0'), 0)
self.assertEqual(conv('0.0'), 0.0)
self.assertEqual(conv('1e-8'), 0.0)
self.assertEqual(conv('-1e-8'), 0.0)
self.assertEqual(conv('0xDD8G'), '0xDD8G')
self.assertEqual(conv('0XDD8G'), '0XDD8G')
self.assertEqual(conv('-stringy'), '-stringy')
self.assertEqual(conv('stringy'), 'stringy')
self.assertEqual(conv('add'), 'add')
self.assertEqual(conv('remove'), 'remove')
self.assertEqual(conv(''), '')
class Ec2utilsTestCase(test.TestCase):
def test_ec2_id_to_id(self):
self.assertEqual(ec2utils.ec2_id_to_id('i-0000001e'), 30)
self.assertEqual(ec2utils.ec2_id_to_id('ami-1d'), 29)
self.assertEqual(ec2utils.ec2_id_to_id('snap-0000001c'), 28)
self.assertEqual(ec2utils.ec2_id_to_id('vol-0000001b'), 27)
def test_bad_ec2_id(self):
self.assertRaises(exception.InvalidEc2Id,
ec2utils.ec2_id_to_id,
'badone')
def test_id_to_ec2_id(self):
self.assertEqual(ec2utils.id_to_ec2_id(30), 'i-0000001e')
self.assertEqual(ec2utils.id_to_ec2_id(29, 'ami-%08x'), 'ami-0000001d')
self.assertEqual(ec2utils.id_to_ec2_snap_id(28), 'snap-0000001c')
self.assertEqual(ec2utils.id_to_ec2_vol_id(27), 'vol-0000001b')
def test_dict_from_dotted_str(self):
in_str = [('BlockDeviceMapping.1.DeviceName', '/dev/sda1'),
('BlockDeviceMapping.1.Ebs.SnapshotId', 'snap-0000001c'),
('BlockDeviceMapping.1.Ebs.VolumeSize', '80'),
('BlockDeviceMapping.1.Ebs.DeleteOnTermination', 'false'),
('BlockDeviceMapping.2.DeviceName', '/dev/sdc'),
('BlockDeviceMapping.2.VirtualName', 'ephemeral0')]
expected_dict = {
'block_device_mapping': {
'1': {'device_name': '/dev/sda1',
'ebs': {'snapshot_id': 'snap-0000001c',
'volume_size': 80,
'delete_on_termination': False}},
'2': {'device_name': '/dev/sdc',
'virtual_name': 'ephemeral0'}}}
out_dict = ec2utils.dict_from_dotted_str(in_str)
self.assertDictMatch(out_dict, expected_dict)
def test_properties_root_defice_name(self):
mappings = [{"device": "/dev/sda1", "virtual": "root"}]
properties0 = {'mappings': mappings}
properties1 = {'root_device_name': '/dev/sdb', 'mappings': mappings}
root_device_name = block_device.properties_root_device_name(
properties0)
self.assertEqual(root_device_name, '/dev/sda1')
root_device_name = block_device.properties_root_device_name(
properties1)
self.assertEqual(root_device_name, '/dev/sdb')
def test_mapping_prepend_dev(self):
mappings = [
{'virtual': 'ami',
'device': 'sda1'},
{'virtual': 'root',
'device': '/dev/sda1'},
{'virtual': 'swap',
'device': 'sdb1'},
{'virtual': 'swap',
'device': '/dev/sdb2'},
{'virtual': 'ephemeral0',
'device': 'sdc1'},
{'virtual': 'ephemeral1',
'device': '/dev/sdc1'}]
expected_result = [
{'virtual': 'ami',
'device': 'sda1'},
{'virtual': 'root',
'device': '/dev/sda1'},
{'virtual': 'swap',
'device': '/dev/sdb1'},
{'virtual': 'swap',
'device': '/dev/sdb2'},
{'virtual': 'ephemeral0',
'device': '/dev/sdc1'},
{'virtual': 'ephemeral1',
'device': '/dev/sdc1'}]
self.assertDictListMatch(block_device.mappings_prepend_dev(mappings),
expected_result)
class ApiEc2TestCase(test.TestCase):
"""Unit test for the cloud controller on an EC2 API"""
def setUp(self):
super(ApiEc2TestCase, self).setUp()
self.host = '127.0.0.1'
# NOTE(vish): skipping the Authorizer
roles = ['sysadmin', 'netadmin']
ctxt = context.RequestContext('fake', 'fake', roles=roles)
self.app = auth.InjectContext(ctxt, ec2.FaultWrapper(
ec2.RequestLogging(ec2.Requestify(ec2.Authorizer(ec2.Executor()
), 'nova.api.ec2.cloud.CloudController'))))
def expect_http(self, host=None, is_secure=False, api_version=None):
"""Returns a new EC2 connection"""
self.ec2 = boto.connect_ec2(
aws_access_key_id='fake',
aws_secret_access_key='fake',
is_secure=False,
region=regioninfo.RegionInfo(None, 'test', self.host),
port=8773,
path='/services/Cloud')
if api_version:
self.ec2.APIVersion = api_version
self.mox.StubOutWithMock(self.ec2, 'new_http_connection')
self.http = FakeHttplibConnection(
self.app, '%s:8773' % (self.host), False)
# pylint: disable=E1103
if boto.Version >= '2':
self.ec2.new_http_connection(host or '%s:8773' % (self.host),
is_secure).AndReturn(self.http)
else:
self.ec2.new_http_connection(host, is_secure).AndReturn(self.http)
return self.http
def test_return_valid_isoformat(self):
"""
Ensure that the ec2 api returns datetime in xs:dateTime
(which apparently isn't datetime.isoformat())
NOTE(ken-pepple): https://bugs.launchpad.net/nova/+bug/721297
"""
conv = apirequest._database_to_isoformat
# sqlite database representation with microseconds
time_to_convert = timeutils.parse_strtime("2011-02-21 20:14:10.634276",
"%Y-%m-%d %H:%M:%S.%f")
self.assertEqual(conv(time_to_convert), '2011-02-21T20:14:10.634Z')
# mysqlite database representation
time_to_convert = timeutils.parse_strtime("2011-02-21 19:56:18",
"%Y-%m-%d %H:%M:%S")
self.assertEqual(conv(time_to_convert), '2011-02-21T19:56:18.000Z')
def test_xmlns_version_matches_request_version(self):
self.expect_http(api_version='2010-10-30')
self.mox.ReplayAll()
# Any request should be fine
self.ec2.get_all_instances()
self.assertTrue(self.ec2.APIVersion in self.http.getresponsebody(),
'The version in the xmlns of the response does '
'not match the API version given in the request.')
def test_describe_instances(self):
"""Test that, after creating a user and a project, the describe
instances call to the API works properly"""
self.expect_http()
self.mox.ReplayAll()
self.assertEqual(self.ec2.get_all_instances(), [])
def test_terminate_invalid_instance(self):
"""Attempt to terminate an invalid instance"""
self.expect_http()
self.mox.ReplayAll()
self.assertRaises(boto_exc.EC2ResponseError,
self.ec2.terminate_instances, "i-00000005")
def test_get_all_key_pairs(self):
"""Test that, after creating a user and project and generating
a key pair, that the API call to list key pairs works properly"""
keyname = "".join(random.choice("sdiuisudfsdcnpaqwertasd")
for x in range(random.randint(4, 8)))
self.expect_http()
self.mox.ReplayAll()
self.ec2.create_key_pair(keyname)
rv = self.ec2.get_all_key_pairs()
results = [k for k in rv if k.name == keyname]
self.assertEquals(len(results), 1)
def test_create_duplicate_key_pair(self):
"""Test that, after successfully generating a keypair,
requesting a second keypair with the same name fails sanely"""
self.expect_http()
self.mox.ReplayAll()
self.ec2.create_key_pair('test')
try:
self.ec2.create_key_pair('test')
except boto_exc.EC2ResponseError, e:
if e.code == 'KeyPairExists':
pass
else:
self.fail("Unexpected EC2ResponseError: %s "
"(expected KeyPairExists)" % e.code)
else:
self.fail('Exception not raised.')
def test_get_all_security_groups(self):
"""Test that we can retrieve security groups"""
self.expect_http()
self.mox.ReplayAll()
rv = self.ec2.get_all_security_groups()
self.assertEquals(len(rv), 1)
self.assertEquals(rv[0].name, 'default')
def test_create_delete_security_group(self):
"""Test that we can create a security group"""
self.expect_http()
self.mox.ReplayAll()
security_group_name = "".join(random.choice("sdiuisudfsdcnpaqwertasd")
for x in range(random.randint(4, 8)))
self.ec2.create_security_group(security_group_name, 'test group')
self.expect_http()
self.mox.ReplayAll()
rv = self.ec2.get_all_security_groups()
self.assertEquals(len(rv), 2)
self.assertTrue(security_group_name in [group.name for group in rv])
self.expect_http()
self.mox.ReplayAll()
self.ec2.delete_security_group(security_group_name)
def test_group_name_valid_chars_security_group(self):
""" Test that we sanely handle invalid security group names.
EC2 API Spec states we should only accept alphanumeric characters,
spaces, dashes, and underscores. Amazon implementation
accepts more characters - so, [:print:] is ok. """
bad_strict_ec2 = "aa \t\x01\x02\x7f"
bad_amazon_ec2 = "aa #^% -=99"
test_raise = [
(True, bad_amazon_ec2, "test desc"),
(True, "test name", bad_amazon_ec2),
(False, bad_strict_ec2, "test desc"),
]
for test in test_raise:
self.expect_http()
self.mox.ReplayAll()
self.flags(ec2_strict_validation=test[0])
self.assertRaises(boto_exc.EC2ResponseError,
self.ec2.create_security_group,
test[1],
test[2])
test_accept = [
(False, bad_amazon_ec2, "test desc"),
(False, "test name", bad_amazon_ec2),
]
for test in test_accept:
self.expect_http()
self.mox.ReplayAll()
self.flags(ec2_strict_validation=test[0])
self.ec2.create_security_group(test[1], test[2])
self.expect_http()
self.mox.ReplayAll()
self.ec2.delete_security_group(test[1])
def test_group_name_valid_length_security_group(self):
"""Test that we sanely handle invalid security group names.
API Spec states that the length should not exceed 255 chars """
self.expect_http()
self.mox.ReplayAll()
# Test block group_name > 255 chars
security_group_name = "".join(random.choice("poiuytrewqasdfghjklmnbvc")
for x in range(random.randint(256, 266)))
self.assertRaises(boto_exc.EC2ResponseError,
self.ec2.create_security_group,
security_group_name,
'test group')
def test_authorize_revoke_security_group_cidr(self):
"""
Test that we can add and remove CIDR based rules
to a security group
"""
self.expect_http()
self.mox.ReplayAll()
security_group_name = "".join(random.choice("sdiuisudfsdcnpaqwertasd")
for x in range(random.randint(4, 8)))
group = self.ec2.create_security_group(security_group_name,
'test group')
self.expect_http()
self.mox.ReplayAll()
group.connection = self.ec2
group.authorize('tcp', 80, 81, '0.0.0.0/0')
group.authorize('icmp', -1, -1, '0.0.0.0/0')
group.authorize('udp', 80, 81, '0.0.0.0/0')
group.authorize('tcp', 1, 65535, '0.0.0.0/0')
group.authorize('udp', 1, 65535, '0.0.0.0/0')
group.authorize('icmp', 1, 0, '0.0.0.0/0')
group.authorize('icmp', 0, 1, '0.0.0.0/0')
group.authorize('icmp', 0, 0, '0.0.0.0/0')
def _assert(message, *args):
try:
group.authorize(*args)
except boto_exc.EC2ResponseError as e:
self.assertEqual(e.status, 400, 'Expected status to be 400')
self.assertIn(message, e.error_message, e.error_message)
else:
raise self.failureException, 'EC2ResponseError not raised'
# Invalid CIDR address
_assert('Invalid CIDR', 'tcp', 80, 81, '0.0.0.0/0444')
# Missing ports
_assert('Not enough parameters', 'tcp', '0.0.0.0/0')
# from port cannot be greater than to port
_assert('Invalid port range', 'tcp', 100, 1, '0.0.0.0/0')
# For tcp, negative values are not allowed
_assert('Invalid port range', 'tcp', -1, 1, '0.0.0.0/0')
# For tcp, valid port range 1-65535
_assert('Invalid port range', 'tcp', 1, 65599, '0.0.0.0/0')
# Invalid Cidr for ICMP type
_assert('Invalid CIDR', 'icmp', -1, -1, '0.0.444.0/4')
# Invalid protocol
_assert('An unknown error has occurred', 'xyz', 1, 14, '0.0.0.0/0')
# Invalid port
_assert('An unknown error has occurred', 'tcp', " ", "81", '0.0.0.0/0')
# Invalid icmp port
_assert('An unknown error has occurred', 'icmp', " ", "81",
'0.0.0.0/0')
# Invalid CIDR Address
_assert('Invalid CIDR', 'icmp', -1, -1, '0.0.0.0')
# Invalid CIDR Address
_assert('Invalid CIDR', 'icmp', -1, -1, '0.0.0.0/')
# Invalid Cidr ports
_assert('Invalid port range', 'icmp', 1, 256, '0.0.0.0/0')
self.expect_http()
self.mox.ReplayAll()
rv = self.ec2.get_all_security_groups()
group = [grp for grp in rv if grp.name == security_group_name][0]
self.assertEquals(len(group.rules), 8)
self.assertEquals(int(group.rules[0].from_port), 80)
self.assertEquals(int(group.rules[0].to_port), 81)
self.assertEquals(len(group.rules[0].grants), 1)
self.assertEquals(str(group.rules[0].grants[0]), '0.0.0.0/0')
self.expect_http()
self.mox.ReplayAll()
group.connection = self.ec2
group.revoke('tcp', 80, 81, '0.0.0.0/0')
group.revoke('icmp', -1, -1, '0.0.0.0/0')
group.revoke('udp', 80, 81, '0.0.0.0/0')
group.revoke('tcp', 1, 65535, '0.0.0.0/0')
group.revoke('udp', 1, 65535, '0.0.0.0/0')
group.revoke('icmp', 1, 0, '0.0.0.0/0')
group.revoke('icmp', 0, 1, '0.0.0.0/0')
group.revoke('icmp', 0, 0, '0.0.0.0/0')
self.expect_http()
self.mox.ReplayAll()
self.ec2.delete_security_group(security_group_name)
self.expect_http()
self.mox.ReplayAll()
group.connection = self.ec2
rv = self.ec2.get_all_security_groups()
self.assertEqual(len(rv), 1)
self.assertEqual(rv[0].name, 'default')
def test_authorize_revoke_security_group_cidr_v6(self):
"""
Test that we can add and remove CIDR based rules
to a security group for IPv6
"""
self.expect_http()
self.mox.ReplayAll()
security_group_name = "".join(random.choice("sdiuisudfsdcnpaqwertasd")
for x in range(random.randint(4, 8)))
group = self.ec2.create_security_group(security_group_name,
'test group')
self.expect_http()
self.mox.ReplayAll()
group.connection = self.ec2
group.authorize('tcp', 80, 81, '::/0')
self.expect_http()
self.mox.ReplayAll()
rv = self.ec2.get_all_security_groups()
group = [grp for grp in rv if grp.name == security_group_name][0]
self.assertEquals(len(group.rules), 1)
self.assertEquals(int(group.rules[0].from_port), 80)
self.assertEquals(int(group.rules[0].to_port), 81)
self.assertEquals(len(group.rules[0].grants), 1)
self.assertEquals(str(group.rules[0].grants[0]), '::/0')
self.expect_http()
self.mox.ReplayAll()
group.connection = self.ec2
group.revoke('tcp', 80, 81, '::/0')
self.expect_http()
self.mox.ReplayAll()
self.ec2.delete_security_group(security_group_name)
self.expect_http()
self.mox.ReplayAll()
group.connection = self.ec2
rv = self.ec2.get_all_security_groups()
self.assertEqual(len(rv), 1)
self.assertEqual(rv[0].name, 'default')
def test_authorize_revoke_security_group_foreign_group(self):
"""
Test that we can grant and revoke another security group access
to a security group
"""
self.expect_http()
self.mox.ReplayAll()
rand_string = 'sdiuisudfsdcnpaqwertasd'
security_group_name = "".join(random.choice(rand_string)
for x in range(random.randint(4, 8)))
other_security_group_name = "".join(random.choice(rand_string)
for x in range(random.randint(4, 8)))
group = self.ec2.create_security_group(security_group_name,
'test group')
self.expect_http()
self.mox.ReplayAll()
other_group = self.ec2.create_security_group(other_security_group_name,
'some other group')
self.expect_http()
self.mox.ReplayAll()
group.connection = self.ec2
group.authorize(src_group=other_group)
self.expect_http()
self.mox.ReplayAll()
rv = self.ec2.get_all_security_groups()
# I don't bother checkng that we actually find it here,
# because the create/delete unit test further up should
# be good enough for that.
for group in rv:
if group.name == security_group_name:
self.assertEquals(len(group.rules), 3)
self.assertEquals(len(group.rules[0].grants), 1)
self.assertEquals(str(group.rules[0].grants[0]), '%s-%s' %
(other_security_group_name, 'fake'))
self.expect_http()
self.mox.ReplayAll()
rv = self.ec2.get_all_security_groups()
for group in rv:
if group.name == security_group_name:
self.expect_http()
self.mox.ReplayAll()
group.connection = self.ec2
group.revoke(src_group=other_group)
self.expect_http()
self.mox.ReplayAll()
self.ec2.delete_security_group(security_group_name)
self.ec2.delete_security_group(other_security_group_name)
| {
"content_hash": "fe67d73d10e30ae7995999c8db28ba4b",
"timestamp": "",
"source": "github",
"line_count": 598,
"max_line_length": 79,
"avg_line_length": 37.68561872909699,
"alnum_prop": 0.5705981540646078,
"repo_name": "usc-isi/nova",
"id": "4a426070533b4390f8d2966d40d4072ef5034627",
"size": "23313",
"binary": false,
"copies": "1",
"ref": "refs/heads/hpc-trunk",
"path": "nova/tests/test_api.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "16002"
},
{
"name": "JavaScript",
"bytes": "7403"
},
{
"name": "Python",
"bytes": "7282590"
},
{
"name": "Shell",
"bytes": "42905"
}
],
"symlink_target": ""
} |
"""Parameter optimizer."""
__all__ = ['Trainer']
from .. import optimizer as opt
from ..model import _create_kvstore
from .parameter import ParameterDict, Parameter
class Trainer(object):
"""Applies an `Optimizer` on a set of Parameters. Trainer should
be used together with `autograd`.
Parameters
----------
params : ParameterDict
The set of parameters to optimize.
optimizer : str or Optimizer
The optimizer to use. See
`help <http://mxnet.io/api/python/optimization/optimization.html#the-mxnet-optimizer-package>`_
on Optimizer for a list of available optimizers.
optimizer_params : dict
Key-word arguments to be passed to optimizer constructor. For example,
`{'learning_rate': 0.1}`. All optimizers accept learning_rate, wd (weight decay),
clip_gradient, and lr_scheduler. See each optimizer's
constructor for a list of additional supported arguments.
kvstore : str or KVStore
kvstore type for multi-gpu and distributed training. See help on
:any:`mxnet.kvstore.create` for more information.
compression_params : dict
Specifies type of gradient compression and additional arguments depending
on the type of compression being used. For example, 2bit compression requires a threshold.
Arguments would then be {'type':'2bit', 'threshold':0.5}
See mxnet.KVStore.set_gradient_compression method for more details on gradient compression.
Properties
----------
learning_rate : float
The current learning rate of the optimizer. Given an Optimizer object
optimizer, its learning rate can be accessed as optimizer.learning_rate.
"""
def __init__(self, params, optimizer, optimizer_params=None, kvstore='device',
compression_params=None):
if isinstance(params, (dict, ParameterDict)):
params = list(params.values())
if not isinstance(params, (list, tuple)):
raise ValueError(
"First argument must be a list or dict of Parameters, " \
"got %s."%(type(params)))
self._params = []
for param in params:
if not isinstance(param, Parameter):
raise ValueError(
"First argument must be a list or dict of Parameters, " \
"got list of %s."%(type(param)))
self._params.append(param)
self._compression_params = compression_params
optimizer_params = optimizer_params if optimizer_params else {}
self._scale = optimizer_params.get('rescale_grad', 1.0)
self._contexts = self._check_contexts()
self._init_optimizer(optimizer, optimizer_params)
self._kv_initialized = False
self._kvstore = kvstore
def _check_contexts(self):
contexts = None
for param in self._params:
ctx = param.list_ctx()
assert contexts is None or contexts == ctx, \
"All Parameters must be initialized on the same set of contexts, " \
"but Parameter %s is initialized on %s while previous Parameters " \
"are initialized on %s."%(param.name, str(ctx), str(contexts))
contexts = ctx
return contexts
def _init_optimizer(self, optimizer, optimizer_params):
param_dict = {i: param for i, param in enumerate(self._params)}
if isinstance(optimizer, opt.Optimizer):
assert not optimizer_params, \
"optimizer_params must be None if optimizer is an instance of " \
"Optimizer instead of str"
self._optimizer = optimizer
self._optimizer.param_dict = param_dict
else:
self._optimizer = opt.create(optimizer, param_dict=param_dict,
**optimizer_params)
self._updaters = [opt.get_updater(self._optimizer) \
for _ in self._contexts]
def _init_kvstore(self):
arg_arrays = {param.name: param.data(self._contexts[0]) for param in self._params}
kvstore, update_on_kvstore = _create_kvstore(self._kvstore, len(self._contexts),
arg_arrays)
if kvstore:
if self._compression_params:
kvstore.set_gradient_compression(self._compression_params)
if 'dist' in kvstore.type:
update_on_kvstore = False
if update_on_kvstore:
kvstore.set_optimizer(self._optimizer)
# optimizer preferably needs to be set before init for multiprecision
for i, param in enumerate(self._params):
param_arrays = param.list_data()
kvstore.init(i, param_arrays[0])
kvstore.pull(i, param_arrays, priority=-i)
self._kvstore = kvstore
self._update_on_kvstore = update_on_kvstore
else:
self._kvstore = None
self._update_on_kvstore = None
self._kv_initialized = True
@property
def learning_rate(self):
if not isinstance(self._optimizer, opt.Optimizer):
raise UserWarning("Optimizer has to be defined before its learning "
"rate can be accessed.")
else:
return self._optimizer.learning_rate
def set_learning_rate(self, lr):
"""Sets a new learning rate of the optimizer.
Parameters
----------
lr : float
The new learning rate of the optimizer.
"""
if not isinstance(self._optimizer, opt.Optimizer):
raise UserWarning("Optimizer has to be defined before its learning "
"rate is mutated.")
else:
self._optimizer.set_learning_rate(lr)
def step(self, batch_size, ignore_stale_grad=False):
"""Makes one step of parameter update. Should be called after
`autograd.compute_gradient` and outside of `record()` scope.
Parameters
----------
batch_size : int
Batch size of data processed. Gradient will be normalized by `1/batch_size`.
Set this to 1 if you normalized loss manually with `loss = mean(loss)`.
ignore_stale_grad : bool, optional, default=False
If true, ignores Parameters with stale gradient (gradient that has not
been updated by `backward` after last step) and skip update.
"""
if not self._kv_initialized:
self._init_kvstore()
self._optimizer.rescale_grad = self._scale / batch_size
for i, param in enumerate(self._params):
if param.grad_req == 'null':
continue
if not ignore_stale_grad:
for data in param.list_data():
if not data._fresh_grad:
raise UserWarning(
"Gradient of Parameter `%s` on context %s has not been updated "
"by backward since last `step`. This could mean a bug in your "
"model that made it only use a subset of the Parameters (Blocks) "
"for this iteration. If you are intentionally only using a subset, "
"call step with ignore_stale_grad=True to suppress this "
"warning and skip updating of Parameters with stale gradient" \
%(param.name, str(data.context)))
if self._kvstore:
self._kvstore.push(i, param.list_grad(), priority=-i)
if self._update_on_kvstore:
self._kvstore.pull(i, param.list_data(), priority=-i)
continue
else:
self._kvstore.pull(i, param.list_grad(), priority=-i)
for upd, arr, grad in zip(self._updaters, param.list_data(), param.list_grad()):
if not ignore_stale_grad or arr._fresh_grad:
upd(i, grad, arr)
arr._fresh_grad = False
def save_states(self, fname):
"""Saves trainer states (e.g. optimizer, momentum) to a file.
Parameters
----------
fname : str
Path to output states file.
"""
assert self._optimizer is not None
if self._update_on_kvstore:
self._kvstore.save_optimizer_states(fname, dump_optimizer=True)
else:
with open(fname, 'wb') as fout:
fout.write(self._updaters[0].get_states(dump_optimizer=True))
def load_states(self, fname):
"""Loads trainer states (e.g. optimizer, momentum) from a file.
Parameters
----------
fname : str
Path to input states file.
"""
if not self._kv_initialized:
self._init_kvstore()
if self._update_on_kvstore:
self._kvstore.load_optimizer_states(fname)
self._optimizer = self._kvstore._updater.optimizer
else:
with open(fname, 'rb') as f:
states = f.read()
for updater in self._updaters:
updater.set_states(states)
updater.optimizer = self._updaters[0].optimizer
self._optimizer = self._updaters[0].optimizer
| {
"content_hash": "fca699ce71483a907ce8200f22c4c226",
"timestamp": "",
"source": "github",
"line_count": 220,
"max_line_length": 103,
"avg_line_length": 42.67272727272727,
"alnum_prop": 0.5749893481039625,
"repo_name": "TuSimple/mxnet",
"id": "e730fd7cd8bdd668b5b5849a0cd4bd4177c06882",
"size": "10222",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/mxnet/gluon/trainer.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "1731"
},
{
"name": "Batchfile",
"bytes": "13130"
},
{
"name": "C",
"bytes": "122099"
},
{
"name": "C++",
"bytes": "5340824"
},
{
"name": "CMake",
"bytes": "80796"
},
{
"name": "Cuda",
"bytes": "963477"
},
{
"name": "Dockerfile",
"bytes": "24811"
},
{
"name": "Groovy",
"bytes": "1020"
},
{
"name": "HTML",
"bytes": "40277"
},
{
"name": "Java",
"bytes": "122297"
},
{
"name": "Jupyter Notebook",
"bytes": "1275177"
},
{
"name": "MATLAB",
"bytes": "34903"
},
{
"name": "Makefile",
"bytes": "68249"
},
{
"name": "Perl",
"bytes": "1256723"
},
{
"name": "Perl 6",
"bytes": "7280"
},
{
"name": "Python",
"bytes": "5417311"
},
{
"name": "R",
"bytes": "311544"
},
{
"name": "Scala",
"bytes": "988309"
},
{
"name": "Shell",
"bytes": "276038"
},
{
"name": "Smalltalk",
"bytes": "3497"
}
],
"symlink_target": ""
} |
import functools
import httplib as http
import itertools
from operator import itemgetter
from dateutil.parser import parse as parse_date
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.utils import timezone
from flask import request, redirect
import pytz
from framework.database import get_or_http_error, autoload
from framework.exceptions import HTTPError
from framework.status import push_status_message
from osf.utils.sanitize import strip_html
from osf.utils.permissions import ADMIN
from osf.models import NodeLog, MetaSchema, DraftRegistration, Sanction
from api.base.utils import rapply
from website.exceptions import NodeStateError
from website.project.decorators import (
must_be_valid_project,
must_have_permission,
http_error_if_disk_saving_mode
)
from website import language, settings
from website.ember_osf_web.decorators import ember_flag_is_active
from website.prereg import utils as prereg_utils
from website.project import utils as project_utils
from website.project.metadata.schemas import LATEST_SCHEMA_VERSION, METASCHEMA_ORDERING
from website.project.metadata.utils import serialize_meta_schema, serialize_draft_registration
from website.project.utils import serialize_node
get_schema_or_fail = lambda query: get_or_http_error(MetaSchema, query)
autoload_draft = functools.partial(autoload, DraftRegistration, 'draft_id', 'draft')
def must_be_branched_from_node(func):
@autoload_draft
@must_be_valid_project
@functools.wraps(func)
def wrapper(*args, **kwargs):
node = kwargs['node']
draft = kwargs['draft']
if draft.deleted:
raise HTTPError(http.GONE)
if not draft.branched_from._id == node._id:
raise HTTPError(
http.BAD_REQUEST,
data={
'message_short': 'Not a draft of this node',
'message_long': 'This draft registration is not created from the given node.'
}
)
return func(*args, **kwargs)
return wrapper
def validate_embargo_end_date(end_date_string, node):
"""
Our reviewers have a window of time in which to review a draft reg. submission.
If an embargo end_date that is within that window is at risk of causing
validation errors down the line if the draft is approved and registered.
The draft registration approval window is always greater than the time span
for disallowed embargo end dates.
:raises: HTTPError if end_date is less than the approval window or greater than the
max embargo end date
"""
end_date = parse_date(end_date_string, ignoretz=True).replace(tzinfo=pytz.utc)
today = timezone.now()
if (end_date - today) <= settings.DRAFT_REGISTRATION_APPROVAL_PERIOD:
raise HTTPError(http.BAD_REQUEST, data={
'message_short': 'Invalid embargo end date',
'message_long': 'Embargo end date for this submission must be at least {0} days in the future.'.format(settings.DRAFT_REGISTRATION_APPROVAL_PERIOD)
})
elif not node._is_embargo_date_valid(end_date):
max_end_date = today + settings.DRAFT_REGISTRATION_APPROVAL_PERIOD
raise HTTPError(http.BAD_REQUEST, data={
'message_short': 'Invalid embargo end date',
'message_long': 'Embargo end date must on or before {0}.'.format(max_end_date.isoformat())
})
def validate_registration_choice(registration_choice):
if registration_choice not in ('embargo', 'immediate'):
raise HTTPError(
http.BAD_REQUEST,
data={
'message_short': "Invalid 'registrationChoice'",
'message_long': "Values for 'registrationChoice' must be either 'embargo' or 'immediate'."
}
)
def check_draft_state(draft):
registered_and_deleted = draft.registered_node and draft.registered_node.is_deleted
if draft.registered_node and not registered_and_deleted:
raise HTTPError(http.FORBIDDEN, data={
'message_short': 'This draft has already been registered',
'message_long': 'This draft has already been registered and cannot be modified.'
})
if draft.is_pending_review:
raise HTTPError(http.FORBIDDEN, data={
'message_short': 'This draft is pending review',
'message_long': 'This draft is pending review and cannot be modified.'
})
if draft.requires_approval and draft.is_approved and (not registered_and_deleted):
raise HTTPError(http.FORBIDDEN, data={
'message_short': 'This draft has already been approved',
'message_long': 'This draft has already been approved and cannot be modified.'
})
@must_have_permission(ADMIN)
@must_be_branched_from_node
def submit_draft_for_review(auth, node, draft, *args, **kwargs):
"""Submit for approvals and/or notifications
:return: serialized registration
:rtype: dict
:raises: HTTPError if embargo end date is invalid
"""
data = request.get_json()
meta = {}
registration_choice = data.get('registrationChoice', 'immediate')
validate_registration_choice(registration_choice)
if registration_choice == 'embargo':
# Initiate embargo
end_date_string = data['embargoEndDate']
validate_embargo_end_date(end_date_string, node)
meta['embargo_end_date'] = end_date_string
meta['registration_choice'] = registration_choice
if draft.registered_node and not draft.registered_node.is_deleted:
raise HTTPError(http.BAD_REQUEST, data=dict(message_long='This draft has already been registered, if you wish to '
'register it again or submit it for review please create '
'a new draft.'))
# Don't allow resubmission unless submission was rejected
if draft.approval and draft.approval.state != Sanction.REJECTED:
raise HTTPError(http.CONFLICT, data=dict(message_long='Cannot resubmit previously submitted draft.'))
draft.submit_for_review(
initiated_by=auth.user,
meta=meta,
save=True
)
if prereg_utils.get_prereg_schema() == draft.registration_schema:
node.add_log(
action=NodeLog.PREREG_REGISTRATION_INITIATED,
params={'node': node._primary_key},
auth=auth,
save=False
)
node.save()
push_status_message(language.AFTER_SUBMIT_FOR_REVIEW,
kind='info',
trust=False)
return {
'status': 'initiated',
'urls': {
'registrations': node.web_url_for('node_registrations')
}
}, http.ACCEPTED
@must_have_permission(ADMIN)
@must_be_branched_from_node
def draft_before_register_page(auth, node, draft, *args, **kwargs):
"""Allow the user to select an embargo period and confirm registration
:return: serialized Node + DraftRegistration
:rtype: dict
"""
ret = serialize_node(node, auth, primary=True)
ret['draft'] = serialize_draft_registration(draft, auth)
return ret
@must_have_permission(ADMIN)
@must_be_branched_from_node
@http_error_if_disk_saving_mode
def register_draft_registration(auth, node, draft, *args, **kwargs):
"""Initiate a registration from a draft registration
:return: success message; url to registrations page
:rtype: dict
"""
data = request.get_json()
registration_choice = data.get('registrationChoice', 'immediate')
validate_registration_choice(registration_choice)
# Don't allow resubmission unless submission was rejected
if draft.approval and draft.approval.state != Sanction.REJECTED:
raise HTTPError(http.CONFLICT, data=dict(message_long='Cannot resubmit previously submitted draft.'))
register = draft.register(auth)
draft.save()
if registration_choice == 'embargo':
# Initiate embargo
embargo_end_date = parse_date(data['embargoEndDate'], ignoretz=True).replace(tzinfo=pytz.utc)
try:
register.embargo_registration(auth.user, embargo_end_date)
except ValidationError as err:
raise HTTPError(http.BAD_REQUEST, data=dict(message_long=err.message))
else:
try:
register.require_approval(auth.user)
except NodeStateError as err:
raise HTTPError(http.BAD_REQUEST, data=dict(message_long=err.message))
register.save()
push_status_message(language.AFTER_REGISTER_ARCHIVING,
kind='info',
trust=False)
return {
'status': 'initiated',
'urls': {
'registrations': node.web_url_for('node_registrations')
}
}, http.ACCEPTED
@must_have_permission(ADMIN)
@must_be_branched_from_node
def get_draft_registration(auth, node, draft, *args, **kwargs):
"""Return a single draft registration
:return: serialized draft registration
:rtype: dict
"""
return serialize_draft_registration(draft, auth), http.OK
@must_have_permission(ADMIN)
@must_be_valid_project
def get_draft_registrations(auth, node, *args, **kwargs):
"""List draft registrations for a node
:return: serialized draft registrations
:rtype: dict
"""
#'updated': '2016-08-03T14:24:12Z'
count = request.args.get('count', 100)
drafts = itertools.islice(node.draft_registrations_active, 0, count)
serialized_drafts = [serialize_draft_registration(d, auth) for d in drafts]
sorted_serialized_drafts = sorted(serialized_drafts, key=itemgetter('updated'), reverse=True)
return {
'drafts': sorted_serialized_drafts
}, http.OK
@must_have_permission(ADMIN)
@must_be_valid_project
@ember_flag_is_active('ember_create_draft_registration_page')
def new_draft_registration(auth, node, *args, **kwargs):
"""Create a new draft registration for the node
:return: Redirect to the new draft's edit page
:rtype: flask.redirect
:raises: HTTPError
"""
if node.is_registration:
raise HTTPError(http.FORBIDDEN, data={
'message_short': "Can't create draft",
'message_long': 'Creating draft registrations on registered projects is not allowed.'
})
data = request.values
schema_name = data.get('schema_name')
if not schema_name:
raise HTTPError(
http.BAD_REQUEST,
data={
'message_short': 'Must specify a schema_name',
'message_long': 'Please specify a schema_name'
}
)
schema_version = data.get('schema_version', 2)
meta_schema = get_schema_or_fail(Q(name=schema_name, schema_version=int(schema_version)))
draft = DraftRegistration.create_from_node(
node,
user=auth.user,
schema=meta_schema,
data={}
)
return redirect(node.web_url_for('edit_draft_registration_page', draft_id=draft._id))
@must_have_permission(ADMIN)
@ember_flag_is_active('ember_edit_draft_registration_page')
@must_be_branched_from_node
def edit_draft_registration_page(auth, node, draft, **kwargs):
"""Draft registration editor
:return: serialized DraftRegistration
:rtype: dict
"""
check_draft_state(draft)
ret = project_utils.serialize_node(node, auth, primary=True)
ret['draft'] = serialize_draft_registration(draft, auth)
return ret
@must_have_permission(ADMIN)
@must_be_branched_from_node
def update_draft_registration(auth, node, draft, *args, **kwargs):
"""Update an existing draft registration
:return: serialized draft registration
:rtype: dict
:raises: HTTPError
"""
check_draft_state(draft)
data = request.get_json()
schema_data = data.get('schema_data', {})
schema_data = rapply(schema_data, strip_html)
schema_name = data.get('schema_name')
schema_version = data.get('schema_version', 1)
if schema_name:
meta_schema = get_schema_or_fail(Q(name=schema_name, schema_version=schema_version))
existing_schema = draft.registration_schema
if (existing_schema.name, existing_schema.schema_version) != (meta_schema.name, meta_schema.schema_version):
draft.registration_schema = meta_schema
draft.update_metadata(schema_data)
draft.save()
return serialize_draft_registration(draft, auth), http.OK
@must_have_permission(ADMIN)
@must_be_branched_from_node
def delete_draft_registration(auth, node, draft, *args, **kwargs):
"""Permanently delete a draft registration
:return: None
:rtype: NoneType
"""
if draft.registered_node and not draft.registered_node.is_deleted:
raise HTTPError(
http.FORBIDDEN,
data={
'message_short': 'Can\'t delete draft',
'message_long': 'This draft has already been registered and cannot be deleted.'
}
)
draft.deleted = timezone.now()
draft.save(update_fields=['deleted'])
return None, http.NO_CONTENT
def get_metaschemas(*args, **kwargs):
"""
List metaschemas with which a draft registration may be created. Only fetch the newest version for each schema.
:return: serialized metaschemas
:rtype: dict
"""
count = request.args.get('count', 100)
include = request.args.get('include', 'latest')
meta_schemas = MetaSchema.objects.filter(active=True)
if include == 'latest':
meta_schemas.filter(schema_version=LATEST_SCHEMA_VERSION)
meta_schemas = sorted(meta_schemas, key=lambda x: METASCHEMA_ORDERING.index(x.name))
return {
'meta_schemas': [
serialize_meta_schema(ms) for ms in meta_schemas[:count]
]
}, http.OK
| {
"content_hash": "8ed71439ad5b3248fdec5c570e5e2b57",
"timestamp": "",
"source": "github",
"line_count": 374,
"max_line_length": 159,
"avg_line_length": 36.86898395721925,
"alnum_prop": 0.6648052795706723,
"repo_name": "chennan47/osf.io",
"id": "ee606fa73298d2e533b3ab470df66a94bfa1ed3c",
"size": "13789",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "website/project/views/drafts.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "110839"
},
{
"name": "HTML",
"bytes": "236223"
},
{
"name": "JavaScript",
"bytes": "1830647"
},
{
"name": "Mako",
"bytes": "665098"
},
{
"name": "Python",
"bytes": "7650137"
},
{
"name": "VCL",
"bytes": "13885"
}
],
"symlink_target": ""
} |
import datetime
import unittest
from unittest import mock
import pytest
from airflow.exceptions import AirflowException
from airflow.models import DAG, Connection, DagRun, TaskInstance as TI
from airflow.operators.dummy import DummyOperator
from airflow.operators.sql import (
BranchSQLOperator,
SQLCheckOperator,
SQLIntervalCheckOperator,
SQLThresholdCheckOperator,
SQLValueCheckOperator,
)
from airflow.providers.postgres.hooks.postgres import PostgresHook
from airflow.utils import timezone
from airflow.utils.session import create_session
from airflow.utils.state import State
from tests.providers.apache.hive import TestHiveEnvironment
DEFAULT_DATE = timezone.datetime(2016, 1, 1)
INTERVAL = datetime.timedelta(hours=12)
SUPPORTED_TRUE_VALUES = [
["True"],
["true"],
["1"],
["on"],
[1],
True,
"true",
"1",
"on",
1,
]
SUPPORTED_FALSE_VALUES = [
["False"],
["false"],
["0"],
["off"],
[0],
False,
"false",
"0",
"off",
0,
]
@mock.patch(
'airflow.operators.sql.BaseHook.get_connection',
return_value=Connection(conn_id='sql_default', conn_type='postgres'),
)
class TestSQLCheckOperatorDbHook:
def setup_method(self):
self.task_id = "test_task"
self.conn_id = "sql_default"
self._operator = SQLCheckOperator(task_id=self.task_id, conn_id=self.conn_id, sql="sql")
@pytest.mark.parametrize('database', [None, 'test-db'])
def test_get_hook(self, mock_get_conn, database):
if database:
self._operator.database = database
assert isinstance(self._operator._hook, PostgresHook)
assert self._operator._hook.schema == database
mock_get_conn.assert_called_once_with(self.conn_id)
def test_not_allowed_conn_type(self, mock_get_conn):
mock_get_conn.return_value = Connection(conn_id='sql_default', conn_type='s3')
with pytest.raises(AirflowException, match=r"The connection type is not supported"):
self._operator._hook
class TestCheckOperator(unittest.TestCase):
def setUp(self):
self._operator = SQLCheckOperator(task_id="test_task", sql="sql")
@mock.patch.object(SQLCheckOperator, "get_db_hook")
def test_execute_no_records(self, mock_get_db_hook):
mock_get_db_hook.return_value.get_first.return_value = []
with pytest.raises(AirflowException, match=r"The query returned None"):
self._operator.execute()
@mock.patch.object(SQLCheckOperator, "get_db_hook")
def test_execute_not_all_records_are_true(self, mock_get_db_hook):
mock_get_db_hook.return_value.get_first.return_value = ["data", ""]
with pytest.raises(AirflowException, match=r"Test failed."):
self._operator.execute()
class TestValueCheckOperator(unittest.TestCase):
def setUp(self):
self.task_id = "test_task"
self.conn_id = "default_conn"
def _construct_operator(self, sql, pass_value, tolerance=None):
dag = DAG("test_dag", start_date=datetime.datetime(2017, 1, 1))
return SQLValueCheckOperator(
dag=dag,
task_id=self.task_id,
conn_id=self.conn_id,
sql=sql,
pass_value=pass_value,
tolerance=tolerance,
)
def test_pass_value_template_string(self):
pass_value_str = "2018-03-22"
operator = self._construct_operator("select date from tab1;", "{{ ds }}")
operator.render_template_fields({"ds": pass_value_str})
assert operator.task_id == self.task_id
assert operator.pass_value == pass_value_str
def test_pass_value_template_string_float(self):
pass_value_float = 4.0
operator = self._construct_operator("select date from tab1;", pass_value_float)
operator.render_template_fields({})
assert operator.task_id == self.task_id
assert operator.pass_value == str(pass_value_float)
@mock.patch.object(SQLValueCheckOperator, "get_db_hook")
def test_execute_pass(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.return_value = [10]
mock_get_db_hook.return_value = mock_hook
sql = "select value from tab1 limit 1;"
operator = self._construct_operator(sql, 5, 1)
operator.execute(None)
mock_hook.get_first.assert_called_once_with(sql)
@mock.patch.object(SQLValueCheckOperator, "get_db_hook")
def test_execute_fail(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.return_value = [11]
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator("select value from tab1 limit 1;", 5, 1)
with pytest.raises(AirflowException, match="Tolerance:100.0%"):
operator.execute()
class TestIntervalCheckOperator(unittest.TestCase):
def _construct_operator(self, table, metric_thresholds, ratio_formula, ignore_zero):
return SQLIntervalCheckOperator(
task_id="test_task",
table=table,
metrics_thresholds=metric_thresholds,
ratio_formula=ratio_formula,
ignore_zero=ignore_zero,
)
def test_invalid_ratio_formula(self):
with pytest.raises(AirflowException, match="Invalid diff_method"):
self._construct_operator(
table="test_table",
metric_thresholds={
"f1": 1,
},
ratio_formula="abs",
ignore_zero=False,
)
@mock.patch.object(SQLIntervalCheckOperator, "get_db_hook")
def test_execute_not_ignore_zero(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.return_value = [0]
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator(
table="test_table",
metric_thresholds={
"f1": 1,
},
ratio_formula="max_over_min",
ignore_zero=False,
)
with pytest.raises(AirflowException):
operator.execute()
@mock.patch.object(SQLIntervalCheckOperator, "get_db_hook")
def test_execute_ignore_zero(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.return_value = [0]
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator(
table="test_table",
metric_thresholds={
"f1": 1,
},
ratio_formula="max_over_min",
ignore_zero=True,
)
operator.execute()
@mock.patch.object(SQLIntervalCheckOperator, "get_db_hook")
def test_execute_min_max(self, mock_get_db_hook):
mock_hook = mock.Mock()
def returned_row():
rows = [
[2, 2, 2, 2], # reference
[1, 1, 1, 1], # current
]
yield from rows
mock_hook.get_first.side_effect = returned_row()
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator(
table="test_table",
metric_thresholds={
"f0": 1.0,
"f1": 1.5,
"f2": 2.0,
"f3": 2.5,
},
ratio_formula="max_over_min",
ignore_zero=True,
)
with pytest.raises(AirflowException, match="f0, f1, f2"):
operator.execute()
@mock.patch.object(SQLIntervalCheckOperator, "get_db_hook")
def test_execute_diff(self, mock_get_db_hook):
mock_hook = mock.Mock()
def returned_row():
rows = [
[3, 3, 3, 3], # reference
[1, 1, 1, 1], # current
]
yield from rows
mock_hook.get_first.side_effect = returned_row()
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator(
table="test_table",
metric_thresholds={
"f0": 0.5,
"f1": 0.6,
"f2": 0.7,
"f3": 0.8,
},
ratio_formula="relative_diff",
ignore_zero=True,
)
with pytest.raises(AirflowException, match="f0, f1"):
operator.execute()
class TestThresholdCheckOperator(unittest.TestCase):
def _construct_operator(self, sql, min_threshold, max_threshold):
dag = DAG("test_dag", start_date=datetime.datetime(2017, 1, 1))
return SQLThresholdCheckOperator(
task_id="test_task",
sql=sql,
min_threshold=min_threshold,
max_threshold=max_threshold,
dag=dag,
)
@mock.patch.object(SQLThresholdCheckOperator, "get_db_hook")
def test_pass_min_value_max_value(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.return_value = (10,)
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator("Select avg(val) from table1 limit 1", 1, 100)
operator.execute()
@mock.patch.object(SQLThresholdCheckOperator, "get_db_hook")
def test_fail_min_value_max_value(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.return_value = (10,)
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator("Select avg(val) from table1 limit 1", 20, 100)
with pytest.raises(AirflowException, match="10.*20.0.*100.0"):
operator.execute()
@mock.patch.object(SQLThresholdCheckOperator, "get_db_hook")
def test_pass_min_sql_max_sql(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.side_effect = lambda x: (int(x.split()[1]),)
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator("Select 10", "Select 1", "Select 100")
operator.execute()
@mock.patch.object(SQLThresholdCheckOperator, "get_db_hook")
def test_fail_min_sql_max_sql(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.side_effect = lambda x: (int(x.split()[1]),)
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator("Select 10", "Select 20", "Select 100")
with pytest.raises(AirflowException, match="10.*20.*100"):
operator.execute()
@mock.patch.object(SQLThresholdCheckOperator, "get_db_hook")
def test_pass_min_value_max_sql(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.side_effect = lambda x: (int(x.split()[1]),)
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator("Select 75", 45, "Select 100")
operator.execute()
@mock.patch.object(SQLThresholdCheckOperator, "get_db_hook")
def test_fail_min_sql_max_value(self, mock_get_db_hook):
mock_hook = mock.Mock()
mock_hook.get_first.side_effect = lambda x: (int(x.split()[1]),)
mock_get_db_hook.return_value = mock_hook
operator = self._construct_operator("Select 155", "Select 45", 100)
with pytest.raises(AirflowException, match="155.*45.*100.0"):
operator.execute()
class TestSqlBranch(TestHiveEnvironment, unittest.TestCase):
"""
Test for SQL Branch Operator
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
with create_session() as session:
session.query(DagRun).delete()
session.query(TI).delete()
def setUp(self):
super().setUp()
self.dag = DAG(
"sql_branch_operator_test",
default_args={"owner": "airflow", "start_date": DEFAULT_DATE},
schedule_interval=INTERVAL,
)
self.branch_1 = DummyOperator(task_id="branch_1", dag=self.dag)
self.branch_2 = DummyOperator(task_id="branch_2", dag=self.dag)
self.branch_3 = None
def tearDown(self):
super().tearDown()
with create_session() as session:
session.query(DagRun).delete()
session.query(TI).delete()
def test_unsupported_conn_type(self):
"""Check if BranchSQLOperator throws an exception for unsupported connection type"""
op = BranchSQLOperator(
task_id="make_choice",
conn_id="redis_default",
sql="SELECT count(1) FROM INFORMATION_SCHEMA.TABLES",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
with pytest.raises(AirflowException):
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
def test_invalid_conn(self):
"""Check if BranchSQLOperator throws an exception for invalid connection"""
op = BranchSQLOperator(
task_id="make_choice",
conn_id="invalid_connection",
sql="SELECT count(1) FROM INFORMATION_SCHEMA.TABLES",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
with pytest.raises(AirflowException):
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
def test_invalid_follow_task_true(self):
"""Check if BranchSQLOperator throws an exception for invalid connection"""
op = BranchSQLOperator(
task_id="make_choice",
conn_id="invalid_connection",
sql="SELECT count(1) FROM INFORMATION_SCHEMA.TABLES",
follow_task_ids_if_true=None,
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
with pytest.raises(AirflowException):
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
def test_invalid_follow_task_false(self):
"""Check if BranchSQLOperator throws an exception for invalid connection"""
op = BranchSQLOperator(
task_id="make_choice",
conn_id="invalid_connection",
sql="SELECT count(1) FROM INFORMATION_SCHEMA.TABLES",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false=None,
dag=self.dag,
)
with pytest.raises(AirflowException):
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
@pytest.mark.backend("mysql")
def test_sql_branch_operator_mysql(self):
"""Check if BranchSQLOperator works with backend"""
branch_op = BranchSQLOperator(
task_id="make_choice",
conn_id="mysql_default",
sql="SELECT 1",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
branch_op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
@pytest.mark.backend("postgres")
def test_sql_branch_operator_postgres(self):
"""Check if BranchSQLOperator works with backend"""
branch_op = BranchSQLOperator(
task_id="make_choice",
conn_id="postgres_default",
sql="SELECT 1",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
branch_op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
@mock.patch("airflow.operators.sql.BaseSQLOperator.get_db_hook")
def test_branch_single_value_with_dag_run(self, mock_get_db_hook):
"""Check BranchSQLOperator branch operation"""
branch_op = BranchSQLOperator(
task_id="make_choice",
conn_id="mysql_default",
sql="SELECT 1",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
self.branch_1.set_upstream(branch_op)
self.branch_2.set_upstream(branch_op)
self.dag.clear()
dr = self.dag.create_dagrun(
run_id="manual__",
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
)
mock_get_records = mock_get_db_hook.return_value.get_first
mock_get_records.return_value = 1
branch_op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
tis = dr.get_task_instances()
for ti in tis:
if ti.task_id == "make_choice":
assert ti.state == State.SUCCESS
elif ti.task_id == "branch_1":
assert ti.state == State.NONE
elif ti.task_id == "branch_2":
assert ti.state == State.SKIPPED
else:
raise ValueError(f"Invalid task id {ti.task_id} found!")
@mock.patch("airflow.operators.sql.BaseSQLOperator.get_db_hook")
def test_branch_true_with_dag_run(self, mock_get_db_hook):
"""Check BranchSQLOperator branch operation"""
branch_op = BranchSQLOperator(
task_id="make_choice",
conn_id="mysql_default",
sql="SELECT 1",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
self.branch_1.set_upstream(branch_op)
self.branch_2.set_upstream(branch_op)
self.dag.clear()
dr = self.dag.create_dagrun(
run_id="manual__",
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
)
mock_get_records = mock_get_db_hook.return_value.get_first
for true_value in SUPPORTED_TRUE_VALUES:
mock_get_records.return_value = true_value
branch_op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
tis = dr.get_task_instances()
for ti in tis:
if ti.task_id == "make_choice":
assert ti.state == State.SUCCESS
elif ti.task_id == "branch_1":
assert ti.state == State.NONE
elif ti.task_id == "branch_2":
assert ti.state == State.SKIPPED
else:
raise ValueError(f"Invalid task id {ti.task_id} found!")
@mock.patch("airflow.operators.sql.BaseSQLOperator.get_db_hook")
def test_branch_false_with_dag_run(self, mock_get_db_hook):
"""Check BranchSQLOperator branch operation"""
branch_op = BranchSQLOperator(
task_id="make_choice",
conn_id="mysql_default",
sql="SELECT 1",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
self.branch_1.set_upstream(branch_op)
self.branch_2.set_upstream(branch_op)
self.dag.clear()
dr = self.dag.create_dagrun(
run_id="manual__",
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
)
mock_get_records = mock_get_db_hook.return_value.get_first
for false_value in SUPPORTED_FALSE_VALUES:
mock_get_records.return_value = false_value
branch_op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
tis = dr.get_task_instances()
for ti in tis:
if ti.task_id == "make_choice":
assert ti.state == State.SUCCESS
elif ti.task_id == "branch_1":
assert ti.state == State.SKIPPED
elif ti.task_id == "branch_2":
assert ti.state == State.NONE
else:
raise ValueError(f"Invalid task id {ti.task_id} found!")
@mock.patch("airflow.operators.sql.BaseSQLOperator.get_db_hook")
def test_branch_list_with_dag_run(self, mock_get_db_hook):
"""Checks if the BranchSQLOperator supports branching off to a list of tasks."""
branch_op = BranchSQLOperator(
task_id="make_choice",
conn_id="mysql_default",
sql="SELECT 1",
follow_task_ids_if_true=["branch_1", "branch_2"],
follow_task_ids_if_false="branch_3",
dag=self.dag,
)
self.branch_1.set_upstream(branch_op)
self.branch_2.set_upstream(branch_op)
self.branch_3 = DummyOperator(task_id="branch_3", dag=self.dag)
self.branch_3.set_upstream(branch_op)
self.dag.clear()
dr = self.dag.create_dagrun(
run_id="manual__",
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
)
mock_get_records = mock_get_db_hook.return_value.get_first
mock_get_records.return_value = [["1"]]
branch_op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
tis = dr.get_task_instances()
for ti in tis:
if ti.task_id == "make_choice":
assert ti.state == State.SUCCESS
elif ti.task_id == "branch_1":
assert ti.state == State.NONE
elif ti.task_id == "branch_2":
assert ti.state == State.NONE
elif ti.task_id == "branch_3":
assert ti.state == State.SKIPPED
else:
raise ValueError(f"Invalid task id {ti.task_id} found!")
@mock.patch("airflow.operators.sql.BaseSQLOperator.get_db_hook")
def test_invalid_query_result_with_dag_run(self, mock_get_db_hook):
"""Check BranchSQLOperator branch operation"""
branch_op = BranchSQLOperator(
task_id="make_choice",
conn_id="mysql_default",
sql="SELECT 1",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
self.branch_1.set_upstream(branch_op)
self.branch_2.set_upstream(branch_op)
self.dag.clear()
self.dag.create_dagrun(
run_id="manual__",
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
)
mock_get_records = mock_get_db_hook.return_value.get_first
mock_get_records.return_value = ["Invalid Value"]
with pytest.raises(AirflowException):
branch_op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
@mock.patch("airflow.operators.sql.BaseSQLOperator.get_db_hook")
def test_with_skip_in_branch_downstream_dependencies(self, mock_get_db_hook):
"""Test SQL Branch with skipping all downstream dependencies"""
branch_op = BranchSQLOperator(
task_id="make_choice",
conn_id="mysql_default",
sql="SELECT 1",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
branch_op >> self.branch_1 >> self.branch_2
branch_op >> self.branch_2
self.dag.clear()
dr = self.dag.create_dagrun(
run_id="manual__",
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
)
mock_get_records = mock_get_db_hook.return_value.get_first
for true_value in SUPPORTED_TRUE_VALUES:
mock_get_records.return_value = [true_value]
branch_op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
tis = dr.get_task_instances()
for ti in tis:
if ti.task_id == "make_choice":
assert ti.state == State.SUCCESS
elif ti.task_id == "branch_1":
assert ti.state == State.NONE
elif ti.task_id == "branch_2":
assert ti.state == State.NONE
else:
raise ValueError(f"Invalid task id {ti.task_id} found!")
@mock.patch("airflow.operators.sql.BaseSQLOperator.get_db_hook")
def test_with_skip_in_branch_downstream_dependencies2(self, mock_get_db_hook):
"""Test skipping downstream dependency for false condition"""
branch_op = BranchSQLOperator(
task_id="make_choice",
conn_id="mysql_default",
sql="SELECT 1",
follow_task_ids_if_true="branch_1",
follow_task_ids_if_false="branch_2",
dag=self.dag,
)
branch_op >> self.branch_1 >> self.branch_2
branch_op >> self.branch_2
self.dag.clear()
dr = self.dag.create_dagrun(
run_id="manual__",
start_date=timezone.utcnow(),
execution_date=DEFAULT_DATE,
state=State.RUNNING,
)
mock_get_records = mock_get_db_hook.return_value.get_first
for false_value in SUPPORTED_FALSE_VALUES:
mock_get_records.return_value = [false_value]
branch_op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
tis = dr.get_task_instances()
for ti in tis:
if ti.task_id == "make_choice":
assert ti.state == State.SUCCESS
elif ti.task_id == "branch_1":
assert ti.state == State.SKIPPED
elif ti.task_id == "branch_2":
assert ti.state == State.NONE
else:
raise ValueError(f"Invalid task id {ti.task_id} found!")
| {
"content_hash": "f8654d05966ce823fed6643a5ac2ba1f",
"timestamp": "",
"source": "github",
"line_count": 734,
"max_line_length": 96,
"avg_line_length": 34.81198910081744,
"alnum_prop": 0.580737319974953,
"repo_name": "apache/incubator-airflow",
"id": "3706fd6d4a0c12dcc45bce4bcfba8201b6a21ee7",
"size": "26340",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "tests/operators/test_sql.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "69070"
},
{
"name": "Dockerfile",
"bytes": "2001"
},
{
"name": "HTML",
"bytes": "283783"
},
{
"name": "JavaScript",
"bytes": "1387552"
},
{
"name": "Mako",
"bytes": "1284"
},
{
"name": "Python",
"bytes": "5482822"
},
{
"name": "Shell",
"bytes": "40957"
}
],
"symlink_target": ""
} |
"""
Exodus 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 program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import json
import re
import urllib
import urlparse
from resources.lib.modules import cache
from resources.lib.modules import client
from resources.lib.modules import source_utils
from resources.lib.modules import dom_parser
class source:
def __init__(self):
self.priority = 1
self.language = ['de']
self.domains = ['kinox.to', 'kinox.ag', 'kinox.tv', 'kinox.me', 'kinox.am', 'kinox.nu', 'kinox.pe', 'kinox.sg']
self._base_link = None
self.search_link = '/Search.html?q=%s'
self.get_links_epi = '/aGET/MirrorByEpisode/?Addr=%s&SeriesID=%s&Season=%s&Episode=%s'
self.mirror_link = '/aGET/Mirror/%s&Hoster=%s&Mirror=%s'
@property
def base_link(self):
if not self._base_link:
self._base_link = cache.get(self.__get_base_url, 120, 'http://%s' % self.domains[0])
return self._base_link
def movie(self, imdb, title, localtitle, aliases, year):
try:
url = self.__search(imdb)
if url:
return urllib.urlencode({'url': url})
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, aliases, year):
try:
url = self.__search(imdb)
if url:
return urllib.urlencode({'url': url})
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if url == None:
return
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
data.update({'season': season, 'episode': episode})
return urllib.urlencode(data)
except:
return
def sources(self, url, hostDict, hostprDict):
sources = []
try:
if url == None:
return sources
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
url = urlparse.urljoin(self.base_link, data.get('url'))
season = data.get('season')
episode = data.get('episode')
r = client.request(url)
if season and episode:
r = dom_parser.parse_dom(r, 'select', attrs={'id': 'SeasonSelection'}, req='rel')[0]
r = client.replaceHTMLCodes(r.attrs['rel'])[1:]
r = urlparse.parse_qs(r)
r = dict([(i, r[i][0]) if r[i] else (i, '') for i in r])
r = urlparse.urljoin(self.base_link, self.get_links_epi % (r['Addr'], r['SeriesID'], season, episode))
r = client.request(r)
r = dom_parser.parse_dom(r, 'ul', attrs={'id': 'HosterList'})[0]
r = dom_parser.parse_dom(r, 'li', attrs={'id': re.compile('Hoster_\d+')}, req='rel')
r = [(client.replaceHTMLCodes(i.attrs['rel']), i.content) for i in r if i[0] and i[1]]
r = [(i[0], re.findall('class="Named"[^>]*>([^<]+).*?(\d+)/(\d+)', i[1])) for i in r]
r = [(i[0], i[1][0][0].lower().rsplit('.', 1)[0], i[1][0][2]) for i in r if len(i[1]) > 0]
for link, hoster, mirrors in r:
valid, hoster = source_utils.is_host_valid(hoster, hostDict)
if not valid: continue
u = urlparse.parse_qs('&id=%s' % link)
u = dict([(x, u[x][0]) if u[x] else (x, '') for x in u])
for x in range(0, int(mirrors)):
url = self.mirror_link % (u['id'], u['Hoster'], x + 1)
if season and episode: url += "&Season=%s&Episode=%s" % (season, episode)
try: sources.append({'source': hoster, 'quality': 'SD', 'language': 'de', 'url': url, 'direct': False, 'debridonly': False})
except: pass
return sources
except:
return sources
def resolve(self, url):
try:
url = urlparse.urljoin(self.base_link, url)
r = client.request(url, referer=self.base_link)
r = json.loads(r)['Stream']
r = [(dom_parser.parse_dom(r, 'a', req='href'), dom_parser.parse_dom(r, 'iframe', req='src'))]
r = [i[0][0].attrs['href'] if i[0] else i[1][0].attrs['src'] for i in r if i[0] or i[1]][0]
if not r.startswith('http'):
r = urlparse.parse_qs(r)
r = [r[i][0] if r[i] and r[i][0].startswith('http') else (i, '') for i in r][0]
return r
except:
return
def __search(self, imdb):
try:
l = ['1', '15']
r = client.request(urlparse.urljoin(self.base_link, self.search_link % imdb))
r = dom_parser.parse_dom(r, 'table', attrs={'id': 'RsltTableStatic'})
r = dom_parser.parse_dom(r, 'tr')
r = [(dom_parser.parse_dom(i, 'a', req='href'), dom_parser.parse_dom(i, 'img', attrs={'alt': 'language'}, req='src')) for i in r]
r = [(i[0][0].attrs['href'], i[0][0].content, i[1][0].attrs['src']) for i in r if i[0] and i[1]]
r = [(i[0], i[1], re.findall('.+?(\d+)\.', i[2])) for i in r]
r = [(i[0], i[1], i[2][0] if len(i[2]) > 0 else '0') for i in r]
r = sorted(r, key=lambda i: int(i[2])) # german > german/subbed
r = [i[0] for i in r if i[2] in l][0]
return source_utils.strip_domain(r)
except:
return
def __get_base_url(self, fallback):
try:
for domain in self.domains:
try:
url = 'http://%s' % domain
r = client.request(url, limit=1, timeout='10')
r = dom_parser.parse_dom(r, 'meta', attrs={'name': 'keywords'}, req='content')
if r and 'kino.to' in r[0].attrs.get('content').lower():
return url
except:
pass
except:
pass
return fallback
| {
"content_hash": "d28e3fdd40d61925bd5e7da3d9839775",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 144,
"avg_line_length": 40.2710843373494,
"alnum_prop": 0.5213163799551234,
"repo_name": "TheWardoctor/Wardoctors-repo",
"id": "f9126cb13ea03781cbc2c7ff63c9e4d21cf2766e",
"size": "6710",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "script.module.exodus/lib/resources/lib/sources/de/kinox.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3208"
},
{
"name": "JavaScript",
"bytes": "115722"
},
{
"name": "Python",
"bytes": "34405207"
},
{
"name": "Shell",
"bytes": "914"
}
],
"symlink_target": ""
} |
import falcon
import jieba
import json
import jieba.posseg as pseg
import posSeg
class Resource(object):
def on_post(self, req, resp):
body = req.stream.read()
if not body:
raise falcon.HTTPBadRequest('Empty request body')
#seg_list = list(jieba.cut(body, cut_all=False))
words = pseg.lcut(body);
result=list();
for word, flag in words:
tmp=posSeg.posSeg(word,flag)
result.append(tmp.__dict__)
resp.body=json.dumps(result)
resp.status = falcon.HTTP_200
| {
"content_hash": "472f87239ae628995511d67fab643a56",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 61,
"avg_line_length": 27.95,
"alnum_prop": 0.6100178890876565,
"repo_name": "eit/jieba-web-service",
"id": "615b29653411d9ad86ab567d648477b8e938b60f",
"size": "559",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pos.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "2018"
},
{
"name": "Shell",
"bytes": "181"
}
],
"symlink_target": ""
} |
from django.shortcuts import redirect, render
import clinq.models as model
from django.http import HttpResponse, StreamingHttpResponse
from django.db.models import Count, Min, Sum, Avg
from django.shortcuts import get_object_or_404, render
# Create your views here.
def Home(request):
return render(request, 'home.html', None)
def audio_by_Artists(request):
groupes = model.AudioFile.objects.order_by("artist").values("artist").annotate(totalLength=Sum('length'))
return render(request, 'musik_by_artist.html', {"artists": groupes})
def list_albums(request):
def getAllAlbums():
groupes = model.AudioFile.objects.order_by("artist","album").values("artist","album").annotate(totalLength=Sum('length'))
for g in groupes:
yield ("%s\n"%g)
resp = StreamingHttpResponse( getAllAlbums(), mimetype='text/plain')
return resp
def list_artists(request):
def getAllArtists():
groupes = model.AudioFile.objects.order_by("artist").values("artist").annotate(totalLength=Sum('length'))
for g in groupes:
yield ("%s\n"%g)
resp = StreamingHttpResponse( getAllArtists(), mimetype='text/plain')
return resp
def getArtistImage(request, artistHex):
artist = artistHex.decode("hex")
dbObj = list(model.AudioFile.objects.filter(artist__exact=artist)[0:1])[0]
if dbObj.cover:
resp = HttpResponse(dbObj.cover, mimetype = dbObj.coverMime)
resp["Cache-Control"] = "public, max-age=31536000"
return resp
return redirect("/static/img/nocover.png")
| {
"content_hash": "ee057a8cf8a99be6018ddac83a444ad9",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 123,
"avg_line_length": 27.296296296296298,
"alnum_prop": 0.7360922659430122,
"repo_name": "Ahn1/Clinq",
"id": "44946276c3130ca3fafd3da7cbfc736a7ef3071f",
"size": "1474",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/clinq/views.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "173256"
},
{
"name": "JavaScript",
"bytes": "39218"
},
{
"name": "Python",
"bytes": "26025"
}
],
"symlink_target": ""
} |
from bs4 import SoupStrainer
from bs4 import BeautifulSoup
from urllib import urlopen
only_ul_tags = SoupStrainer("ul")
url = "http://tratu.coviet.vn/hoc-tieng-trung/cap-cau-song-ngu/vietgle-tra-tu/tat-ca/trang-1.html"
soup = BeautifulSoup(urlopen(url), "html.parser", parse_only = only_ul_tags)
print (soup.prettify()) | {
"content_hash": "3f5c6b2d1533c038864689a2af685bad",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 98,
"avg_line_length": 32.2,
"alnum_prop": 0.7577639751552795,
"repo_name": "hoaibang07/collecting-corpus-online",
"id": "3ee178d8f2e03115e15dcf3e6cc5b0c823fd959f",
"size": "322",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Vietgle/Source/Hoaibang/ParsingOnlyPartOfPage.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "41723"
}
],
"symlink_target": ""
} |
from typing import Tuple
import base64, getpass
import pysodium #type: ignore
#===============================================================================
def prompt_for_new_password() -> str:
""" Prompt the user to enter a new password, with confirmation """
while True:
passw: str = getpass.getpass()
passw2: str = getpass.getpass()
if passw == passw2: return passw
else: print('Passwords do not match')
#===============================================================================
def hash_password(password: str, salt: bytes) -> bytes:
return pysodium.crypto_pwhash(pysodium.crypto_secretbox_KEYBYTES, password, salt,
pysodium.crypto_pwhash_argon2i_OPSLIMIT_INTERACTIVE,
pysodium.crypto_pwhash_argon2i_MEMLIMIT_INTERACTIVE,
pysodium.crypto_pwhash_ALG_ARGON2I13)
#===============================================================================
def make_keypair() -> Tuple[bytes, bytes]:
public_key, private_key = pysodium.crypto_sign_keypair()
print('Do you wish to encrypt the private key under a password? (y/n)')
answer: str
while True:
answer = input('>').lower()
if answer not in ['y', 'n']: print('Invalid answer')
else: break
if answer == 'y':
salt: bytes = pysodium.randombytes(pysodium.crypto_pwhash_SALTBYTES)
key: bytes = hash_password(prompt_for_new_password(), salt)
nonce: bytes = pysodium.randombytes(pysodium.crypto_box_NONCEBYTES)
cyphertext: bytes = pysodium.crypto_secretbox(private_key, nonce, key)
private_key = b'y' + salt + nonce + cyphertext
else:
private_key = b'n' + private_key
return base64.b64encode(private_key), base64.b64encode(public_key)
#===============================================================================
def unlock_private_key(private_key_b64: str) -> bytes:
private_key: bytes = base64.b64decode(private_key_b64)
if private_key[0] == b'y':
sbytes: int = pysodium.crypto_pwhash_SALTBYTES
nbytes: int = pysodium.crypto_box_NONCEBYTES
salt: bytes = private_key[1:sbytes+1]
nonce: bytes = private_key[sbytes+1: sbytes+nbytes+1]
cyphertext: bytes = private_key[sbytes+nbytes+1:]
key: bytes = hash_password(getpass.getpass(), salt)
private_key = pysodium.crypto_secretbox_open(cyphertext, nonce, key)
return private_key
else:
return private_key[1:]
| {
"content_hash": "9a38fdecd6ccd4a11e39f51eeb858cf9",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 87,
"avg_line_length": 45.01754385964912,
"alnum_prop": 0.5530007794232268,
"repo_name": "robehickman/simple-http-file-sync",
"id": "a66f5ea4943dd5a7f1a4fb206fd4e67fef3d061d",
"size": "2566",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bversion/crypto.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "376"
},
{
"name": "Python",
"bytes": "162348"
}
],
"symlink_target": ""
} |
"""
Fava – A web interface for beancount.
Copyright © 2015-2016 Dominik Aumayr <dominik@aumayr.name>
Licensed under the MIT License.
You may not use this file except in compliance with the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
__url__ = "http://github.com/aumayr/fava"
__version__ = "0.3.1-dev"
__license__ = "MIT"
__author__ = "Dominik Aumayr"
__author_email__ = "dominik@aumayr.name"
| {
"content_hash": "45f7e1e0d37c92e371b8ed15da5d7ff4",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 76,
"avg_line_length": 41.470588235294116,
"alnum_prop": 0.7120567375886525,
"repo_name": "corani/beancount-web",
"id": "b49bde7ef33369fe70747b8986ffe35f46feef79",
"size": "732",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "fava/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "38251"
},
{
"name": "HTML",
"bytes": "76031"
},
{
"name": "JavaScript",
"bytes": "51166"
},
{
"name": "Makefile",
"bytes": "503"
},
{
"name": "Python",
"bytes": "64809"
},
{
"name": "Shell",
"bytes": "1189"
}
],
"symlink_target": ""
} |
"""Fichier contenant la classe DiligenceMaudite, détaillée plus bas."""
from random import choice
from abstraits.obase import BaseObj
class DiligenceMaudite(BaseObj):
"""Classe représentant une diligence maudite.
Une diligence maudite au niveau prototype est un modèle, définissant
un ensemble de salles qui seront dupliquées par le système en
ajoutant quelques aléatoires. Par exemple, une diligence maudite
pourrait contenir vingt salles, en comptant des détails et scripts,
peut-être certains PNJ. La configuration particulière de la
diligence se fera dans un éditeur spécialisé. Quand le système
devra créer une véritable diligence maudite, accessible aux
joueurs, il créera une zone particulière en dupliquant les salles
de la diligence et en intégrant les paramètres aléatoires configurés
dans l'éditeur spécifique (comme la présence ou l'absence de
PNJ aléatoires). La diligence maudite est ensuite rendue accessible
grâce à une sortie menant dans l'univers accessible aux joueurs.
"""
enregistrer = True
def __init__(self, cle):
"""Constructeur de la fiche."""
BaseObj.__init__(self)
self.cle = cle
self.ouverte = False
self._construire()
def __getnewargs__(self):
return ("", )
@property
def salles(self):
"""Retourne toutes les salles modèle de la diligence."""
zone = importeur.salle.zones.get(self.cle)
if zone:
return zone.salles
return []
def creer_premiere_salle(self):
"""Crée la première salle de la diligence."""
return importeur.salle.creer_salle(self.cle, "1", valide=False)
def apparaitre(self):
"""Fait apparaître la diligence dupliquée."""
# Cherche la clé de la zone à créer
nb = 1
while (self.cle + "_" + str(nb)) in importeur.salle.zones:
nb += 1
cle = self.cle + "_" + str(nb)
# Duplication des salles
for salle in self.salles:
n_salle = importeur.salle.creer_salle(cle, salle.mnemonic,
valide=False)
n_salle.titre = salle.titre
n_salle.description = salle.description
n_salle.details = salle.details
n_salle.interieur = salle.interieur
n_salle.script = salle.script
# On recopie les sorties
for salle in self.salles:
ident = "{}:{}".format(cle, salle.mnemonic)
n_salle = importeur.salle.salles[ident]
for dir, sortie in salle.sorties._sorties.items():
if sortie and sortie.salle_dest:
n_ident = "{}:{}".format(cle, sortie.salle_dest.mnemonic)
c_salle = importeur.salle.salles[n_ident]
t_sortie = n_salle.sorties.ajouter_sortie(dir,
sortie.nom, sortie.article, c_salle,
sortie.correspondante)
if sortie.porte:
t_sortie.ajouter_porte()
t_sortie.porte._clef = sortie.porte._clef
t_sortie.porte.verrouillee = sortie.porte.verrouillee
return cle
@staticmethod
def lier(origine, salle):
"""Lie l'origine de la diligence à la salle indiquée."""
if origine.sorties.sortie_existe("bas"):
raise ValueError("la sortie bas existe en {}".format(
origine.ident))
if salle.sorties.sortie_existe("haut"):
raise ValueError("la sortie haut existe en {}".format(
salle.ident))
sortie = salle.sorties.ajouter_sortie("haut", "diligence", "la",
origine, "bas")
origine.sorties.ajouter_sortie("bas", "sortie", "la",
salle, "haut")
return sortie
@staticmethod
def deplacer(entree):
"""Déplace la diligence d'une salle, si possible."""
origine = entree.sorties.get_sortie_par_nom_ou_direction(
"bas").salle_dest
terrain = origine.nom_terrain
sorties = []
for sortie in origine.sorties:
if sortie and sortie.salle_dest and sortie.salle_dest.exterieur \
and sortie.salle_dest.nom_terrain == terrain and \
sortie.salle_dest is not entree and not \
sortie.salle_dest.sorties.sortie_existe("haut"):
sorties.append(sortie)
if not sorties:
return
sortie = choice(sorties)
salle = sortie.salle_dest
# Modification de la sortie
entree.sorties.supprimer_sortie("bas")
origine.sorties.supprimer_sortie("haut")
salle.sorties.ajouter_sortie("haut", "diligence", "la",
entree, "bas")
entree.sorties.ajouter_sortie("bas", "sortie", "la",
salle, "haut")
origine.envoyer("Une diligence lourd lentement vers {}.".format(
sortie.nom_complet))
salle.envoyer("Une diligence arrive en roulant pesamment.")
return salle
| {
"content_hash": "65bd4fe8fcccc96507089b26a3b443a9",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 77,
"avg_line_length": 37.625,
"alnum_prop": 0.5954660934141098,
"repo_name": "vlegoff/tsunami",
"id": "cdbbc2da9a6e58fff6ec6503829dcb6f8567444e",
"size": "6724",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/secondaires/diligence/diligence.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "7930908"
},
{
"name": "Ruby",
"bytes": "373"
}
],
"symlink_target": ""
} |
from django.test import Client, TestCase
from .utils import create_admin_account, make_request
from app.timetables.factories import TimetableFactory
class TimetableApiTest(TestCase):
def setUp(self):
self.client = Client()
create_admin_account()
self.timetable = TimetableFactory()
def retrieve_timetables(self):
query = 'query {timetables{edges{node{name}}}}'
return make_request(self.client, query)
def test_retrieve_timetables(self):
response = self.retrieve_timetables()
expected = {
'timetables': [{
'name': self.timetable.name
}]
}
self.assertEqual(expected, response)
| {
"content_hash": "f5edc214eb25b6b2d05bbc6d83b0daf3",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 55,
"avg_line_length": 27.153846153846153,
"alnum_prop": 0.6359773371104815,
"repo_name": "teamtaverna/core",
"id": "67179eb4207ea35286c19bcdf93e8b696bb462b3",
"size": "706",
"binary": false,
"copies": "1",
"ref": "refs/heads/staging",
"path": "app/api/tests/test_timetable_api.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "163026"
}
],
"symlink_target": ""
} |
def library_keyword_1(arg1):
"""library keyword 1 doc"""
print arg1
def library_keyword_2(arg1, arg2):
"""library keyword 2 doc"""
print arg1, arg2
| {
"content_hash": "da168c98f274ae32486ab0585bf1bec3",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 34,
"avg_line_length": 21.75,
"alnum_prop": 0.6091954022988506,
"repo_name": "andriyko/sublime-robot-framework-assistant",
"id": "8b6015d8dd544413926b429b35bc3463a17c751f",
"size": "174",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/resource/test_data/suite_tree/LibNoClass.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "216082"
},
{
"name": "RobotFramework",
"bytes": "13898"
},
{
"name": "Smarty",
"bytes": "2837"
}
],
"symlink_target": ""
} |
from ctypes import c_char_p, c_int, c_size_t, c_ubyte, c_uint, POINTER
from django.contrib.gis.geos.libgeos import lgeos, CS_PTR, GEOM_PTR
from django.contrib.gis.geos.prototypes.errcheck import \
check_geom, check_minus_one, check_sized_string, check_string, check_zero
# This is the return type used by binary output (WKB, HEX) routines.
c_uchar_p = POINTER(c_ubyte)
# We create a simple subclass of c_char_p here because when the response
# type is set to c_char_p, you get a _Python_ string and there's no way
# to access the string's address inside the error checking function.
# In other words, you can't free the memory allocated inside GEOS. Previously,
# the return type would just be omitted and the integer address would be
# used -- but this allows us to be specific in the function definition and
# keeps the reference so it may be free'd.
class geos_char_p(c_char_p):
pass
### ctypes generation functions ###
def bin_constructor(func):
"Generates a prototype for binary construction (HEX, WKB) GEOS routines."
func.argtypes = [c_char_p, c_size_t]
func.restype = GEOM_PTR
func.errcheck = check_geom
return func
# HEX & WKB output
def bin_output(func):
"Generates a prototype for the routines that return a a sized string."
func.argtypes = [GEOM_PTR, POINTER(c_size_t)]
func.errcheck = check_sized_string
func.restype = c_uchar_p
return func
def geom_output(func, argtypes):
"For GEOS routines that return a geometry."
if argtypes: func.argtypes = argtypes
func.restype = GEOM_PTR
func.errcheck = check_geom
return func
def geom_index(func):
"For GEOS routines that return geometries from an index."
return geom_output(func, [GEOM_PTR, c_int])
def int_from_geom(func, zero=False):
"Argument is a geometry, return type is an integer."
func.argtypes = [GEOM_PTR]
func.restype = c_int
if zero:
func.errcheck = check_zero
else:
func.errcheck = check_minus_one
return func
def string_from_geom(func):
"Argument is a Geometry, return type is a string."
# We do _not_ specify an argument type because we want just an
# address returned from the function.
func.argtypes = [GEOM_PTR]
func.restype = geos_char_p
func.errcheck = check_string
return func
### ctypes prototypes ###
# TODO: Tell all users to use GEOS 3.0.0, instead of the release
# candidates, and use the new Reader and Writer APIs (e.g.,
# GEOSWKT[Reader|Writer], GEOSWKB[Reader|Writer]). A good time
# to do this will be when Refractions releases a Windows PostGIS
# installer using GEOS 3.0.0.
# Creation routines from WKB, HEX, WKT
from_hex = bin_constructor(lgeos.GEOSGeomFromHEX_buf)
from_wkb = bin_constructor(lgeos.GEOSGeomFromWKB_buf)
from_wkt = geom_output(lgeos.GEOSGeomFromWKT, [c_char_p])
# Output routines
to_hex = bin_output(lgeos.GEOSGeomToHEX_buf)
to_wkb = bin_output(lgeos.GEOSGeomToWKB_buf)
to_wkt = string_from_geom(lgeos.GEOSGeomToWKT)
# The GEOS geometry type, typeid, num_coordites and number of geometries
geos_normalize = int_from_geom(lgeos.GEOSNormalize)
geos_type = string_from_geom(lgeos.GEOSGeomType)
geos_typeid = int_from_geom(lgeos.GEOSGeomTypeId)
get_dims = int_from_geom(lgeos.GEOSGeom_getDimensions, zero=True)
get_num_coords = int_from_geom(lgeos.GEOSGetNumCoordinates)
get_num_geoms = int_from_geom(lgeos.GEOSGetNumGeometries)
# Geometry creation factories
create_point = geom_output(lgeos.GEOSGeom_createPoint, [CS_PTR])
create_linestring = geom_output(lgeos.GEOSGeom_createLineString, [CS_PTR])
create_linearring = geom_output(lgeos.GEOSGeom_createLinearRing, [CS_PTR])
# Polygon and collection creation routines are special and will not
# have their argument types defined.
create_polygon = geom_output(lgeos.GEOSGeom_createPolygon, None)
create_collection = geom_output(lgeos.GEOSGeom_createCollection, None)
# Ring routines
get_extring = geom_output(lgeos.GEOSGetExteriorRing, [GEOM_PTR])
get_intring = geom_index(lgeos.GEOSGetInteriorRingN)
get_nrings = int_from_geom(lgeos.GEOSGetNumInteriorRings)
# Collection Routines
get_geomn = geom_index(lgeos.GEOSGetGeometryN)
# Cloning
geom_clone = lgeos.GEOSGeom_clone
geom_clone.argtypes = [GEOM_PTR]
geom_clone.restype = GEOM_PTR
# Destruction routine.
destroy_geom = lgeos.GEOSGeom_destroy
destroy_geom.argtypes = [GEOM_PTR]
destroy_geom.restype = None
# SRID routines
geos_get_srid = lgeos.GEOSGetSRID
geos_get_srid.argtypes = [GEOM_PTR]
geos_get_srid.restype = c_int
geos_set_srid = lgeos.GEOSSetSRID
geos_set_srid.argtypes = [GEOM_PTR, c_int]
geos_set_srid.restype = None
| {
"content_hash": "5d1782ebb7341b2fd287a36119e52cab",
"timestamp": "",
"source": "github",
"line_count": 126,
"max_line_length": 79,
"avg_line_length": 36.55555555555556,
"alnum_prop": 0.7403386886669562,
"repo_name": "chewable/django",
"id": "d42ceaa29205c0d201bffc93870b146440e33dfe",
"size": "4606",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "django/contrib/gis/geos/prototypes/geom.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mybitbank.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| {
"content_hash": "d459e072e49a0d88d4f204dbf92010ee",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 73,
"avg_line_length": 23.1,
"alnum_prop": 0.70995670995671,
"repo_name": "sgoudelis/mybitbank",
"id": "ecaa0ecfa31ea71a6f84a7da645ca52cf138938a",
"size": "253",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "manage.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "105105"
},
{
"name": "HTML",
"bytes": "74263"
},
{
"name": "JavaScript",
"bytes": "182459"
},
{
"name": "Python",
"bytes": "258496"
}
],
"symlink_target": ""
} |
"""Support for Geofency."""
from aiohttp import web
import voluptuous as vol
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER
from homeassistant.const import (
ATTR_LATITUDE,
ATTR_LONGITUDE,
ATTR_NAME,
CONF_WEBHOOK_ID,
HTTP_OK,
HTTP_UNPROCESSABLE_ENTITY,
STATE_NOT_HOME,
)
from homeassistant.helpers import config_entry_flow
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.util import slugify
from .const import DOMAIN
PLATFORMS = [DEVICE_TRACKER]
CONF_MOBILE_BEACONS = "mobile_beacons"
CONFIG_SCHEMA = vol.Schema(
{
vol.Optional(DOMAIN): vol.Schema(
{
vol.Optional(CONF_MOBILE_BEACONS, default=[]): vol.All(
cv.ensure_list, [cv.string]
)
}
)
},
extra=vol.ALLOW_EXTRA,
)
ATTR_ADDRESS = "address"
ATTR_BEACON_ID = "beaconUUID"
ATTR_CURRENT_LATITUDE = "currentLatitude"
ATTR_CURRENT_LONGITUDE = "currentLongitude"
ATTR_DEVICE = "device"
ATTR_ENTRY = "entry"
BEACON_DEV_PREFIX = "beacon"
LOCATION_ENTRY = "1"
LOCATION_EXIT = "0"
TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
def _address(value: str) -> str:
r"""Coerce address by replacing '\n' with ' '."""
return value.replace("\n", " ")
WEBHOOK_SCHEMA = vol.Schema(
{
vol.Required(ATTR_ADDRESS): vol.All(cv.string, _address),
vol.Required(ATTR_DEVICE): vol.All(cv.string, slugify),
vol.Required(ATTR_ENTRY): vol.Any(LOCATION_ENTRY, LOCATION_EXIT),
vol.Required(ATTR_LATITUDE): cv.latitude,
vol.Required(ATTR_LONGITUDE): cv.longitude,
vol.Required(ATTR_NAME): vol.All(cv.string, slugify),
vol.Optional(ATTR_CURRENT_LATITUDE): cv.latitude,
vol.Optional(ATTR_CURRENT_LONGITUDE): cv.longitude,
vol.Optional(ATTR_BEACON_ID): cv.string,
},
extra=vol.ALLOW_EXTRA,
)
async def async_setup(hass, hass_config):
"""Set up the Geofency component."""
config = hass_config.get(DOMAIN, {})
mobile_beacons = config.get(CONF_MOBILE_BEACONS, [])
hass.data[DOMAIN] = {
"beacons": [slugify(beacon) for beacon in mobile_beacons],
"devices": set(),
"unsub_device_tracker": {},
}
return True
async def handle_webhook(hass, webhook_id, request):
"""Handle incoming webhook from Geofency."""
try:
data = WEBHOOK_SCHEMA(dict(await request.post()))
except vol.MultipleInvalid as error:
return web.Response(text=error.error_message, status=HTTP_UNPROCESSABLE_ENTITY)
if _is_mobile_beacon(data, hass.data[DOMAIN]["beacons"]):
return _set_location(hass, data, None)
if data["entry"] == LOCATION_ENTRY:
location_name = data["name"]
else:
location_name = STATE_NOT_HOME
if ATTR_CURRENT_LATITUDE in data:
data[ATTR_LATITUDE] = data[ATTR_CURRENT_LATITUDE]
data[ATTR_LONGITUDE] = data[ATTR_CURRENT_LONGITUDE]
return _set_location(hass, data, location_name)
def _is_mobile_beacon(data, mobile_beacons):
"""Check if we have a mobile beacon."""
return ATTR_BEACON_ID in data and data["name"] in mobile_beacons
def _device_name(data):
"""Return name of device tracker."""
if ATTR_BEACON_ID in data:
return f"{BEACON_DEV_PREFIX}_{data['name']}"
return data["device"]
def _set_location(hass, data, location_name):
"""Fire HA event to set location."""
device = _device_name(data)
async_dispatcher_send(
hass,
TRACKER_UPDATE,
device,
(data[ATTR_LATITUDE], data[ATTR_LONGITUDE]),
location_name,
data,
)
return web.Response(text=f"Setting location for {device}", status=HTTP_OK)
async def async_setup_entry(hass, entry):
"""Configure based on config entry."""
hass.components.webhook.async_register(
DOMAIN, "Geofency", entry.data[CONF_WEBHOOK_ID], handle_webhook
)
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
hass.components.webhook.async_unregister(entry.data[CONF_WEBHOOK_ID])
hass.data[DOMAIN]["unsub_device_tracker"].pop(entry.entry_id)()
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
async_remove_entry = config_entry_flow.webhook_async_remove_entry
| {
"content_hash": "917ad48987471996bcdec2c7525c0324",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 87,
"avg_line_length": 29.289473684210527,
"alnum_prop": 0.6617250673854448,
"repo_name": "sander76/home-assistant",
"id": "1cbaea2373371f09eae4b3e2690854dbf960f493",
"size": "4452",
"binary": false,
"copies": "4",
"ref": "refs/heads/dev",
"path": "homeassistant/components/geofency/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1795"
},
{
"name": "Python",
"bytes": "36548768"
},
{
"name": "Shell",
"bytes": "4910"
}
],
"symlink_target": ""
} |
from api import serializers as s
class NodeVersionSerializer(s.Serializer):
hostname = s.Field()
version = s.Field(source='system_version')
platform_version = s.Field(source='platform_version')
| {
"content_hash": "414ca31c2279addd3acf9d4012b1dd2c",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 57,
"avg_line_length": 29.714285714285715,
"alnum_prop": 0.7307692307692307,
"repo_name": "erigones/esdc-ce",
"id": "ed470e09cb3afdc26faf810f3ce0782a860ab6dd",
"size": "208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api/system/node/serializers.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Awk",
"bytes": "2728"
},
{
"name": "C",
"bytes": "8581"
},
{
"name": "CSS",
"bytes": "146461"
},
{
"name": "DTrace",
"bytes": "2250"
},
{
"name": "Erlang",
"bytes": "18842"
},
{
"name": "HTML",
"bytes": "473343"
},
{
"name": "JavaScript",
"bytes": "679240"
},
{
"name": "Jinja",
"bytes": "29584"
},
{
"name": "PLpgSQL",
"bytes": "17954"
},
{
"name": "Perl",
"bytes": "93955"
},
{
"name": "Python",
"bytes": "3124524"
},
{
"name": "Ruby",
"bytes": "56"
},
{
"name": "SCSS",
"bytes": "82814"
},
{
"name": "Shell",
"bytes": "281885"
}
],
"symlink_target": ""
} |
from __future__ import unicode_literals
import frappe, copy, json
from frappe import _, msgprint
from frappe.utils import cint
rights = ("read", "write", "create", "delete", "submit", "cancel", "amend",
"print", "email", "report", "import", "export", "set_user_permissions")
def check_admin_or_system_manager(user=None):
if not user: user = frappe.session.user
if ("System Manager" not in frappe.get_roles(user)) and (user!="Administrator"):
frappe.throw(_("Not permitted"), frappe.PermissionError)
def has_permission(doctype, ptype="read", doc=None, verbose=True, user=None):
"""check if user has permission"""
if not user: user = frappe.session.user
if frappe.is_table(doctype):
return True
meta = frappe.get_meta(doctype)
if ptype=="submit" and not cint(meta.is_submittable):
return False
if ptype=="import" and not cint(meta.allow_import):
return False
if user=="Administrator":
return True
role_permissions = get_role_permissions(meta, user=user)
if not role_permissions.get(ptype):
return False
if doc:
if isinstance(doc, basestring):
doc = frappe.get_doc(meta.name, doc)
if role_permissions["apply_user_permissions"].get(ptype):
if not user_has_permission(doc, verbose=verbose, user=user,
user_permission_doctypes=role_permissions.get("user_permission_doctypes")):
return False
if not has_controller_permissions(doc, ptype, user=user):
return False
return True
def get_doc_permissions(doc, verbose=False, user=None):
if not user: user = frappe.session.user
if frappe.is_table(doc.doctype):
return {"read":1, "write":1}
meta = frappe.get_meta(doc.doctype)
role_permissions = copy.deepcopy(get_role_permissions(meta, user=user))
if not cint(meta.is_submittable):
role_permissions["submit"] = 0
if not cint(meta.allow_import):
role_permissions["import"] = 0
if role_permissions.get("apply_user_permissions") and not user_has_permission(doc, verbose=verbose, user=user,
user_permission_doctypes=role_permissions.get("user_permission_doctypes")):
# no user permissions, switch off all user-level permissions
for ptype in role_permissions:
if role_permissions["apply_user_permissions"].get(ptype):
role_permissions[ptype] = 0
return role_permissions
def get_role_permissions(meta, user=None):
if not user: user = frappe.session.user
cache_key = (meta.name, user)
if not frappe.local.role_permissions.get(cache_key):
perms = frappe._dict({ "apply_user_permissions": {} })
user_roles = frappe.get_roles(user)
for p in meta.permissions:
if cint(p.permlevel)==0 and (p.role in user_roles):
for ptype in rights:
perms[ptype] = perms.get(ptype, 0) or cint(p.get(ptype))
if ptype != "set_user_permissions" and p.get(ptype):
perms["apply_user_permissions"][ptype] = (perms["apply_user_permissions"].get(ptype, 1)
and p.get("apply_user_permissions"))
if p.apply_user_permissions:
# set user_permission_doctypes in perms
user_permission_doctypes = (json.loads(p.user_permission_doctypes)
if p.user_permission_doctypes else None)
if user_permission_doctypes and user_permission_doctypes not in perms.get("user_permission_doctypes", []):
# perms["user_permission_doctypes"] would be a list of list like [["User", "Blog Post"], ["User"]]
perms.setdefault("user_permission_doctypes", []).append(user_permission_doctypes)
for key, value in perms.get("apply_user_permissions").items():
if not value:
del perms["apply_user_permissions"][key]
frappe.local.role_permissions[cache_key] = perms
return frappe.local.role_permissions[cache_key]
def user_has_permission(doc, verbose=True, user=None, user_permission_doctypes=None):
from frappe.defaults import get_user_permissions
user_permissions = get_user_permissions(user)
user_permission_doctypes = get_user_permission_doctypes(user_permission_doctypes, user_permissions)
def check_user_permission(d):
meta = frappe.get_meta(d.get("doctype"))
end_result = False
messages = {}
# check multiple sets of user_permission_doctypes using OR condition
for doctypes in user_permission_doctypes:
result = True
for df in meta.get_fields_to_check_permissions(doctypes):
if (df.options in user_permissions and d.get(df.fieldname)
and d.get(df.fieldname) not in user_permissions[df.options]):
result = False
if verbose:
msg = _("Not allowed to access {0} with {1} = {2}").format(df.options, _(df.label), d.get(df.fieldname))
if d.parentfield:
msg = "{doctype}, {row} #{idx}, ".format(doctype=_(d.doctype),
row=_("Row"), idx=d.idx) + msg
messages[df.fieldname] = msg
end_result = end_result or result
if not end_result and messages:
for fieldname, msg in messages.items():
msgprint(msg)
return end_result
_user_has_permission = check_user_permission(doc)
for d in doc.get_all_children():
_user_has_permission = check_user_permission(d) and _user_has_permission
return _user_has_permission
def has_controller_permissions(doc, ptype, user=None):
if not user: user = frappe.session.user
for method in frappe.get_hooks("has_permission").get(doc.doctype, []):
if not frappe.call(frappe.get_attr(method), doc=doc, ptype=ptype, user=user):
return False
return True
def can_set_user_permissions(doctype, docname=None):
# System Manager can always set user permissions
if "System Manager" in frappe.get_roles():
return True
meta = frappe.get_meta(doctype)
# check if current user has read permission for docname
if docname and not has_permission(doctype, "read", docname):
return False
# check if current user has a role that can set permission
if get_role_permissions(meta).set_user_permissions!=1:
return False
return True
def set_user_permission_if_allowed(doctype, name, user, with_message=False):
if get_role_permissions(frappe.get_meta(doctype), user).set_user_permissions!=1:
add_user_permission(doctype, name, user, with_message)
def add_user_permission(doctype, name, user, with_message=False):
if name not in frappe.defaults.get_user_permissions(user).get(doctype, []):
if not frappe.db.exists(doctype, name):
frappe.throw(_("{0} {1} not found").format(_(doctype), name), frappe.DoesNotExistError)
frappe.defaults.add_default(doctype, name, user, "User Permission")
elif with_message:
msgprint(_("Permission already set"))
def remove_user_permission(doctype, name, user, default_value_name=None):
frappe.defaults.clear_default(key=doctype, value=name, parent=user, parenttype="User Permission",
name=default_value_name)
def clear_user_permissions_for_doctype(doctype):
frappe.defaults.clear_default(parenttype="User Permission", key=doctype)
def can_import(doctype, raise_exception=False):
if not ("System Manager" in frappe.get_roles() or has_permission(doctype, "import")):
if raise_exception:
raise frappe.PermissionError("You are not allowed to import: {doctype}".format(doctype=doctype))
else:
return False
return True
def can_export(doctype, raise_exception=False):
if not ("System Manager" in frappe.get_roles() or has_permission(doctype, "export")):
if raise_exception:
raise frappe.PermissionError("You are not allowed to export: {doctype}".format(doctype=doctype))
else:
return False
return True
def apply_user_permissions(doctype, ptype, user=None):
"""Check if apply_user_permissions is checked for a doctype, perm type, user combination"""
role_permissions = get_role_permissions(frappe.get_meta(doctype), user=user)
return role_permissions.get("apply_user_permissions", {}).get(ptype)
def get_user_permission_doctypes(user_permission_doctypes, user_permissions):
"""returns a list of list like [["User", "Blog Post"], ["User"]]"""
if user_permission_doctypes:
# select those user permission doctypes for which user permissions exist!
user_permission_doctypes = [list(set(doctypes).intersection(set(user_permissions.keys())))
for doctypes in user_permission_doctypes]
else:
user_permission_doctypes = [user_permissions.keys()]
if len(user_permission_doctypes) > 1:
# OPTIMIZATION
# if intersection exists, use that to reduce the amount of querying
# for example, [["Blogger", "Blog Category"], ["Blogger"]], should only search in [["Blogger"]] as the first and condition becomes redundant
common = user_permission_doctypes[0]
for i in xrange(1, len(user_permission_doctypes), 1):
common = list(set(common).intersection(set(user_permission_doctypes[i])))
if not common:
break
if common:
# is common one of the user_permission_doctypes set?
for doctypes in user_permission_doctypes:
# are these lists equal?
if set(common) == set(doctypes):
user_permission_doctypes = [common]
break
return user_permission_doctypes
def reset_perms(doctype):
"""Reset permissions for given doctype."""
from frappe.desk.notifications import delete_notification_count_for
delete_notification_count_for(doctype)
frappe.db.sql("""delete from tabDocPerm where parent=%s""", doctype)
frappe.reload_doc(frappe.db.get_value("DocType", doctype, "module"),
"DocType", doctype, force=True)
| {
"content_hash": "4dce06f278cef33fe6c2151dc61125cb",
"timestamp": "",
"source": "github",
"line_count": 258,
"max_line_length": 142,
"avg_line_length": 35.46124031007752,
"alnum_prop": 0.72292053776369,
"repo_name": "gangadharkadam/v5_frappe",
"id": "c384689a0dce4037d0061d7b6efcfe4555197554",
"size": "9253",
"binary": false,
"copies": "4",
"ref": "refs/heads/v5.0",
"path": "frappe/permissions.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "152220"
},
{
"name": "HTML",
"bytes": "111716"
},
{
"name": "JavaScript",
"bytes": "1227854"
},
{
"name": "Python",
"bytes": "969285"
},
{
"name": "Shell",
"bytes": "517"
}
],
"symlink_target": ""
} |
import os
import mock
from os_brick.initiator import connector
from nova import exception
from nova.tests.unit.virt.libvirt.volume import test_volume
from nova import utils
from nova.virt.libvirt.volume import vzstorage
class LibvirtVZStorageTestCase(test_volume.LibvirtVolumeBaseTestCase):
"""Tests the libvirt vzstorage volume driver."""
def setUp(self):
super(LibvirtVZStorageTestCase, self).setUp()
self.mnt_base = '/mnt'
self.flags(vzstorage_mount_point_base=self.mnt_base, group='libvirt')
self.flags(vzstorage_cache_path="/tmp/ssd-cache/%(cluster_name)s",
group='libvirt')
def test_libvirt_vzstorage_driver(self):
libvirt_driver = vzstorage.LibvirtVZStorageVolumeDriver(self.fake_host)
self.assertIsInstance(libvirt_driver.connector,
connector.RemoteFsConnector)
def test_libvirt_vzstorage_driver_opts_negative(self):
"""Test that custom options cannot duplicate the configured"""
bad_opts = [
["-c", "clus111", "-v"],
["-l", "/var/log/pstorage.log", "-L", "5x5"],
["-u", "user1", "-p", "pass1"],
["-v", "-R", "100", "-C", "/ssd"],
]
for opts in bad_opts:
self.flags(vzstorage_mount_opts=opts, group='libvirt')
self.assertRaises(exception.NovaException,
vzstorage.LibvirtVZStorageVolumeDriver,
self.fake_host)
def test_libvirt_vzstorage_driver_share_fmt_neg(self):
drv = vzstorage.LibvirtVZStorageVolumeDriver(self.fake_host)
wrong_export_string = 'mds1, mds2:/testcluster:passwd12111'
connection_info = {'data': {'export': wrong_export_string,
'name': self.name}}
err_pattern = ("^Valid share format is "
"\[mds\[,mds1\[\.\.\.\]\]:/\]clustername\[:password\]$")
self.assertRaisesRegex(exception.InvalidVolume,
err_pattern,
drv.connect_volume,
connection_info,
self.disk_info)
def test_libvirt_vzstorage_driver_connect(self):
def brick_conn_vol(data):
return {'path': 'vstorage://testcluster'}
drv = vzstorage.LibvirtVZStorageVolumeDriver(self.fake_host)
drv.connector.connect_volume = brick_conn_vol
export_string = 'testcluster'
connection_info = {'data': {'export': export_string,
'name': self.name}}
drv.connect_volume(connection_info, self.disk_info)
self.assertEqual('vstorage://testcluster',
connection_info['data']['device_path'])
self.assertEqual('-u stack -g qemu -m 0770 '
'-l /var/log/pstorage/testcluster/nova.log.gz '
'-C /tmp/ssd-cache/testcluster',
connection_info['data']['options'])
def test_libvirt_vzstorage_driver_disconnect(self):
drv = vzstorage.LibvirtVZStorageVolumeDriver(self.fake_host)
drv.connector.disconnect_volume = mock.MagicMock()
conn = {'data': self.disk_info}
drv.disconnect_volume(conn, self.disk_info)
drv.connector.disconnect_volume.assert_called_once_with(
self.disk_info, None)
def test_libvirt_vzstorage_driver_get_config(self):
libvirt_driver = vzstorage.LibvirtVZStorageVolumeDriver(self.fake_host)
export_string = 'vzstorage'
export_mnt_base = os.path.join(self.mnt_base,
utils.get_hash_str(export_string))
file_path = os.path.join(export_mnt_base, self.name)
connection_info = {'data': {'export': export_string,
'name': self.name,
'device_path': file_path}}
conf = libvirt_driver.get_config(connection_info, self.disk_info)
self.assertEqual('file', conf.source_type)
self.assertEqual(file_path, conf.source_path)
self.assertEqual('raw', conf.driver_format)
self.assertEqual('writethrough', conf.driver_cache)
| {
"content_hash": "e9380ab261d24b062e243e6c874353a0",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 79,
"avg_line_length": 43.88775510204081,
"alnum_prop": 0.5773076028830505,
"repo_name": "vmturbo/nova",
"id": "23adb8d52b64b8e01bdef518812e78bd14cb5af5",
"size": "4874",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "nova/tests/unit/virt/libvirt/volume/test_vzstorage.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "601"
},
{
"name": "PHP",
"bytes": "4503"
},
{
"name": "Python",
"bytes": "18983608"
},
{
"name": "Shell",
"bytes": "31813"
},
{
"name": "Smarty",
"bytes": "307089"
}
],
"symlink_target": ""
} |
"""
Retina-inspired preprocessing as described in
Salakhutdinov, R. and Hinton, G. Deep Boltzmann machines.
In *AISTATS* 2009.
"""
import numpy
from pylearn2.datasets.dense_design_matrix import DefaultViewConverter
from pylearn2.space import Conv2DSpace
def foveate_channel(img, rings, output, start_idx):
"""For a given channel (image), perform pooling on peripheral vision.
.. todo::
Write parameter list
"""
ring_w = numpy.sum(rings)
# extract image center, which remains dense
inner_img = img[:, ring_w : img.shape[1] - ring_w , ring_w : img.shape[2] - ring_w]
# flatten and write to dense output matrix
inner_img = inner_img.reshape(len(output), -1)
end_idx = start_idx + inner_img.shape[1]
output[:, start_idx : end_idx] = inner_img
# start by downsampling the periphery of the images
idx = 0
start_idx = end_idx
for rd in rings:
# downsample the ring with top-left corner (idx,idx) of width rd
# results are written in output[start_idx:]
start_idx = downsample_ring(img, idx, rd, output, start_idx)
idx += rd
return start_idx
def downsample_ring(img, coord, width, output, start_idx):
"""
.. todo::
WRITEME
Parameters
----------
img : WRITEME
numpy matrix in topological order
(batch size, rows, cols, channels)
coord : WRITEME
perform average pooling starting at coordinate (coord,coord)
width : WRITEME
width of "square ring" to average pool
output : WRITEME
dense design matrix, of shape (batch size, rows*cols*channels)
start_idx : WRITEME
column index where to start writing the output
"""
(img_h,img_w) = img.shape[1:3]
# left column, full height
start_idx = downsample_rect(img, coord, coord, img_h - coord, coord + width, width, output, start_idx)
# right column, full height
start_idx = downsample_rect(img, coord, img_w - coord - width, img_h - coord, img_w - coord, width, output, start_idx)
# top row, between columns
start_idx = downsample_rect(img, coord, coord + width, coord + width, img_w - coord - width, width, output, start_idx)
# bottom row, between columns
start_idx = downsample_rect(img, img_h - coord - width, coord + width, img_h - coord, img_w - coord - width, width, output, start_idx)
return start_idx
def downsample_rect(img, start_row, start_col, end_row, end_col, width, output, start_idx):
"""
.. todo::
WRITEME
Parameters
----------
img : WRITEME
numpy matrix in topological order
(batch size, rows, cols, channels)
start_row : WRITEME
row index of top-left corner of rectangle to average pool
start_col : WRITEME
col index of top-left corner of rectangle to average pool
end_row : WRITEME
row index of bottom-right corner of rectangle to average pool
end_col : WRITEME
col index of bottom-right corner of rectangle to average pool
width : WRITEME
take the mean over rectangular block of this width
output : WRITEME
dense design matrix, of shape (batch size, rows*cols*channels)
start_idx : WRITEME
column index where to start writing the output
"""
idx = start_idx
for i in xrange(start_row, end_row - width + 1, width):
for j in xrange(start_col, end_col - width + 1, width):
block = img[:, i:i+width, j:j+width]
output[:,idx] = numpy.apply_over_axes(numpy.mean, block, axes=[1,2])[:,0,0]
idx += 1
return idx
def defoveate_channel(img, rings, dense_input, start_idx):
"""
Defoveate a single channel of the DenseDesignMatrix dense_input into the
variable, stored in topological ordering.
Parameters
----------
img : WRITEME
channel for defoveated image of shape (batch, img_h, img_w)
rings : WRITEME
list of ring_sizes which were used to generate dense_input
dense_input : WRITEME
DenseDesignMatrix containing foveated dataset, of shape
(batch, dims)
start_idx : WRITEME
channel pointed to by img starts at dense_input[start_idx]
"""
ring_w = numpy.sum(rings)
# extract image center, which remains dense
inner_h = img.shape[1] - 2*ring_w
inner_w = img.shape[2] - 2*ring_w
end_idx = start_idx + inner_h * inner_w
inner_img = dense_input[:, start_idx : end_idx].reshape(-1, inner_h, inner_w)
# now restore image center in uncompressed image
img[:, ring_w:ring_w+inner_h, ring_w:ring_w+inner_w] = inner_img
# now undo downsampling along the periphery
idx = 0
start_idx = end_idx
for rd in rings:
# downsample the ring with top-left corner (idx,idx) of width rd
# results are written in img[idx:idx+rd, idx:idx+rd]
start_idx = restore_ring(img, idx, rd, dense_input, start_idx)
idx += rd
return start_idx
def restore_ring(output, coord, width, dense_input, start_idx):
"""
.. todo::
WRITEME
Parameters
----------
output : WRITEME
output matrix in topological order
(batch, height, width, channels)
coord : WRITEME
perform average pooling starting at coordinate (coord,coord)
width : WRITEME
width of "square ring" to average pool
dense_input : WRITEME
dense design matrix to convert (batchsize, dims)
start_idx : WRITEME
column index where to start writing the output
"""
(img_h, img_w) = output.shape[1:3]
# left column, full height
start_idx = restore_rect(output, coord, coord, img_h - coord, coord + width, width, dense_input, start_idx)
# right column, full height
start_idx = restore_rect(output, coord, img_w - coord - width, img_h - coord, img_w - coord, width, dense_input, start_idx)
# top row, between columns
start_idx = restore_rect(output, coord, coord + width, coord + width, 96 - coord - width, width, dense_input, start_idx)
# bottom row, between columns
start_idx = restore_rect(output, img_h - coord - width, coord + width, img_h - coord, img_w - coord - width, width, dense_input, start_idx)
return start_idx
def restore_rect(output, start_row, start_col, stop_row, stop_col, width, dense_input, start_idx):
"""
.. todo::
WRITEME
Parameters
----------
output : WRITEME
output matrix in topological order
(batch, height, width, channels)
start_row : WRITEME
row index of top-left corner of rectangle to average pool
start_col : WRITEME
col index of top-left corner of rectangle to average pool
end_row : WRITEME
row index of bottom-right corner of rectangle to average pool
end_col : WRITEME
col index of bottom-right corner of rectangle to average pool
width : WRITEME
take the mean over rectangular block of this width
dense_input : WRITEME
dense design matrix to convert (batchsize, dims)
start_idx : WRITEME
column index where to start writing the output
"""
idx = start_idx
for i in xrange(start_row, stop_row - width + 1, width):
for j in xrange(start_col, stop_col - width + 1, width):
# broadcast along the width and height of the block
output[:, i:i+width, j:j+width] = dense_input[:, idx][:, None, None]
idx += 1
return idx
def get_encoded_size(img_h, img_w, rings):
"""
.. todo::
WRITEME
"""
pool_len = 0
# count number of pixels after compression
for r in rings:
if (img_h%r) != 0 or (img_w%r) != 0:
raise ValueError('Image width (%i) or height (%i) is not a multiple of ring size %i' %
(img_h, img_w, r))
pool_len += 2*img_h/r + 2*(img_w - 2*r)/r
img_h -= 2*r
img_w -= 2*r
return pool_len + img_h * img_w
def encode(topo_X, rings):
"""
.. todo::
WRITEME
Parameters
----------
topo_X : WRITEME
dataset matrix in topological format (batch, rows, cols, chans)
rings : WRITEME
list of ring_sizes which were used to generate dense_input
"""
(batch_size, img_h, img_w, chans) = topo_X.shape
# determine output shape
out_size = get_encoded_size(img_h, img_w, rings)
output = numpy.zeros((batch_size, out_size * chans))
start_idx = 0
# perform retina encoding on each channel separately
for chan_i in xrange(chans):
channel = topo_X[..., chan_i]
start_idx = foveate_channel(channel, rings, output, start_idx)
return output
def decode(dense_X, img_shp, rings):
"""
.. todo::
WRITEME
Parameters
----------
dense_X : WRITEME
matrix in DenseDesignMatrix format (batch, dim)
img_shp : WRITEME
tuple of image dimensions (rows, cols, chans)
rings : WRITEME
list of ring_sizes which were used to generate dense_input
"""
out_shp = [len(dense_X)] + list(img_shp)
output = numpy.zeros(out_shp)
start_idx = 0
# perform retina encoding on each channel separately
for chan_i in xrange(out_shp[-1]):
channel = output[..., chan_i]
start_idx = defoveate_channel(channel, rings, dense_X, start_idx)
return output
class RetinaEncodingBlock(object):
"""
.. todo::
WRITEME
Parameters
----------
rings : WRITEME
"""
def __init__(self, rings):
self.rings = rings
def perform(self, V):
assert V.ndim == 4
return encode(V, self.rings)
def apply(self, dataset, can_fit=False):
topo_X = dataset.get_topological_view()
fov_X = encode(topo_X, self.rings)
dataset.set_design_matrix(fov_X)
class RetinaDecodingBlock(object):
"""
.. todo::
WRITEME
Parameters
----------
img_shp : WRITEME
rings : WRITEME
"""
def __init__(self, img_shp, rings):
"""
.. todo::
WRITEME
"""
self.img_shp = img_shp
self.rings = rings
def apply(self, dataset, can_fit=False):
"""
.. todo::
WRITEME
"""
X = dataset.get_design_matrix()
topo_X = self.perform(X)
dataset.set_topological_view(topo_X)
def perform(self, X):
"""
.. todo::
WRITEME
"""
return decode(X, self.img_shp, self.rings)
class RetinaCodingViewConverter(DefaultViewConverter):
"""
.. todo::
WRITEME
Parameters
----------
shape : iterable
List or tuple of three ints: rows, cols, channels
rings : WRITEME
"""
def __init__(self, shape, rings):
self.shape = shape
self.rings = rings
rows, cols, channels = shape
self.topo_space = Conv2DSpace(shape=[rows, cols], num_channels=channels)
self.decoder = RetinaDecodingBlock(shape, rings)
self.encoder = RetinaEncodingBlock(rings)
def design_mat_to_topo_view(self, X):
"""
.. todo::
WRITEME
"""
return self.decoder.perform(X)
def design_mat_to_weights_view(self, X):
"""
.. todo::
WRITEME
"""
return self.design_mat_to_topo_view(X)
def topo_view_to_design_mat(self, V):
"""
.. todo::
WRITEME
"""
return self.encoder.perform(V)
| {
"content_hash": "7e44daaa796adef3bb9af1b7ee02d72a",
"timestamp": "",
"source": "github",
"line_count": 404,
"max_line_length": 143,
"avg_line_length": 28.455445544554454,
"alnum_prop": 0.6018615170494085,
"repo_name": "ml-lab/pylearn2",
"id": "5caa4bb01e354fb1bb97ad686dfe158b3cf6fa5a",
"size": "11496",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "pylearn2/datasets/retina.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
"""
#;+
#; NAME:
#; spec_guis
#; Version 1.0
#;
#; PURPOSE:
#; Module for Spectroscopy Guis with QT
#; These call pieces from spec_widgets
#; 12-Dec-2014 by JXP
#;-
#;------------------------------------------------------------------------------
"""
from __future__ import print_function, absolute_import, division, unicode_literals
# Import libraries
import numpy as np
import imp
import glob
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from matplotlib import rcParams
from astropy.units import Quantity
from astropy import units as u
from xastropy.xutils import xdebug as xdb
from xastropy.xguis import spec_widgets as xspw
from xastropy.xguis import utils as xxgu
xa_path = imp.find_module('xastropy')[1]
#class XSpecGui(QtGui.QMainWindow):
#class XAbsIDGui(QtGui.QMainWindow):
#class XVelPltGui(QtGui.QDialog):
# GUI for Identifying many (all) Abs Systems in a Spectrum
class XAbsIDGui(QtGui.QMainWindow):
''' GUI to analyze absorption systems in a spectrum
16-Dec-2014 by JXP
'''
def __init__(self, inspec, parent=None, abssys_dir=None, absid_list=None, norm=True,
srch_id=True, id_dir='ID_LINES/'):
QtGui.QMainWindow.__init__(self, parent)
'''
spec = Spectrum1D
second_file = Second spectrum file (e.g. COS + STIS)
'''
# Build a widget combining several others
self.main_widget = QtGui.QWidget()
# Status bar
self.create_status_bar()
# Initialize
if absid_list is None:
# Automatically search for ID files
if srch_id:
absid_list = glob.glob(id_dir+'*id.fits')
else:
absid_list = []
# Grab the pieces and tie together
self.abssys_widg = xspw.AbsSysWidget(absid_list)
self.pltline_widg = xspw.PlotLinesWidget(status=self.statusBar)
self.spec_widg = xspw.ExamineSpecWidget(inspec,status=self.statusBar,
llist=self.pltline_widg.llist, norm=norm,
abs_sys=self.abssys_widg.abs_sys)
self.pltline_widg.spec_widg = self.spec_widg
# Connections
self.spec_widg.canvas.mpl_connect('button_press_event', self.on_click)
self.spec_widg.canvas.mpl_connect('key_press_event', self.on_key)
self.abssys_widg.refine_button.clicked.connect(self.refine_abssys)
# Layout
anly_widg = QtGui.QWidget()
anly_widg.setMaximumWidth(300)
anly_widg.setMinimumWidth(150)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.pltline_widg)
vbox.addWidget(self.abssys_widg)
anly_widg.setLayout(vbox)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(self.spec_widg)
hbox.addWidget(anly_widg)
self.main_widget.setLayout(hbox)
# Point MainWindow
self.setCentralWidget(self.main_widget)
def create_status_bar(self):
self.status_text = QtGui.QLabel("XAbsID")
self.statusBar().addWidget(self.status_text, 1)
def on_key(self,event):
if event.key == 'v': # Stack plot
if self.spec_widg.vplt_flg == 1:
self.abssys_widg.add_fil(self.spec_widg.outfil)
self.abssys_widg.reload()
elif self.spec_widg.vplt_flg == -1:
return
# Update line list
idx = self.pltline_widg.lists.index(self.spec_widg.llist['List'])
self.pltline_widg.llist_widget.setCurrentRow(idx)
elif event.key == '?': # Check for a match with known systems
wv_chosen = event.xdata
# Load grb
llist = xspw.set_llist('grb.lst')
# Loop through systems
for iabs_sys in self.abssys_widg.all_abssys:
z = iabs_sys.zabs
wvobs = np.array((1+z) * llist['grb.lst']['wrest'])
mtwv = np.where( np.abs( wvobs-wv_chosen ) < 0.2 )[0]
for imt in mtwv:
#QtCore.pyqtRemoveInputHook()
#xdb.set_trace()
#QtCore.pyqtRestoreInputHook()
print('z={:g}, {:s}, f={:g}'.format(z,
llist['grb.lst']['name'][imt],
llist['grb.lst']['fval'][imt]))
if len(mtwv) == 0:
print('No match. wrest={:g} for z={:g}'.format(wv_chosen/(1+z), z))
def on_click(self,event):
if event.button == 3: # Set redshift
# Line list?
try:
self.pltline_widg.llist['List']
except KeyError:
print('Set a line list first!!')
return
#
if self.pltline_widg.llist[self.pltline_widg.llist['List']] == 'None':
return
self.select_line_widg = xspw.SelectLineWidget(
self.pltline_widg.llist[self.pltline_widg.llist['List']]._data)
self.select_line_widg.exec_()
line = self.select_line_widg.line
if line.strip() == 'None':
return
#
quant = line.split('::')[1].lstrip()
spltw = quant.split(' ')
wrest = Quantity(float(spltw[0]), unit=spltw[1])
z = event.xdata/wrest.value - 1.
self.pltline_widg.llist['z'] = z
self.statusBar().showMessage('z = {:f}'.format(z))
self.pltline_widg.zbox.setText(self.pltline_widg.zbox.z_frmt.format(
self.pltline_widg.llist['z']))
# Draw
self.spec_widg.on_draw()
def refine_abssys(self):
item = self.abssys_widg.abslist_widget.selectedItems()
if len(item) != 1:
self.statusBar().showMessage('AbsSys: Must select only 1 system!')
print('AbsSys: Must select only 1 system!')
txt = item[0].text()
ii = self.abssys_widg.all_items.index(txt)
iabs_sys = self.abssys_widg.all_abssys[ii]
#QtCore.pyqtRemoveInputHook()
#xdb.set_trace()
#QtCore.pyqtRestoreInputHook()
# Launch
gui = XVelPltGui(self.spec_widg.spec, outfil=iabs_sys.absid_file,
abs_sys=iabs_sys, norm=self.spec_widg.norm)
gui.exec_()
# ##################################
# GUI for velocity plot
class XVelPltGui(QtGui.QDialog):
''' GUI to analyze absorption systems in a spectrum
24-Dec-2014 by JXP
'''
def __init__(self, ispec, z=None, parent=None, llist=None, norm=True,
vmnx=[-300., 300.]*u.km/u.s, abs_sys=None, outfil='dum_ID.fits',
sel_wv=None):
'''
spec = Filename or Spectrum1D
Norm: Bool (False)
Normalized spectrum?
abs_sys: AbsSystem
Absorption system class
sel_wv: Selected wavelength. Used to inspect a single, unknown line
'''
super(XVelPltGui, self).__init__(parent)
# Initialize
self.abs_sys = abs_sys
if self.abs_sys is not None:
self.z = self.abs_sys.zabs
else:
if z is None:
raise ValueError('XVelPlt: Need to set abs_sys or z!')
self.z = z
self.vmnx = vmnx
self.outfil = outfil
self.norm = norm
self.sel_wv = sel_wv
# Grab the pieces and tie together
self.vplt_widg = xspw.VelPlotWidget(ispec, abs_sys=self.abs_sys, llist=llist,
vmnx=self.vmnx, z=self.z, norm=self.norm)
self.pltline_widg = xspw.PlotLinesWidget(init_llist=self.vplt_widg.llist,
init_z=self.z)
#self.pltline_widg.spec_widg = self.vplt_widg
self.slines = xspw.SelectedLinesWidget(self.vplt_widg.llist[self.vplt_widg.llist['List']],
init_select=self.vplt_widg.llist['show_line'],
plot_widget=self.vplt_widg)
# Connections
self.pltline_widg.llist_widget.currentItemChanged.connect(self.on_llist_change)
self.connect(self.pltline_widg.zbox, QtCore.SIGNAL('editingFinished ()'), self.setz)
self.vplt_widg.canvas.mpl_connect('key_press_event', self.on_key)
# Outfil
wbtn = QtGui.QPushButton('Write', self)
wbtn.setAutoDefault(False)
wbtn.clicked.connect(self.write_out)
self.out_box = QtGui.QLineEdit()
self.out_box.setText(self.outfil)
self.connect(self.out_box, QtCore.SIGNAL('editingFinished ()'), self.set_outfil)
# Quit
buttons = QtGui.QWidget()
wqbtn = QtGui.QPushButton('Write+Quit', self)
wqbtn.setAutoDefault(False)
wqbtn.clicked.connect(self.write_quit)
qbtn = QtGui.QPushButton('Quit', self)
qbtn.setAutoDefault(False)
qbtn.clicked.connect(self.quit)
# Sizes
lines_widg = QtGui.QWidget()
lines_widg.setMaximumWidth(300)
lines_widg.setMinimumWidth(200)
# Layout
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.pltline_widg)
vbox.addWidget(self.slines)
vbox.addWidget(wbtn)
vbox.addWidget(self.out_box)
# Write/Quit buttons
hbox1 = QtGui.QHBoxLayout()
hbox1.addWidget(wqbtn)
hbox1.addWidget(qbtn)
buttons.setLayout(hbox1)
#
vbox.addWidget(buttons)
lines_widg.setLayout(vbox)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(self.vplt_widg)
hbox.addWidget(lines_widg)
self.setLayout(hbox)
# Initial draw
self.vplt_widg.on_draw()
# Change z
def on_key(self,event):
if event.key == 'z':
self.z = self.vplt_widg.z
self.pltline_widg.llist['z'] = self.z
self.pltline_widg.zbox.setText(self.pltline_widg.zbox.z_frmt.format(self.z))
if event.key == 'T': # Try another rest wavelength for input line
# Get line from User
self.select_line_widg = xspw.SelectLineWidget(
self.pltline_widg.llist[self.pltline_widg.llist['List']]._data)
self.select_line_widg.exec_()
line = self.select_line_widg.line
quant = line.split('::')[1].lstrip()
spltw = quant.split(' ')
wrest = Quantity(float(spltw[0]), unit=spltw[1])
# Set redshift
self.z = self.sel_wv / wrest - 1.
print('Setting z = {:g}'.format(self.z))
self.pltline_widg.llist['z'] = self.z
self.pltline_widg.zbox.setText(self.pltline_widg.zbox.z_frmt.format(self.z))
self.vplt_widg.z = self.pltline_widg.llist['z']
# Reset
self.vplt_widg.init_lines()
self.vplt_widg.on_draw()
# Set z from pltline_widg
def setz(self):
self.vplt_widg.abs_sys.zabs = self.pltline_widg.llist['z']
self.vplt_widg.z = self.pltline_widg.llist['z']
self.z = self.pltline_widg.llist['z']
self.vplt_widg.on_draw()
# Change list of lines to choose from
def on_llist_change(self):
llist = self.pltline_widg.llist
all_lines = list( llist[llist['List']]._data['wrest'] )
# Set selected
abs_sys = self.vplt_widg.abs_sys
wrest = [line.wrest for line in abs_sys.lines]
select = []
for iwrest in wrest:
try:
select.append(all_lines.index(iwrest))
except ValueError:
pass
select.sort()
# GUIs
self.vplt_widg.llist['List'] = llist['List']
self.vplt_widg.llist['show_line'] = select
self.vplt_widg.idx_line = 0
self.slines.selected = select
#QtCore.pyqtRemoveInputHook()
#xdb.set_trace()
#QtCore.pyqtRestoreInputHook()
self.slines.on_list_change(llist[llist['List']])
# Write
def set_outfil(self):
self.outfil = str(self.out_box.text())
print('XVelPlot: Will write to {:s}'.format(self.outfil))
# Write
def write_out(self):
self.vplt_widg.abs_sys.absid_file = self.outfil
self.vplt_widg.abs_sys.write_absid_file()
# Write + Quit
def write_quit(self):
self.write_out()
self.flg_quit = 1
self.abs_sys = self.vplt_widg.abs_sys
self.done(1)
# Write + Quit
def quit(self):
#self.abs_sys = self.vplt_widg.abs_sys # Have to write to pass back
self.flg_quit = 0
self.done(1)
# x_specplot replacement
class XAODMGui(QtGui.QDialog):
''' GUI to show AODM plots
28-Dec-2014 by JXP
'''
def __init__(self, spec, z, wrest, vmnx=[-300., 300.]*u.km/u.s, parent=None, norm=True):
super(XAODMGui, self).__init__(parent)
'''
spec = Spectrum1D
'''
# Grab the pieces and tie together
self.aodm_widg = xspw.AODMWidget(spec,z,wrest,vmnx=vmnx,norm=norm)
self.aodm_widg.canvas.mpl_connect('key_press_event', self.on_key)
vbox = QtGui.QVBoxLayout()
vbox.addWidget(self.aodm_widg)
self.setLayout(vbox)
self.aodm_widg.on_draw()
def on_key(self,event):
if event.key == 'q': # Quit
self.done(1)
# Script to run XAbsID from the command line
def run_xabsid():
import argparse
parser = argparse.ArgumentParser(description='Script for XSpec')
parser.add_argument("flag", type=int, help="GUI flag (ignored)")
parser.add_argument("file", type=str, help="Spectral file")
parser.add_argument("--un_norm", help="Spectrum is NOT normalized",
action="store_true")
parser.add_argument("-id_dir", type=str,
help="Directory for ID files (ID_LINES is default)")
parser.add_argument("-secondfile", type=str, help="Second spectral file")
parser.add_argument("-thirdfile", type=str, help="Third spectral file")
args = parser.parse_args()
# Normalized?
norm=True
if args.un_norm:
norm=False
infile = args.file
# Second spectral file?
if args.secondfile:
infile = [infile, args.secondfile]
if args.thirdfile:
infile.append(args.thirdfile)
# Launch
app = QtGui.QApplication(sys.argv)
gui = XAbsIDGui(infile, norm=norm)
gui.show()
app.exec_()
# Script to run XVelPltGui from the command line or ipython
def run_xvelp(*args, **kwargs):
'''
Runs the XVelPltGui
Command line
or from Python
Examples:
1. python ~/xastropy/xastropy/xguis/spec_guis.py 3
2. spec_guis.run_xvelp(filename)
3. spec_guis.run_xvelp(spec1d)
'''
import argparse
from specutils import Spectrum1D
xdb.set_trace() # DEPRECATED FOR NOW
parser = argparse.ArgumentParser(description='Parse for XVelPlt')
parser.add_argument("flag", type=int, help="GUI flag (ignored)")
parser.add_argument("file", type=str, help="Spectral file")
parser.add_argument("-zsys", type=float, help="System Redshift")
parser.add_argument("--un_norm", help="Spectrum is NOT normalized",
action="store_true")
if len(args) == 0:
pargs = parser.parse_args()
else: # better know what you are doing!
if isinstance(args[0],(Spectrum1D,tuple)):
if not kwargs['rerun']:
app = QtGui.QApplication(sys.argv)
xdb.set_trace()
gui = XVelPltGui(args[0], **kwargs)
gui.exec_()
#gui.show()
#app.exec_()
return gui, app
else: # String parsing
largs = ['1'] + [iargs for iargs in args]
pargs = parser.parse_args(largs)
# Normalized?
norm=True
if pargs.un_norm:
norm=False
# Second spectral file?
try:
zsys = pargs.zsys
except AttributeError:
zsys=None
xdb.set_trace() # Not setup for command line yet
app = QtGui.QApplication(sys.argv)
gui = XSpecGui(pargs.file, zsys=zsys, norm=norm)
gui.show()
app.exec_()
return gui
# ################
if __name__ == "__main__":
import sys
from linetools.spectra import io as lsi
from xastropy.igm import abs_sys as xiabs
if len(sys.argv) == 1: # TESTING
flg_fig = 0
#flg_fig += 2**0 # XSpec
#flg_fig += 2**1 # XAbsID
#flg_fig += 2**2 # XVelPlt Gui
#flg_fig += 2**3 # XVelPlt Gui without ID list; Also tests select wave
#flg_fig += 2**4 # XAODM Gui
# Read spectrum
spec_fil = '/u/xavier/Keck/HIRES/RedData/PH957/PH957_f.fits'
spec = lsi.readspec(spec_fil)
# XSpec
if (flg_fig % 2) == 1:
app = QtGui.QApplication(sys.argv)
gui = XSpecGui(spec)
gui.show()
app.exec_()
# XAbsID
if (flg_fig % 2**2) >= 2**1:
#spec_fil = '/u/xavier/PROGETTI/LLSZ3/data/normalize/SDSSJ1004+0018_nF.fits'
#spec = xspec.readwrite.readspec(spec_fil)
#norm = True
spec_fil = '/Users/xavier/Dropbox/CASBAH/jxp_analysis/FBQS0751+2919/fbqs0751_nov2014bin.fits'
norm = False
absid_fil = '/Users/xavier/paper/LLS/Optical/Data/Analysis/MAGE/SDSSJ1004+0018_z2.746_id.fits'
absid_fil2 = '/Users/xavier/paper/LLS/Optical/Data/Analysis/MAGE/SDSSJ2348-1041_z2.997_id.fits'
app = QtGui.QApplication(sys.argv)
gui = XAbsIDGui(spec_fil,norm=norm) #,absid_list=[absid_fil, absid_fil2])
gui.show()
app.exec_()
# XVelPlt with existing AbsID file
if (flg_fig % 2**3) >= 2**2:
spec_fil = '/u/xavier/PROGETTI/LLSZ3/data/normalize/SDSSJ1004+0018_nF.fits'
#spec = xspec.readwrite.readspec(spec_fil)
absid_fil = '/Users/xavier/paper/LLS/Optical/Data/Analysis/MAGE/SDSSJ1004+0018_z2.746_id.fits'
abs_sys = xiabs.abssys_utils.Generic_System(None)
abs_sys.parse_absid_file(absid_fil)
#
app = QtGui.QApplication(sys.argv)
app.setApplicationName('XVelPlt')
gui = XVelPltGui(spec_fil,abs_sys=abs_sys,
outfil='/Users/xavier/Desktop/tmp.fits')
gui.show()
sys.exit(app.exec_())
# XVelPlt without existing AbsID file
if (flg_fig % 2**4) >= 2**3:
#spec_fil = '/u/xavier/PROGETTI/LLSZ3/data/normalize/SDSSJ1004+0018_nF.fits'
#z=2.746
#outfil='/Users/xavier/Desktop/J1004+0018_z2.746_id.fits'
spec_fil = '/Users/xavier/Dropbox/CASBAH/jxp_analysis/FBQS0751+2919/fbqs0751_nov2014bin.fits'
z=0.
outfil='/Users/xavier/Desktop/tmp.fits'
#
app = QtGui.QApplication(sys.argv)
app.setApplicationName('XVelPlt')
gui = XVelPltGui(spec_fil, z=z, outfil=outfil,norm=False, sel_wv=1526.80)
gui.show()
sys.exit(app.exec_())
# AODM GUI
if (flg_fig % 2**5) >= 2**4:
#spec_fil = '/Users/xavier/PROGETTI/LLSZ3/data/normalize/UM184_nF.fits'
#z=2.96916
#lines = [1548.195, 1550.770]
norm = True
spec_fil = '/Users/xavier/Dropbox/CASBAH/jxp_analysis/FBQS0751+2919/fbqs0751_nov2014bin.fits'
z=0.4391
lines = [1215.6701, 1025.7223] * u.AA
norm = False
# Launch
spec = lsi.readspec(spec_fil)
app = QtGui.QApplication(sys.argv)
app.setApplicationName('AODM')
main = XAODMGui(spec, z, lines, norm=norm)
main.show()
sys.exit(app.exec_())
else: # RUN A GUI
id_gui = int(sys.argv[1]) # 1 = XSpec, 2=XAbsId
if id_gui == 1:
run_xspec()
elif id_gui == 2:
run_xabsid()
elif id_gui == 3:
run_xvelp()
else:
raise ValueError('Unsupported flag for spec_guis')
| {
"content_hash": "005031a7f029ad1bb4fb9e9bb4ddde85",
"timestamp": "",
"source": "github",
"line_count": 576,
"max_line_length": 107,
"avg_line_length": 34.96875,
"alnum_prop": 0.5615132558832291,
"repo_name": "profxj/xastropy",
"id": "5f04ce8598c4605be7316491f98ffd12582f1a85",
"size": "20142",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "xastropy/xguis/spec_guis.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "36695"
},
{
"name": "OpenEdge ABL",
"bytes": "144038"
},
{
"name": "Python",
"bytes": "977152"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
import datetime
import io
from datetime import timedelta
import itertools
import time
from concurrent.futures import as_completed
from dateutil.tz import tzutc
import six
from botocore.exceptions import ClientError
from collections import OrderedDict
from c7n.actions import BaseAction
from c7n.filters import ValueFilter, Filter, OPERATORS
from c7n.filters.iamaccess import CrossAccountAccessFilter
from c7n.manager import resources
from c7n.query import QueryResourceManager, DescribeSource
from c7n.resolver import ValuesFrom
from c7n.utils import local_session, type_schema, chunks
@resources.register('iam-group')
class Group(QueryResourceManager):
class resource_type(object):
service = 'iam'
type = 'group'
enum_spec = ('list_groups', 'Groups', None)
detail_spec = None
filter_name = None
id = name = 'GroupName'
date = 'CreateDate'
dimension = None
config_type = "AWS::IAM::Group"
# Denotes this resource type exists across regions
global_resource = True
def get_resources(self, resource_ids, cache=True):
"""For IAM Groups on events, resource ids are Group Names."""
client = local_session(self.session_factory).client('iam')
resources = []
for rid in resource_ids:
try:
result = client.get_group(GroupName=rid)
except client.exceptions.NoSuchEntityException:
continue
group = result.pop('Group')
group['c7n:Users'] = result['Users']
resources.append(group)
return resources
@resources.register('iam-role')
class Role(QueryResourceManager):
class resource_type(object):
service = 'iam'
type = 'role'
enum_spec = ('list_roles', 'Roles', None)
detail_spec = None
filter_name = None
id = name = 'RoleName'
date = 'CreateDate'
dimension = None
config_type = "AWS::IAM::Role"
# Denotes this resource type exists across regions
global_resource = True
def get_resources(self, resource_ids, cache=True):
"""For IAM Roles on events, resource ids are role names."""
resources = []
client = local_session(self.session_factory).client('iam')
for rid in resource_ids:
try:
resources.append(client.get_role(RoleName=rid)['Role'])
except client.exceptions.NoSuchEntityException:
continue
return resources
@resources.register('iam-user')
class User(QueryResourceManager):
class resource_type(object):
service = 'iam'
type = 'user'
enum_spec = ('list_users', 'Users', None)
filter_name = None
id = name = 'UserName'
date = 'CreateDate'
dimension = None
config_type = "AWS::IAM::User"
# Denotes this resource type exists across regions
global_resource = True
def get_source(self, source_type):
if source_type == 'describe':
return DescribeUser(self)
return super(User, self).get_source(source_type)
class DescribeUser(DescribeSource):
def get_resources(self, resource_ids, cache=True):
client = local_session(self.manager.session_factory).client('iam')
resources = []
for rid in resource_ids:
try:
resources.append(client.get_user(UserName=rid).get('User'))
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchEntityException':
continue
raise
return resources
@resources.register('iam-policy')
class Policy(QueryResourceManager):
class resource_type(object):
service = 'iam'
type = 'policy'
enum_spec = ('list_policies', 'Policies', None)
id = 'PolicyId'
name = 'PolicyName'
date = 'CreateDate'
dimension = None
config_type = "AWS::IAM::Policy"
filter_name = None
# Denotes this resource type exists across regions
global_resource = True
arn_path_prefix = "aws:policy/"
def get_source(self, source_type):
if source_type == 'describe':
return DescribePolicy(self)
return super(Policy, self).get_source(source_type)
class DescribePolicy(DescribeSource):
def get_resources(self, resource_ids, cache=True):
client = local_session(self.manager.session_factory).client('iam')
results = []
for r in resource_ids:
try:
results.append(client.get_policy(PolicyArn=r)['Policy'])
except ClientError as e:
if e.response['Error']['Code'] == 'NoSuchEntityException':
continue
return results
@resources.register('iam-profile')
class InstanceProfile(QueryResourceManager):
class resource_type(object):
service = 'iam'
type = 'instance-profile'
enum_spec = ('list_instance_profiles', 'InstanceProfiles', None)
id = 'InstanceProfileId'
filter_name = None
name = 'InstanceProfileId'
date = 'CreateDate'
dimension = None
# Denotes this resource type exists across regions
global_resource = True
@resources.register('iam-certificate')
class ServerCertificate(QueryResourceManager):
class resource_type(object):
service = 'iam'
type = 'server-certificate'
enum_spec = ('list_server_certificates',
'ServerCertificateMetadataList',
None)
id = 'ServerCertificateId'
filter_name = None
name = 'ServerCertificateName'
date = 'Expiration'
dimension = None
# Denotes this resource type exists across regions
global_resource = True
class IamRoleUsage(Filter):
def get_permissions(self):
perms = list(itertools.chain([
self.manager.get_resource_manager(m).get_permissions()
for m in ['lambda', 'launch-config', 'ec2']]))
perms.extend(['ecs:DescribeClusters', 'ecs:DescribeServices'])
return perms
def service_role_usage(self):
results = set()
results.update(self.scan_lambda_roles())
results.update(self.scan_ecs_roles())
results.update(self.collect_profile_roles())
return results
def instance_profile_usage(self):
results = set()
results.update(self.scan_asg_roles())
results.update(self.scan_ec2_roles())
return results
def scan_lambda_roles(self):
manager = self.manager.get_resource_manager('lambda')
return [r['Role'] for r in manager.resources() if 'Role' in r]
def scan_ecs_roles(self):
results = []
client = local_session(self.manager.session_factory).client('ecs')
for cluster in client.describe_clusters()['clusters']:
services = client.list_services(
cluster=cluster['clusterName'])['serviceArns']
if services:
for service in client.describe_services(
cluster=cluster['clusterName'],
services=services)['services']:
if 'roleArn' in service:
results.append(service['roleArn'])
return results
def collect_profile_roles(self):
# Collect iam roles attached to instance profiles of EC2/ASG resources
profiles = set()
profiles.update(self.scan_asg_roles())
profiles.update(self.scan_ec2_roles())
manager = self.manager.get_resource_manager('iam-profile')
iprofiles = manager.resources()
results = []
for p in iprofiles:
if p['InstanceProfileName'] not in profiles:
continue
for role in p.get('Roles', []):
results.append(role['RoleName'])
return results
def scan_asg_roles(self):
manager = self.manager.get_resource_manager('launch-config')
return [r['IamInstanceProfile'] for r in manager.resources() if (
'IamInstanceProfile' in r)]
def scan_ec2_roles(self):
manager = self.manager.get_resource_manager('ec2')
results = []
for e in manager.resources():
# do not include instances that have been recently terminated
if e['State']['Name'] == 'terminated':
continue
profile_arn = e.get('IamInstanceProfile', {}).get('Arn', None)
if not profile_arn:
continue
# split arn to get the profile name
results.append(profile_arn.split('/')[-1])
return results
###################
# IAM Roles #
###################
@Role.filter_registry.register('used')
class UsedIamRole(IamRoleUsage):
"""Filter IAM roles that are either being used or not
Checks for usage on EC2, Lambda, ECS only
:example:
.. code-block:: yaml
policies:
- name: iam-role-in-use
resource: iam-role
filters:
- type: used
state: true
"""
schema = type_schema(
'used',
state={'type': 'boolean'})
def process(self, resources, event=None):
roles = self.service_role_usage()
if self.data.get('state', True):
return [r for r in resources if (
r['Arn'] in roles or r['RoleName'] in roles)]
return [r for r in resources if (
r['Arn'] not in roles and r['RoleName'] not in roles)]
@Role.filter_registry.register('unused')
class UnusedIamRole(IamRoleUsage):
"""Filter IAM roles that are either being used or not
This filter has been deprecated. Please use the 'used' filter
with the 'state' attribute to get unused iam roles
Checks for usage on EC2, Lambda, ECS only
:example:
.. code-block:: yaml
policies:
- name: iam-roles-not-in-use
resource: iam-role
filters:
- type: used
state: false
"""
schema = type_schema('unused')
def process(self, resources, event=None):
return UsedIamRole({'state': False}, self.manager).process(resources)
@Role.filter_registry.register('cross-account')
class RoleCrossAccountAccess(CrossAccountAccessFilter):
policy_attribute = 'AssumeRolePolicyDocument'
permissions = ('iam:ListRoles',)
schema = type_schema(
'cross-account',
# white list accounts
whitelist_from=ValuesFrom.schema,
whitelist={'type': 'array', 'items': {'type': 'string'}})
@Role.filter_registry.register('has-inline-policy')
class IamRoleInlinePolicy(Filter):
"""Filter IAM roles that have an inline-policy attached
True: Filter roles that have an inline-policy
False: Filter roles that do not have an inline-policy
:example:
.. code-block:: yaml
policies:
- name: iam-roles-with-inline-policies
resource: iam-role
filters:
- type: has-inline-policy
value: True
"""
schema = type_schema('has-inline-policy', value={'type': 'boolean'})
permissions = ('iam:ListRolePolicies',)
def _inline_policies(self, client, resource):
policies = client.list_role_policies(
RoleName=resource['RoleName'])['PolicyNames']
resource['c7n:InlinePolicies'] = policies
return resource
def process(self, resources, event=None):
c = local_session(self.manager.session_factory).client('iam')
res = []
value = self.data.get('value', True)
for r in resources:
r = self._inline_policies(c, r)
if len(r['c7n:InlinePolicies']) > 0 and value:
res.append(r)
if len(r['c7n:InlinePolicies']) == 0 and not value:
res.append(r)
return res
@Role.filter_registry.register('has-specific-managed-policy')
class SpecificIamRoleManagedPolicy(Filter):
"""Filter IAM roles that has a specific policy attached
For example, if the user wants to check all roles with 'admin-policy':
:example:
.. code-block:: yaml
policies:
- name: iam-roles-have-admin
resource: iam-role
filters:
- type: has-specific-managed-policy
value: admin-policy
"""
schema = type_schema('has-specific-managed-policy', value={'type': 'string'})
permissions = ('iam:ListAttachedRolePolicies',)
def _managed_policies(self, client, resource):
return [r['PolicyName'] for r in client.list_attached_role_policies(
RoleName=resource['RoleName'])['AttachedPolicies']]
def process(self, resources, event=None):
c = local_session(self.manager.session_factory).client('iam')
if self.data.get('value'):
return [r for r in resources if self.data.get('value') in self._managed_policies(c, r)]
return []
@Role.filter_registry.register('no-specific-managed-policy')
class NoSpecificIamRoleManagedPolicy(Filter):
"""Filter IAM roles that do not have a specific policy attached
For example, if the user wants to check all roles without 'ip-restriction':
:example:
.. code-block:: yaml
policies:
- name: iam-roles-no-ip-restriction
resource: iam-role
filters:
- type: no-specific-managed-policy
value: ip-restriction
"""
schema = type_schema('no-specific-managed-policy', value={'type': 'string'})
permissions = ('iam:ListAttachedRolePolicies',)
def _managed_policies(self, client, resource):
return [r['PolicyName'] for r in client.list_attached_role_policies(
RoleName=resource['RoleName'])['AttachedPolicies']]
def process(self, resources, event=None):
c = local_session(self.manager.session_factory).client('iam')
if self.data.get('value'):
return [r for r in resources if not self.data.get('value') in
self._managed_policies(c, r)]
return []
######################
# IAM Policies #
######################
@Policy.filter_registry.register('used')
class UsedIamPolicies(Filter):
"""Filter IAM policies that are being used
:example:
.. code-block:: yaml
policies:
- name: iam-policy-used
resource: iam-policy
filters:
- type: used
"""
schema = type_schema('used')
permissions = ('iam:ListPolicies',)
def process(self, resources, event=None):
return [r for r in resources if r['AttachmentCount'] > 0]
@Policy.filter_registry.register('unused')
class UnusedIamPolicies(Filter):
"""Filter IAM policies that are not being used
:example:
.. code-block:: yaml
policies:
- name: iam-policy-unused
resource: iam-policy
filters:
- type: unused
"""
schema = type_schema('unused')
permissions = ('iam:ListPolicies',)
def process(self, resources, event=None):
return [r for r in resources if r['AttachmentCount'] == 0]
@Policy.filter_registry.register('has-allow-all')
class AllowAllIamPolicies(Filter):
"""Check if IAM policy resource(s) have allow-all IAM policy statement block.
This allows users to implement CIS AWS check 1.24 which states that no
policy must exist with the following requirements.
Policy must have 'Action' and Resource = '*' with 'Effect' = 'Allow'
The policy will trigger on the following IAM policy (statement).
For example:
.. code-block: json
{
'Version': '2012-10-17',
'Statement': [{
'Action': '*',
'Resource': '*',
'Effect': 'Allow'
}]
}
Additionally, the policy checks if the statement has no 'Condition' or
'NotAction'
For example, if the user wants to check all used policies and filter on
allow all:
.. code-block:: yaml
- name: iam-no-used-all-all-policy
resource: iam-policy
filters:
- type: used
- type: has-allow-all
Note that scanning and getting all policies and all statements can take
a while. Use it sparingly or combine it with filters such as 'used' as
above.
"""
schema = type_schema('has-allow-all')
permissions = ('iam:ListPolicies', 'iam:ListPolicyVersions')
def has_allow_all_policy(self, client, resource):
statements = client.get_policy_version(
PolicyArn=resource['Arn'],
VersionId=resource['DefaultVersionId']
)['PolicyVersion']['Document']['Statement']
if isinstance(statements, dict):
statements = [statements]
for s in statements:
if ('Condition' not in s and
'Action' in s and
isinstance(s['Action'], six.string_types) and
s['Action'] == "*" and
'Resource' in s and
isinstance(s['Resource'], six.string_types) and
s['Resource'] == "*" and
s['Effect'] == "Allow"):
return True
return False
def process(self, resources, event=None):
c = local_session(self.manager.session_factory).client('iam')
results = [r for r in resources if self.has_allow_all_policy(c, r)]
self.log.info(
"%d of %d iam policies have allow all.",
len(results), len(resources))
return results
@Policy.action_registry.register('delete')
class PolicyDelete(BaseAction):
"""Delete an IAM Policy.
For example, if you want to automatically delete all unused IAM policies.
:example:
.. code-block:: yaml
- name: iam-delete-unused-policies
resource: iam-policy
filters:
- type: unused
actions:
- delete
"""
schema = type_schema('delete')
permissions = ('iam:DeletePolicy',)
def process(self, resources):
client = local_session(self.manager.session_factory).client('iam')
for r in resources:
if not r['Arn'].startswith("arn:aws:iam::aws:policy"):
self.log.debug('Deleting policy %s' % r['PolicyName'])
client.delete_policy(
PolicyArn=r['Arn'])
else:
self.log.debug('Cannot delete AWS managed policy %s' % r['PolicyName'])
###############################
# IAM Instance Profiles #
###############################
@InstanceProfile.filter_registry.register('used')
class UsedInstanceProfiles(IamRoleUsage):
"""Filter IAM profiles that are being used
:example:
.. code-block:: yaml
policies:
- name: iam-instance-profiles-in-use
resource: iam-profile
filters:
- type: used
"""
schema = type_schema('used')
def process(self, resources, event=None):
results = []
profiles = self.instance_profile_usage()
for r in resources:
if r['Arn'] in profiles or r['InstanceProfileName'] in profiles:
results.append(r)
self.log.info(
"%d of %d instance profiles currently in use." % (
len(results), len(resources)))
return results
@InstanceProfile.filter_registry.register('unused')
class UnusedInstanceProfiles(IamRoleUsage):
"""Filter IAM profiles that are not being used
:example:
.. code-block:: yaml
policies:
- name: iam-instance-profiles-not-in-use
resource: iam-profile
filters:
- type: unused
"""
schema = type_schema('unused')
def process(self, resources, event=None):
results = []
profiles = self.instance_profile_usage()
for r in resources:
if (r['Arn'] not in profiles or r['InstanceProfileName'] not in profiles):
results.append(r)
self.log.info(
"%d of %d instance profiles currently not in use." % (
len(results), len(resources)))
return results
###################
# IAM Users #
###################
class CredentialReport(Filter):
"""Use IAM Credential report to filter users.
The IAM Credential report ( https://goo.gl/sbEPtM ) aggregates
multiple pieces of information on iam users. This makes it highly
efficient for querying multiple aspects of a user that would
otherwise require per user api calls.
For example if we wanted to retrieve all users with mfa who have
never used their password but have active access keys from the
last month
.. code-block:: yaml
- name: iam-mfa-active-keys-no-login
resource: iam-user
filters:
- type: credential
key: mfa_active
value: true
- type: credential
key: password_last_used
value: absent
- type: credential
key: access_keys.last_used
value_type: age
value: 30
op: less-than
Credential Report Transforms
We perform some default transformations from the raw
credential report. Sub-objects (access_key_1, cert_2)
are turned into array of dictionaries for matching
purposes with their common prefixes stripped.
N/A values are turned into None, TRUE/FALSE are turned
into boolean values.
"""
schema = type_schema(
'credential',
value_type=ValueFilter.schema['properties']['value_type'],
key={'type': 'string',
'title': 'report key to search',
'enum': [
'user',
'arn',
'user_creation_time',
'password_enabled',
'password_last_used',
'password_last_changed',
'password_next_rotation',
'mfa_active',
'access_keys',
'access_keys.active',
'access_keys.last_used_date',
'access_keys.last_used_region',
'access_keys.last_used_service',
'access_keys.last_rotated',
'certs',
'certs.active',
'certs.last_rotated',
]},
value={'oneOf': [
{'type': 'array'},
{'type': 'string'},
{'type': 'boolean'},
{'type': 'number'},
{'type': 'null'}]},
op={'enum': list(OPERATORS.keys())},
report_generate={
'title': 'Generate a report if none is present.',
'default': True,
'type': 'boolean'},
report_delay={
'title': 'Number of seconds to wait for report generation.',
'default': 10,
'type': 'number'},
report_max_age={
'title': 'Number of seconds to consider a report valid.',
'default': 60 * 60 * 24,
'type': 'number'})
list_sub_objects = (
('access_key_1_', 'access_keys'),
('access_key_2_', 'access_keys'),
('cert_1_', 'certs'),
('cert_2_', 'certs'))
permissions = ('iam:GenerateCredentialReport',
'iam:GetCredentialReport')
def get_value_or_schema_default(self, k):
if k in self.data:
return self.data[k]
return self.schema['properties'][k]['default']
def get_credential_report(self):
report = self.manager._cache.get('iam-credential-report')
if report:
return report
data = self.fetch_credential_report()
report = {}
if isinstance(data, six.binary_type):
reader = csv.reader(io.StringIO(data.decode('utf-8')))
else:
reader = csv.reader(io.StringIO(data))
headers = next(reader)
for line in reader:
info = dict(zip(headers, line))
report[info['user']] = self.process_user_record(info)
self.manager._cache.save('iam-credential-report', report)
return report
@classmethod
def process_user_record(cls, info):
"""Type convert the csv record, modifies in place."""
keys = list(info.keys())
# Value conversion
for k in keys:
v = info[k]
if v in ('N/A', 'no_information'):
info[k] = None
elif v == 'false':
info[k] = False
elif v == 'true':
info[k] = True
# Object conversion
for p, t in cls.list_sub_objects:
obj = dict([(k[len(p):], info.pop(k))
for k in keys if k.startswith(p)])
if obj.get('active', False):
info.setdefault(t, []).append(obj)
return info
def fetch_credential_report(self):
client = local_session(self.manager.session_factory).client('iam')
try:
report = client.get_credential_report()
except ClientError as e:
if e.response['Error']['Code'] != 'ReportNotPresent':
raise
report = None
if report:
threshold = datetime.datetime.now(tz=tzutc()) - timedelta(
seconds=self.get_value_or_schema_default(
'report_max_age'))
if not report['GeneratedTime'].tzinfo:
threshold = threshold.replace(tzinfo=None)
if report['GeneratedTime'] < threshold:
report = None
if report is None:
if not self.get_value_or_schema_default('report_generate'):
raise ValueError("Credential Report Not Present")
client.generate_credential_report()
time.sleep(self.get_value_or_schema_default('report_delay'))
report = client.get_credential_report()
return report['Content']
def process(self, resources, event=None):
if '.' in self.data['key']:
self.matcher_config = dict(self.data)
self.matcher_config['key'] = self.data['key'].split('.', 1)[1]
return []
def match(self, info):
if info is None:
return False
k = self.data.get('key')
if '.' not in k:
vf = ValueFilter(self.data)
vf.annotate = False
return vf(info)
prefix, sk = k.split('.', 1)
vf = ValueFilter(self.matcher_config)
vf.annotate = False
for v in info.get(prefix, ()):
if vf.match(v):
return True
@User.filter_registry.register('credential')
class UserCredentialReport(CredentialReport):
def process(self, resources, event=None):
super(UserCredentialReport, self).process(resources, event)
report = self.get_credential_report()
if report is None:
return []
results = []
for r in resources:
info = report.get(r['UserName'])
if self.match(info):
r['c7n:credential-report'] = info
results.append(r)
return results
@User.filter_registry.register('has-inline-policy')
class IamUserInlinePolicy(Filter):
"""
Filter IAM users that have an inline-policy attached
True: Filter users that have an inline-policy
False: Filter users that do not have an inline-policy
"""
schema = type_schema('has-inline-policy', value={'type': 'boolean'})
permissions = ('iam:ListUserPolicies',)
def _inline_policies(self, client, resource):
resource['c7n:InlinePolicies'] = client.list_user_policies(
UserName=resource['UserName'])['PolicyNames']
return resource
def process(self, resources, event=None):
c = local_session(self.manager.session_factory).client('iam')
value = self.data.get('value', True)
res = []
for r in resources:
r = self._inline_policies(c, r)
if len(r['c7n:InlinePolicies']) > 0 and value:
res.append(r)
if len(r['c7n:InlinePolicies']) == 0 and not value:
res.append(r)
return res
@User.filter_registry.register('policy')
class UserPolicy(ValueFilter):
"""Filter IAM users based on attached policy values
:example:
.. code-block:: yaml
policies:
- name: iam-users-with-admin-access
resource: iam-user
filters:
- type: policy
key: PolicyName
value: AdministratorAccess
"""
schema = type_schema('policy', rinherit=ValueFilter.schema)
permissions = ('iam:ListAttachedUserPolicies',)
def user_policies(self, user_set):
client = local_session(self.manager.session_factory).client('iam')
for u in user_set:
if 'c7n:Policies' not in u:
u['c7n:Policies'] = []
aps = client.list_attached_user_policies(
UserName=u['UserName'])['AttachedPolicies']
for ap in aps:
u['c7n:Policies'].append(
client.get_policy(PolicyArn=ap['PolicyArn'])['Policy'])
def process(self, resources, event=None):
user_set = chunks(resources, size=50)
with self.executor_factory(max_workers=2) as w:
self.log.debug(
"Querying %d users policies" % len(resources))
list(w.map(self.user_policies, user_set))
matched = []
for r in resources:
for p in r['c7n:Policies']:
if self.match(p) and r not in matched:
matched.append(r)
return matched
@User.filter_registry.register('group')
class GroupMembership(ValueFilter):
"""Filter IAM users based on attached group values
:example:
.. code-block:: yaml
policies:
- name: iam-users-in-admin-group
resource: iam-user
filters:
- type: group
key: GroupName
value: Admins
"""
schema = type_schema('group', rinherit=ValueFilter.schema)
permissions = ('iam:ListGroupsForUser',)
def get_user_groups(self, client, user_set):
for u in user_set:
u['c7n:Groups'] = client.list_groups_for_user(
UserName=u['UserName'])['Groups']
def process(self, resources, event=None):
client = local_session(self.manager.session_factory).client('iam')
with self.executor_factory(max_workers=2) as w:
futures = []
for user_set in chunks(
[r for r in resources if 'c7n:Groups' not in r], size=50):
futures.append(
w.submit(self.get_user_groups, client, user_set))
for f in as_completed(futures):
pass
matched = []
for r in resources:
for p in r.get('c7n:Groups', []):
if self.match(p) and r not in matched:
matched.append(r)
return matched
@User.filter_registry.register('access-key')
class UserAccessKey(ValueFilter):
"""Filter IAM users based on access-key values
:example:
.. code-block:: yaml
policies:
- name: iam-users-with-active-keys
resource: iam-user
filters:
- type: access-key
key: Status
value: Active
"""
schema = type_schema('access-key', rinherit=ValueFilter.schema)
permissions = ('iam:ListAccessKeys',)
def user_keys(self, user_set):
client = local_session(self.manager.session_factory).client('iam')
for u in user_set:
u['c7n:AccessKeys'] = client.list_access_keys(
UserName=u['UserName'])['AccessKeyMetadata']
def process(self, resources, event=None):
user_set = chunks(resources, size=50)
with self.executor_factory(max_workers=2) as w:
self.log.debug(
"Querying %d users' api keys" % len(resources))
list(w.map(self.user_keys, user_set))
matched = []
for r in resources:
for k in r['c7n:AccessKeys']:
if self.match(k):
matched.append(r)
break
return matched
# Mfa-device filter for iam-users
@User.filter_registry.register('mfa-device')
class UserMfaDevice(ValueFilter):
"""Filter iam-users based on mfa-device status
:example:
.. code-block:: yaml
policies:
- name: mfa-enabled-users
resource: iam-user
filters:
- type: mfa-device
key: UserName
value: not-null
"""
schema = type_schema('mfa-device', rinherit=ValueFilter.schema)
permissions = ('iam:ListMfaDevices',)
def __init__(self, *args, **kw):
super(UserMfaDevice, self).__init__(*args, **kw)
self.data['key'] = 'MFADevices'
def process(self, resources, event=None):
def _user_mfa_devices(resource):
client = local_session(self.manager.session_factory).client('iam')
resource['MFADevices'] = client.list_mfa_devices(
UserName=resource['UserName'])['MFADevices']
with self.executor_factory(max_workers=2) as w:
query_resources = [
r for r in resources if 'MFADevices' not in r]
self.log.debug(
"Querying %d users' mfa devices" % len(query_resources))
list(w.map(_user_mfa_devices, query_resources))
matched = []
for r in resources:
if self.match(r):
matched.append(r)
return matched
@User.action_registry.register('delete')
class UserDelete(BaseAction):
"""Delete a user or properties of a user.
For example if you want to have a whitelist of valid (machine-)users
and want to ensure that no users have been clicked without documentation.
You can use both the 'credential' or the 'username'
filter. 'credential' will have an SLA of 4h,
(http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html),
but the added benefit of performing less API calls, whereas
'username' will make more API calls, but have a SLA of your cache.
:example:
.. code-block:: yaml
# using a 'credential' filter'
- name: iam-only-whitelisted-users
resource: iam-user
filters:
- type: credential
key: user
op: not-in
value:
- valid-user-1
- valid-user-2
actions:
- delete
# using a 'username' filter with 'UserName'
- name: iam-only-whitelisted-users
resource: iam-user
filters:
- type: username
key: UserName
op: not-in
value:
- valid-user-1
- valid-user-2
actions:
- delete
# using a 'username' filter with 'Arn'
- name: iam-only-whitelisted-users
resource: iam-user
filters:
- type: username
key: Arn
op: not-in
value:
- arn:aws:iam:123456789012:user/valid-user-1
- arn:aws:iam:123456789012:user/valid-user-2
actions:
- delete
Additionally, you can specify the options to delete properties of an iam-user,
including console-access, access-keys, attached-user-policies,
inline-user-policies, mfa-devices, groups,
ssh-keys, signing-certificates, and service-specific-credentials.
Note: using options will _not_ delete the user itself, only the items specified
by ``options`` that are attached to the respective iam-user. To delete a user
completely, use the ``delete`` action without specifying ``options``.
:example:
.. code-block:: yaml
- name: delete-console-access-unless-valid
comment: |
finds iam-users with console access and deletes console access unless
the username is included in whitelist
resource: iam-user
filters:
- type: username
key: UserName
op: not-in
value:
- valid-user-1
- valid-user-2
- type: credential
key: Status
value: Active
actions:
- type: delete
options:
- console-access
- name: delete-misc-access-for-iam-user
comment: |
deletes multiple options from test_user
resource: iam-user
filters:
- UserName: test_user
actions:
- type: delete
options:
- mfa-devices
- access-keys
- ssh-keys
"""
ORDERED_OPTIONS = OrderedDict([
('console-access', 'delete_console_access'),
('access-keys', 'delete_access_keys'),
('attached-user-policies', 'delete_attached_user_policies'),
('inline-user-policies', 'delete_inline_user_policies'),
('mfa-devices', 'delete_hw_mfa_devices'),
('groups', 'delete_groups'),
('ssh-keys', 'delete_ssh_keys'),
('signing-certificates', 'delete_signing_certificates'),
('service-specific-credentials', 'delete_service_specific_credentials'),
])
COMPOUND_OPTIONS = {
'user-policies': ['attached-user-policies', 'inline-user-policies'],
}
schema = type_schema(
'delete',
options={
'type': 'array',
'items': {
'type': 'string',
'enum': list(ORDERED_OPTIONS.keys()) + list(COMPOUND_OPTIONS.keys()),
}
})
permissions = (
'iam:ListAttachedUserPolicies',
'iam:ListAccessKeys',
'iam:ListGroupsForUser',
'iam:ListMFADevices',
'iam:ListServiceSpecificCredentials',
'iam:ListSigningCertificates',
'iam:ListSSHPublicKeys',
'iam:DeactivateMFADevice',
'iam:DeleteAccessKey',
'iam:DeleteLoginProfile',
'iam:DeleteSigningCertificate',
'iam:DeleteSSHPublicKey',
'iam:DeleteUser',
'iam:DeleteUserPolicy',
'iam:DetachUserPolicy',
'iam:RemoveUserFromGroup')
@staticmethod
def delete_console_access(client, r):
try:
client.delete_login_profile(
UserName=r['UserName'])
except ClientError as e:
if e.response['Error']['Code'] not in ('NoSuchEntity',):
raise
@staticmethod
def delete_access_keys(client, r):
response = client.list_access_keys(UserName=r['UserName'])
for access_key in response['AccessKeyMetadata']:
client.delete_access_key(UserName=r['UserName'],
AccessKeyId=access_key['AccessKeyId'])
@staticmethod
def delete_attached_user_policies(client, r):
response = client.list_attached_user_policies(UserName=r['UserName'])
for user_policy in response['AttachedPolicies']:
client.detach_user_policy(
UserName=r['UserName'], PolicyArn=user_policy['PolicyArn'])
@staticmethod
def delete_inline_user_policies(client, r):
response = client.list_user_policies(UserName=r['UserName'])
for user_policy_name in response['PolicyNames']:
client.delete_user_policy(
UserName=r['UserName'], PolicyName=user_policy_name)
@staticmethod
def delete_hw_mfa_devices(client, r):
response = client.list_mfa_devices(UserName=r['UserName'])
for mfa_device in response['MFADevices']:
client.deactivate_mfa_device(
UserName=r['UserName'], SerialNumber=mfa_device['SerialNumber'])
@staticmethod
def delete_groups(client, r):
response = client.list_groups_for_user(UserName=r['UserName'])
for user_group in response['Groups']:
client.remove_user_from_group(
UserName=r['UserName'], GroupName=user_group['GroupName'])
@staticmethod
def delete_ssh_keys(client, r):
response = client.list_ssh_public_keys(UserName=r['UserName'])
for key in response.get('SSHPublicKeys', ()):
client.delete_ssh_public_key(
UserName=r['UserName'], SSHPublicKeyId=key['SSHPublicKeyId'])
@staticmethod
def delete_signing_certificates(client, r):
response = client.list_signing_certificates(UserName=r['UserName'])
for cert in response.get('Certificates', ()):
client.delete_signing_certificate(
UserName=r['UserName'], CertificateId=cert['CertificateId'])
@staticmethod
def delete_service_specific_credentials(client, r):
# Service specific user credentials (codecommit)
response = client.list_service_specific_credentials(UserName=r['UserName'])
for screds in response.get('ServiceSpecificCredentials', ()):
client.delete_service_specific_credential(
UserName=r['UserName'],
ServiceSpecificCredentialId=screds['ServiceSpecificCredentialId'])
@staticmethod
def delete_user(client, r):
client.delete_user(UserName=r['UserName'])
def process(self, resources):
client = local_session(self.manager.session_factory).client('iam')
self.log.debug('Deleting user %s options: %s' %
(len(resources), self.data.get('options', 'all')))
for r in resources:
self.process_user(client, r)
def process_user(self, client, r):
user_options = self.data.get('options', list(self.ORDERED_OPTIONS.keys()))
# resolve compound options
for cmd in self.COMPOUND_OPTIONS:
if cmd in user_options:
user_options += self.COMPOUND_OPTIONS[cmd]
# process options in ordered fashion
for cmd in self.ORDERED_OPTIONS:
if cmd in user_options:
op = getattr(self, self.ORDERED_OPTIONS[cmd])
op(client, r)
if not self.data.get('options'):
self.delete_user(client, r)
@User.action_registry.register('remove-keys')
class UserRemoveAccessKey(BaseAction):
"""Delete or disable user's access keys.
For example if we wanted to disable keys after 90 days of non-use and
delete them after 180 days of nonuse:
:example:
.. code-block:: yaml
- name: iam-mfa-active-keys-no-login
resource: iam-user
actions:
- type: remove-keys
disable: true
age: 90
- type: remove-keys
age: 180
"""
schema = type_schema(
'remove-keys', age={'type': 'number'}, disable={'type': 'boolean'})
permissions = ('iam:ListAccessKeys', 'iam:UpdateAccessKey',
'iam:DeleteAccessKey')
def process(self, resources):
client = local_session(self.manager.session_factory).client('iam')
age = self.data.get('age')
disable = self.data.get('disable')
if age:
threshold_date = datetime.datetime.now(tz=tzutc()) - timedelta(age)
for r in resources:
if 'c7n:AccessKeys' not in r:
r['c7n:AccessKeys'] = client.list_access_keys(
UserName=r['UserName'])['AccessKeyMetadata']
keys = r['c7n:AccessKeys']
for k in keys:
if age:
if not k['CreateDate'] < threshold_date:
continue
if disable:
client.update_access_key(
UserName=r['UserName'],
AccessKeyId=k['AccessKeyId'],
Status='Inactive')
else:
client.delete_access_key(
UserName=r['UserName'],
AccessKeyId=k['AccessKeyId'])
#################
# IAM Groups #
#################
@Group.filter_registry.register('has-users')
class IamGroupUsers(Filter):
"""Filter IAM groups that have users attached based on True/False value:
True: Filter all IAM groups with users assigned to it
False: Filter all IAM groups without any users assigned to it
:example:
.. code-block:: yaml
- name: empty-iam-group
resource: iam-group
filters:
- type: has-users
value: False
"""
schema = type_schema('has-users', value={'type': 'boolean'})
permissions = ('iam:GetGroup',)
def _user_count(self, client, resource):
return len(client.get_group(GroupName=resource['GroupName'])['Users'])
def process(self, resources, events=None):
c = local_session(self.manager.session_factory).client('iam')
if self.data.get('value', True):
return [r for r in resources if self._user_count(c, r) > 0]
return [r for r in resources if self._user_count(c, r) == 0]
@Group.filter_registry.register('has-inline-policy')
class IamGroupInlinePolicy(Filter):
"""Filter IAM groups that have an inline-policy based on boolean value:
True: Filter all groups that have an inline-policy attached
False: Filter all groups that do not have an inline-policy attached
:example:
.. code-block:: yaml
- name: iam-groups-with-inline-policy
resource: iam-group
filters:
- type: has-inline-policy
value: True
"""
schema = type_schema('has-inline-policy', value={'type': 'boolean'})
permissions = ('iam:ListGroupPolicies',)
def _inline_policies(self, client, resource):
resource['c7n:InlinePolicies'] = client.list_group_policies(
GroupName=resource['GroupName'])['PolicyNames']
return resource
def process(self, resources, events=None):
c = local_session(self.manager.session_factory).client('iam')
value = self.data.get('value', True)
res = []
for r in resources:
r = self._inline_policies(c, r)
if len(r['c7n:InlinePolicies']) > 0 and value:
res.append(r)
if len(r['c7n:InlinePolicies']) == 0 and not value:
res.append(r)
return res
| {
"content_hash": "4ad557e404d18152a116c2b15932e580",
"timestamp": "",
"source": "github",
"line_count": 1441,
"max_line_length": 99,
"avg_line_length": 32.47814018043026,
"alnum_prop": 0.5747740432896733,
"repo_name": "taohungyang/cloud-custodian",
"id": "00f2574a7b992e69e84feb6d8756237452e0c435",
"size": "47391",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "c7n/resources/iam.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "517"
},
{
"name": "Go",
"bytes": "131325"
},
{
"name": "HTML",
"bytes": "31"
},
{
"name": "Makefile",
"bytes": "10146"
},
{
"name": "Python",
"bytes": "3444793"
},
{
"name": "Shell",
"bytes": "2294"
}
],
"symlink_target": ""
} |
from __future__ import absolute_import
from datetime import timedelta
from random import randint
from flask import current_app
from celery import Celery
from celery.schedules import crontab
from celery.signals import worker_process_init
from redash import __version__, create_app, settings
from redash.metrics import celery as celery_metrics
celery = Celery('redash',
broker=settings.CELERY_BROKER,
include='redash.tasks')
celery_schedule = {
'refresh_queries': {
'task': 'redash.tasks.refresh_queries',
'schedule': timedelta(seconds=30)
},
'cleanup_tasks': {
'task': 'redash.tasks.cleanup_tasks',
'schedule': timedelta(minutes=5)
},
'refresh_schemas': {
'task': 'redash.tasks.refresh_schemas',
'schedule': timedelta(minutes=settings.SCHEMAS_REFRESH_SCHEDULE)
}
}
if settings.GOOGLE_GROUP_MEMBER_SYNC_ENABLED:
celery_schedule['sync_google_group_members'] = {
'task': 'redash.tasks.sync_google_group_members',
'schedule': timedelta(hours=1)
}
if settings.VERSION_CHECK:
celery_schedule['version_check'] = {
'task': 'redash.tasks.version_check',
# We need to schedule the version check to run at a random hour/minute, to spread the requests from all users
# evenly.
'schedule': crontab(minute=randint(0, 59), hour=randint(0, 23))
}
if settings.QUERY_RESULTS_CLEANUP_ENABLED:
celery_schedule['cleanup_query_results'] = {
'task': 'redash.tasks.cleanup_query_results',
'schedule': timedelta(minutes=5)
}
celery.conf.update(CELERY_RESULT_BACKEND=settings.CELERY_BACKEND,
CELERYBEAT_SCHEDULE=celery_schedule,
CELERY_TIMEZONE='UTC',
CELERY_TASK_RESULT_EXPIRES=settings.CELERY_TASK_RESULT_EXPIRES,
CELERYD_LOG_FORMAT=settings.CELERYD_LOG_FORMAT,
CELERYD_TASK_LOG_FORMAT=settings.CELERYD_TASK_LOG_FORMAT)
if settings.SENTRY_DSN:
from raven import Client
from raven.contrib.celery import register_signal
client = Client(settings.SENTRY_DSN, release=__version__, install_logging_hook=False)
register_signal(client)
# Create a new Task base class, that pushes a new Flask app context to allow DB connections if needed.
TaskBase = celery.Task
class ContextTask(TaskBase):
abstract = True
def __call__(self, *args, **kwargs):
with current_app.app_context():
return TaskBase.__call__(self, *args, **kwargs)
celery.Task = ContextTask
# Create Flask app after forking a new worker, to make sure no resources are shared between processes.
@worker_process_init.connect
def init_celery_flask_app(**kwargs):
app = create_app()
app.app_context().push()
| {
"content_hash": "a2f6f35edcda18a6d88fd9a6dd9242f3",
"timestamp": "",
"source": "github",
"line_count": 86,
"max_line_length": 117,
"avg_line_length": 32.41860465116279,
"alnum_prop": 0.6714490674318508,
"repo_name": "crowdworks/redash",
"id": "fed631698ee35e4f9fe77d57d60b952e8293ff67",
"size": "2788",
"binary": false,
"copies": "1",
"ref": "refs/heads/crowdworks",
"path": "redash/worker.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "363388"
},
{
"name": "HTML",
"bytes": "133346"
},
{
"name": "JavaScript",
"bytes": "280524"
},
{
"name": "Makefile",
"bytes": "807"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Python",
"bytes": "750251"
},
{
"name": "Shell",
"bytes": "26661"
}
],
"symlink_target": ""
} |
from .models import *
def fix_airport_country(country_str, iso_code2):
try:
aps = Airport.objects.filter(country_str__contains=country_str)
except:
print("No listings were found.")
try:
c = Country.objects.get(iso_code2=iso_code2)
except:
print("That country was not found.")
print("There are {} listings found for {}.".format(aps.count(), c.name))
for a in aps:
a.country = c
a.save()
| {
"content_hash": "c1d4999e94a0884d3500278614f9c373",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 76,
"avg_line_length": 25.88888888888889,
"alnum_prop": 0.5987124463519313,
"repo_name": "MarconiMediaGroup/TravelHub",
"id": "feea8816a90d18e6c34866f44b3c18f4f39d23ca",
"size": "466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/ofd/helpers.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "123160"
},
{
"name": "JavaScript",
"bytes": "146168"
},
{
"name": "Python",
"bytes": "35589"
}
],
"symlink_target": ""
} |
import os
from project import app
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port) | {
"content_hash": "f275c9236e11afedc043c233abda9a38",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 40,
"avg_line_length": 18.666666666666668,
"alnum_prop": 0.6875,
"repo_name": "yangchandle/FlaskTaskr",
"id": "a7191b9b69e1c151c84ffebe843ac8adf4092b82",
"size": "132",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "run.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "225"
},
{
"name": "HTML",
"bytes": "9364"
},
{
"name": "Python",
"bytes": "41566"
}
],
"symlink_target": ""
} |
import rospy
import math
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist, Quaternion
from tf import transformations as tft
def quaternion_to_heading(quaternion):
"""
Converts a quaternion to equivalent Euler yaw/heading
input: nav_msgs.msg.Quaternion
output: euler heading in radians
"""
try:
quat = [quaternion.x, quaternion.y, quaternion.z, quaternion.w]
except AttributeError:
quat = quaternion
yaw = tft.euler_from_quaternion(quat)[2]
return yaw
def heading_to_quaternion(heading):
"""
Converts a Euler yaw/heading angle to equivalent quaternion
input: euler heading in radians
output: nav_msgs.msg.Quaternion
"""
quat = tft.quaternion_from_euler(0, 0, heading)
quaternion = Quaternion()
quaternion.x = quat[0]
quaternion.y = quat[1]
quaternion.z = quat[2]
quaternion.w = quat[3]
return quaternion
def dot_product(vec1, vec2):
"""
calcuates the dot product of two tuples/vectors a, b
input: 2 three-tuples a, vec2
output: double: dot product
"""
return vec1[0]*vec2[0]+vec1[1]*vec2[1]+vec1[2]*vec2[2]
def cross_product(vec1, vec2):
"""
calcuates the cross product of two tuples/vectors a, b
input: 2 three-tuples vec1, vec2
output: three-tuple (cross product of a, vec2)
i j k
a[0] a[1] a[2]
b[0] b[1] b[2]
"""
i = vec1[1]*vec2[2]-vec1[2]*vec2[1]
j = vec1[0]*vec2[2]-vec1[2]*vec2[0]
k = vec1[0]*vec2[1]-vec1[1]*vec2[0]
return (i, j, k,)
def scale(vector, magnitude):
"""
scales the given vector by the magnitude (scalar multiplication)
input: three-tuple vector, double magnitude
output: three-tuple scaled vector
"""
return (vector[0]*magnitude, vector[1]*magnitude, vector[2]*magnitude)
def unit(vector):
"""
returns the unit vector in the same direction as the given vector
"""
length = math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]+
vector[2]*vector[2])
if under_minimum(vector):
raise ZeroDivisionError('vector length 0 cannot be scaled to a unit vector')
return scale(vector, 1.0/length)
def under_minimum(vector):
length = math.sqrt(vector[0]*vector[0]+vector[1]*vector[1]+
vector[2]*vector[2])
return length < .0001
def calc_errors(location, goal):
"""
calculate errors in "x", "y", "theta" between a location and a goal
input: two nav_msgs.msg.Odometry, a current best estimate of location
and the goal
output: a three-tuple representing error along the goal heading vector,
error normal to that vector, and heading error
example usage:
odom = Odometry(current location)
goal = Odometry(target location)
along_axis, off_axis, heading = calc_errors(odom, goal)
"""
along = along_axis_error(location, goal)
off = off_axis_error(location, goal)
heading = heading_error(location, goal)
return (along, off, heading,)
def along_axis_error(location, goal):
"""
calc error along the axis defined by the goal position and direction
input: two nav_msgs.msg.Odometry, current best location estimate + goal
output: double distance along the axis
axis is defined by a vector from the unit circle aligned with the goal
heading
relative position is the vector from the goal x, y to the location x, y
distance is defined by the dot product
example use:
see calc_errors above
"""
relative_position_x = (location.pose.pose.position.x -
goal.pose.pose.position.x)
relative_position_y = (location.pose.pose.position.y -
goal.pose.pose.position.y)
# relative position of the best estimate position and the goal
# vector points from the goal to the location
relative_position = (relative_position_x, relative_position_y, 0.0)
goal_heading = quaternion_to_heading(goal.pose.pose.orientation)
goal_vector_x = math.cos(goal_heading)
goal_vector_y = math.sin(goal_heading)
# vector in the direction of the goal heading, axis of desired motion
goal_vector = (goal_vector_x, goal_vector_y, 0.0)
return dot_product(relative_position, goal_vector)
def off_axis_error(location, goal):
"""
calc error normal to axis defined by the goal position and direction
input: two nav_msgs.msg.Odometry, current best location estimate and
goal
output: double distance along the axis
axis is defined by a vector from the unit circle aligned with the goal
heading
relative position is the vector from the goal x, y to the location x, y
distance is defined by subtracting the parallel vector from the total
relative position vector
example use:
see calc_errors above
"""
# TODO(buckbaskin): assign a sign convention to off axis value
relative_position_x = (location.pose.pose.position.x -
goal.pose.pose.position.x)
relative_position_y = (location.pose.pose.position.y -
goal.pose.pose.position.y)
relative_position_z = (location.pose.pose.position.z -
goal.pose.pose.position.z)
# relative position of the best estimate position and the goal
# vector points from the goal to the location
relative_position = (relative_position_x, relative_position_y,
relative_position_z)
if under_minimum(relative_position):
return 0.0
goal_heading = quaternion_to_heading(goal.pose.pose.orientation)
goal_vector_x = math.cos(goal_heading)
goal_vector_y = math.sin(goal_heading)
# vector in the direction of the goal heading, axis of desired motion
goal_vector = (goal_vector_x, goal_vector_y, 0.0)
relative_along_goal = scale(unit(goal_vector),
dot_product(relative_position, goal_vector))
relative_normal_x = relative_position[0]-relative_along_goal[0]
relative_normal_y = relative_position[1]-relative_along_goal[1]
relative_normal_z = relative_position[2]-relative_along_goal[2]
sign = 1.0
crs_product = cross_product(goal_vector, relative_position)
if crs_product[2] < 0:
sign = -1.0
return sign*math.sqrt(relative_normal_x*relative_normal_x+
relative_normal_y*relative_normal_y+
relative_normal_z*relative_normal_z)
def heading_error(location, goal):
"""
return difference in heading between location and goal
"""
loc_head = quaternion_to_heading(location.pose.pose.orientation)
goal_head = quaternion_to_heading(goal.pose.pose.orientation)
return loc_head - goal_head
def dist(odom1, odom2):
"""
returns linear distance between two odometry messages
"""
# pylint: disable=invalid-name
# x and y accurately represent the axis that I'm referring to
x = odom1.pose.pose.position.x - odom2.pose.pose.position.x
y = odom1.pose.pose.position.y - odom2.pose.pose.position.y
return math.sqrt(x*x+y*y)
def easy_Odom(x, y, heading=0.0, v=0.0, w=0.0, frame='odom'):
odom = Odometry()
odom.pose.pose.position.x = x
odom.pose.pose.position.y = y
odom.pose.pose.orientation = heading_to_quaternion(heading)
odom.twist.twist.linear.x = v
odom.twist.twist.angular.z = w
odom.header.frame_id = frame
return odom
def minimize_angle(delta):
while (delta > 2.0*math.pi):
delta = delta - 2.0*math.pi
while (delta < -2.0*math.pi):
delta = delta + 2.0*math.pi
if delta > math.pi:
delta = -2.0*math.pi + delta
if delta < -math.pi:
delta = 2.0*math.pi + delta
return delta
def is_close(a, b, sigma=4):
if not (abs(a-b) < math.pow(1, -sigma)):
print(a, 'not close to', b)
return abs(a-b) < math.pow(1, -sigma)
def drange(start, stop, step):
counter = start
while counter < stop:
yield counter
counter += step
| {
"content_hash": "66d079c55acfd4e80b12e549b9325d82",
"timestamp": "",
"source": "github",
"line_count": 248,
"max_line_length": 84,
"avg_line_length": 31.600806451612904,
"alnum_prop": 0.6698991961209646,
"repo_name": "buckbaskin/drive_stack",
"id": "84258e38a185583192da25355ba5468718d5efb9",
"size": "7837",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/utils.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Matlab",
"bytes": "16498"
},
{
"name": "Python",
"bytes": "121562"
},
{
"name": "Shell",
"bytes": "420"
}
],
"symlink_target": ""
} |
'''
Manage RDP Service on Windows servers
'''
# Import python libs
import re
# Import salt libs
import salt.utils
def __virtual__():
'''
Only works on Windows systems
'''
if salt.utils.is_windows():
return 'rdp'
return False
def _parse_return_code_powershell(string):
'''
return from the input string the return code of the powershell command
'''
regex = re.search(r'ReturnValue\s*: (\d*)', string)
if not regex:
return False
else:
return int(regex.group(1))
def _psrdp(cmd):
'''
Create a Win32_TerminalServiceSetting WMI Object as $RDP and execute the
command cmd returns the STDOUT of the command
'''
rdp = ('$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting '
'-Namespace root\\CIMV2\\TerminalServices -Computer . '
'-Authentication 6 -ErrorAction Stop')
return __salt__['cmd.run']('{0} ; {1}'.format(rdp, cmd),
shell='powershell')
def enable():
'''
Enable RDP the service on the server
CLI Example:
.. code-block:: bash
salt '*' rdp.enable
'''
return _parse_return_code_powershell(
_psrdp('$RDP.SetAllowTsConnections(1,1)')) == 0
def disable():
'''
Disable RDP the service on the server
CLI Example:
.. code-block:: bash
salt '*' rdp.disable
'''
return _parse_return_code_powershell(
_psrdp('$RDP.SetAllowTsConnections(0,1)')) == 0
def status():
'''
Show if rdp is enabled on the server
CLI Example:
.. code-block:: bash
salt '*' rdp.status
'''
out = int(_psrdp('echo $RDP.AllowTSConnections').strip())
return out != 0
| {
"content_hash": "10fc1d619f935b4cef93f91cfe866c5b",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 76,
"avg_line_length": 19.74712643678161,
"alnum_prop": 0.5890570430733411,
"repo_name": "victorywang80/Maintenance",
"id": "428c360db32eb8885ae1d1096fb8c240654bba08",
"size": "1742",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "saltstack/src/salt/modules/rdp.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "160954"
},
{
"name": "JavaScript",
"bytes": "1"
},
{
"name": "Python",
"bytes": "4522522"
},
{
"name": "Scheme",
"bytes": "7488"
},
{
"name": "Shell",
"bytes": "14653"
}
],
"symlink_target": ""
} |
import matplotlib as mp
mp.use('agg')
from model.bootstrap_func import flattenList, checkFileExists, readFreqsFile, readLDFile, readFstFile, estimateFstByBootstrap, estimateFstByBootstrap_bysnp, estimateFreqSpectrum, estimatePi, estimater2decay, estimatedprimedecay
from model.params_func import get_ranges, generate_params
from model.error_func import calc_error, read_error_dimensionsfile
from model.search_func import read_dimensionsfile, sample_point, get_real_value, get_scaled_value
from model.plot_func import plot_comparison
from scipy import optimize
import numpy as np
import subprocess
import argparse
import random
import sys
#############################
## DEFINE ARGUMENT PARSER ###
#############################
def full_parser_cms_modeller():
parser=argparse.ArgumentParser(description="This script contains command-line utilities for exploratory fitting of demographic models to population genetic data.")
subparsers = parser.add_subparsers(help="sub-commands")
######################
## CALCULATE TARGET ##
######################
target_stats_parser = subparsers.add_parser('target_stats', help='Perform per-site(/per-site-pair) calculations of population summary statistics for model target values.')
target_stats_parser.add_argument('inputTpeds', action='store', type=list, help='comma-delimited list of unzipped input tped files (only one file per pop being modelled; must run chroms separately or concatenate)')
target_stats_parser.add_argument('recomFile', action='store', type=str, help='file defining recombination map for input')
target_stats_parser.add_argument('regions', action='store', type=str, help='tab-separated file with putative neutral regions') #OPTIONAL?
target_stats_parser.add_argument('--freqs', action='store_true', help='calculate summary statistics from within-population allele frequencies')
target_stats_parser.add_argument('--ld', action='store_true', help='calculate summary statistics from within-population linkage disequilibrium')
target_stats_parser.add_argument('--fst', action='store_true', help='calculate summary statistics from population comparison using allele frequencies')
target_stats_parser.add_argument('out', action='store', type=str, help='outfile prefix')
target_stats_parser.add_argument('--modelpath', action='store', type=str, default='cms/model/', help="path to model directory containing executables")
bootstrap_parser = subparsers.add_parser('bootstrap', help='Perform bootstrap estimates of population summary statistics from per-site(/per-site-pair) calculations in order to finalize model target values.')
bootstrap_parser.add_argument('nBootstrapReps', action='store', type=int, help='number of bootstraps to perform in order to estimate standard error of the dataset (should converge for reasonably small n)')
bootstrap_parser.add_argument('--in_freqs', action='store', help='comma-delimited list of infiles with per-site calculations for population. One file per population -- for bootstrap estimates of genome-wide values, should first concatenate per-chrom files')
bootstrap_parser.add_argument('--nFreqHistBins', action='store',type=int, default=6, help="number of bins for site frequency spectrum and p(der|freq)")
bootstrap_parser.add_argument('--in_ld', action='store', help='comma-delimited list of infiles with per-site-pair calculations for population. One file per population -- for bootstrap estimates of genome-wide values, should first concatenate per-chrom files')
bootstrap_parser.add_argument('--mafcutoffdprime', action='store', type=float, default=.2, help="for D' calculations, only use sites with MAF > mafcutoffdprime")
bootstrap_parser.add_argument('--nphysdisthist', action='store', type=int, default=14, help="nbins for r2 LD calculations")
bootstrap_parser.add_argument('--in_fst', action='store', help='comma-delimited list of infiles with per-site calculations for population pair. One file per population-pair -- for bootstrap estimates of genome-wide values, should first concatenate per-chrom files')
bootstrap_parser.add_argument('--ngendisthist', action='store', type=int, default=17, help="nbins for D' LD calculations")
bootstrap_parser.add_argument('out', action='store', type=str, help='outfile prefix')
##########################
### COSI - SHARED ARGS ##
##########################
point_parser = subparsers.add_parser('point', help='Run simulates of a point in parameter-space.')
grid_parser = subparsers.add_parser('grid', help='Perform grid search: for specified parameters and intervals, define points in parameter-space to sample and compare.')
optimize_parser = subparsers.add_parser('optimize', help='Perform optimization algorithm (scipy.optimize) to fit model parameters robustly.')
for cosi_parser in [point_parser, grid_parser, optimize_parser]:
cosi_parser.add_argument('inputParamFile', type=str, action='store', help='file with model specifications for input')
cosi_parser.add_argument('nCoalescentReps', type=int, help='number of coalescent replicates to run per point in parameter-space')
cosi_parser.add_argument('outputDir', type=str, action='store', help='location in which to write cosi output')
cosi_parser.add_argument('--cosiBuild', action='store', default="coalescent", help='which version of cosi to run?')
cosi_parser.add_argument('--dropSings', action='store', type=float, help='randomly thin global singletons from output dataset (i.e., to model ascertainment bias)')
cosi_parser.add_argument('--genmapRandomRegions', action='store_true', help='cosi option to sub-sample genetic map randomly from input')
cosi_parser.add_argument('--stopAfterMinutes', action='store', help='cosi option to terminate simulations')
cosi_parser.add_argument('--calcError', type=str, action='store', help='file specifying dimensions of error function to use. if unspecified, defaults to all. first line = stats, second line = pops')
######################
## VISUALIZE MODEL ##
######################
point_parser.add_argument('--targetvalsFile', action='store', type=str, help='file containing target values for model')
point_parser.add_argument('--plotStats', action='store_true', default=False, help='visualize goodness-of-fit to model targets')
#########################
## FIT MODEL TO TARGET ##
#########################
grid_parser.add_argument('grid_inputdimensionsfile', type=str, action='store', help='file with specifications of grid search. each parameter to vary is indicated: KEY\tINDEX\t[VALUES]') #must be defined for each search
#grid_parser.add_argument('--parallel', type=str, action='store', default="uger", help='if specified, launch points of grid search as tasks on a scheduler')
optimize_parser.add_argument('optimize_inputdimensionsfile', type=str, action='store', help='file with specifications of optimization. each parameter to vary is indicated: KEY\tINDEX')
optimize_parser.add_argument('--stepSize', action='store', type=float, help='scaled step size (i.e. whole range = 1)')
optimize_parser.add_argument('--method', action='store', type=str, default='SLSQP', help='algorithm to pass to scipy.optimize')
for common_parser in [target_stats_parser, point_parser]:#[bootstrap_parser, grid_parser, optimize_parser]:
common_parser.add_argument('--printOnly', action='store_true', help='print rather than execute pipeline commands')
return parser
#############################
## WRAPPER FOR OPTIMIZE ###
#############################
def sample_point_wrapper(values):
'''function passed to scipy.optimize.'''
return sample_point(nreps, gradientname, keys, indices, values)
############################
## DEFINE EXEC FUNCTIONS ###
############################
def execute_target_stats(args):
'''calls bootstrap_*_popstats_regions to get per-snp/per-snp-pair values'''
#pathcmd = "export PATH=" + args.modelpath + ":$PATH"
#subprocess.check_call(pathcmd.split())
modelpath = args.modelpath
if modelpath[-1] != "/":
modelpath += "/"
inputtpedstring = ''.join(args.inputTpeds)
inputtpeds = inputtpedstring.split(',')
npops = len(inputtpeds)
print("calculating summary statistics for " + str(npops) + " populations...")
allCmds = []
for ipop in range(npops):
inputtped = inputtpeds[ipop]
if args.freqs:
freqCmd = [modelpath + 'bootstrap_freq_popstats_regions', inputtped, args.recomFile, args.regions, args.out + "_freqs_" + str(ipop)]
allCmds.append(freqCmd)
if args.ld:
ldCmd = [modelpath + 'bootstrap_ld_popstats_regions', inputtped, args.recomFile, args.regions, args.out + "_ld_" + str(ipop)]
allCmds.append(ldCmd)
if args.fst:
for jpop in range(ipop+1, npops):
inputtped2 = inputtpeds[jpop]
fstCmd = [modelpath + 'bootstrap_fst_popstats_regions', inputtped, inputtped2, args.recomFile, args.regions, args.out + "_fst_" + str(ipop) + "_" + str(jpop)]
allCmds.append(fstCmd)
for command in allCmds:
command = [str(x) for x in command]
if args.printOnly:
commandstring = ""
for item in command:
commandstring += item + " "
print(commandstring)
else:
subprocess.check_call( command )
return
def execute_bootstrap(args):
'''pulls all per-snp/per-snp-pair values to get genome-wide bootstrap estimates.'''
nbootstraprep = args.nBootstrapReps
print("running " + str(nbootstraprep) + " bootstrap estimates of summary statistics...")
targetstats_filename = args.out + "_bootstrap_n" + str(nbootstraprep) + ".txt"
writefile = open(targetstats_filename, 'w')
#################
### FREQ STATS ##
#################
if args.in_freqs is not None:
nhist = args.nFreqHistBins
inputestimatefilenames = ''.join(args.in_freqs)
inputfilenames = inputestimatefilenames.split(',')
npops = len(inputfilenames)
for ipop in range(npops):
allRegionDER, allRegionANC, allRegionPI, allseqlens = [], [], [], []
nsnps, totalregions, totallen = 0, 0, 0
inputfilename = inputfilenames[ipop]
print("reading allele frequency statistics from: " + inputfilename)
writefile.write(str(ipop) + '\n')
if checkFileExists(inputfilename):
allpi, allnderiv, allnanc, nregions, seqlens = readFreqsFile(inputfilename)
allRegionPI.extend(allpi)
allRegionDER.extend(allnderiv)
allRegionANC.extend(allnanc)
allseqlens.extend(seqlens)
totalregions += nregions
totallen += sum(seqlens)
for i in range(len(allpi)):
nsnps += len(allpi[i])
print("TOTAL: logged frequency values for " + str(nsnps) + " SNPS across " + str(totalregions) + ".")
####################################
#### PI: MEAN & BOOTSTRAP STDERR ###
####################################
pi_mean = estimatePi(allRegionPI, allseqlens)
writefile.write(str(pi_mean)+'\t')
estimates = []
for j in range(nbootstraprep):
rep_pis, rep_seqlens = [], []
for k in range(totalregions):
index = random.randint(0, totalregions-1)
rep_pis.append(allRegionPI[index])
rep_seqlens.append(allseqlens[index])
rep_pi_mean = estimatePi(rep_pis, rep_seqlens)
estimates.append(rep_pi_mean)
pi_se = np.std(estimates)
writefile.write(str(pi_se) + '\n')
#########################################
### SFS, ANC: MEAN ACROSS ALL REGIONS ###
#########################################
mafhist, anchist = estimateFreqSpectrum(allRegionDER, allRegionANC, nhist)
npoly = sum(mafhist)
sfs_mean = [float(x)/npoly for x in mafhist]
anc_mean = [anchist[i]/float(mafhist[i]) for i in range(len(mafhist))]
###################################################
### SFS, ANC: STDERR ACROSS BOOTSTRAP ESTIMATES ###
###################################################
estimates_sfs, estimates_anc = [[] for i in range(nhist)], [[] for i in range(nhist)]
for j in range(nbootstraprep):
rep_all_nderiv, rep_all_nanc = [], []
flatanc = flattenList(allRegionANC)
flatder = flattenList(allRegionDER)
for w in range(nsnps):
index = random.randint(0, nsnps-1)
rep_all_nderiv.append(flatder[index])
rep_all_nanc.append(flatanc[index])
repmafhist, repanchist = estimateFreqSpectrum(rep_all_nderiv, rep_all_nanc, nhist)
npoly = sum(repmafhist)
repsfs = [float(x)/npoly for x in repmafhist]
for ibin in range(nhist):
estimates_sfs[ibin].append(repsfs[ibin])
repanc = [repanchist[i]/float(repmafhist[i]) for i in range(nhist)]
for ibin in range(nhist):
estimates_anc[ibin].append(repanc[ibin])
sfs_se = [np.std(x) for x in estimates_sfs]
anc_se = [np.std(x) for x in estimates_anc]
writefile.write(str(sfs_mean) + '\n')
writefile.write(str(sfs_se) + '\n')
writefile.write(str(anc_mean) + '\n')
writefile.write(str(anc_se) + '\n')
#########
### LD ##
#########
if args.in_ld is not None:
nphysdisthist = args.nphysdisthist
ngendisthist = args.ngendisthist
inputestimatefilenames = ''.join(args.in_ld)
inputfilenames = inputestimatefilenames.split(',')
npops = len(inputfilenames)
#print('npops ' + str(npops)) #debug
for ipop in range(npops):
inputfilename = inputfilenames[ipop]
print("reading linkage disequilibrium statistics from: " + inputfilename)
writefile.write(str(ipop) + '\n')
N_r2regs, N_dprimeregs = 0, 0
N_r2snps, N_dprimesnps = 0, 0
allRegionDists, allRegionr2, allRegionGendists, allRegionDprime, nr2regions, ndprimeregions = readLDFile(inputfilename, dprimecutoff = args.mafcutoffdprime)
N_r2regs += nr2regions
N_r2snps += sum([len(x) for x in allRegionr2])
N_dprimeregs += ndprimeregions
N_dprimesnps += sum([len(x) for x in allRegionDprime])
print("\tlogged r2 values for " + str(N_r2snps) + " SNP pairs across " + str(N_r2regs) + " regions.")
print("\tlogged D' values for " + str(N_dprimesnps) + " SNP pairs across " + str(N_dprimeregs) + " regions.")
###################################
### r2: MEAN ACROSS ALL REGIONS ###
###################################
r2sums, physDistHist = estimater2decay(allRegionr2, allRegionDists, nphysdisthist)
r2dist = [r2sums[u]/physDistHist[u] for u in range(len(r2sums))]
writefile.write(str(r2dist) + "\n")
############################################
### r2: STDERR ACROSS BOOTSTRAP ESTIMATES ##
############################################
estimates_r2 = [[] for i in range(nphysdisthist)]
while len(estimates_r2[0]) < nbootstraprep:
rep_all_r2, rep_all_physdist = [], []
flatr2 = flattenList(allRegionr2)
flatregions = flattenList(allRegionDists)
nsnppairs = len(flatr2)
for w in range(nsnppairs):
index_r2 = random.randint(0, nsnppairs-1)
rep_all_r2.append(flatr2[index_r2])
rep_all_physdist.append(flatregions[index_r2])
#add pseudocount for empty bins
repr2sum, repphysdisthist = estimater2decay(rep_all_r2, rep_all_physdist, nphysdisthist)
for ibin in range(len(repphysdisthist)):
if repphysdisthist[ibin] == 0:
repphysdisthist[ibin] = 1
r2estimate =[repr2sum[u]/repphysdisthist[u] for u in range(len(repr2sum))]
for ibin in range(nphysdisthist):
estimates_r2[ibin].append(r2estimate[ibin])
r2_se = [np.std(x) for x in estimates_r2]
writefile.write(str(r2_se) + "\n")
####################################
### D': MEAN ACROSS ALL REGIONS ###
####################################
compLDhist, genDistHist = estimatedprimedecay(allRegionDprime, allRegionGendists, ngendisthist)
#add pseudocounts
for ibin in range(len(genDistHist)):
if genDistHist[ibin] == 0:
genDistHist[ibin]+=1
dprimedist = [float(compLDhist[x])/float(genDistHist[x]) for x in range(len(compLDhist))]
writefile.write(str(dprimedist) + "\n")
############################################
### D': STDERR ACROSS BOOTSTRAP ESTIMATES ##
############################################
estimates_dprime = [[] for i in range(ngendisthist)]
while len(estimates_dprime[0]) < nbootstraprep:
rep_all_dprime, rep_all_gendist = [], []
flatdprime = flattenList(allRegionDprime)
flatgendist = flattenList(allRegionGendists)
nsnppairs = len(flatdprime)
for w in range(nsnppairs):
index_dprime = random.randint(0, nsnppairs-1)
rep_all_dprime.append(flatdprime[index_dprime])
rep_all_gendist.append(flatgendist[index_dprime])
repcompLDhist, repgenDistHist = estimatedprimedecay(rep_all_dprime, rep_all_gendist, ngendisthist)
for ibin in range(len(repgenDistHist)):
if repgenDistHist[ibin] == 0:
repgenDistHist[ibin] = 1
dprimeestimate = [float(repcompLDhist[x])/float(repgenDistHist[x]) for x in range(ngendisthist)]
for ibin in range(ngendisthist):
estimates_dprime[ibin].append(dprimeestimate[ibin])
dprime_se = [np.std(x) for x in estimates_dprime]
writefile.write(str(dprime_se) + "\n")
##########
### FST ##
##########
if args.in_fst is not None:
inputestimatefilenames = ''.join(args.in_fst)
inputfilenames = inputestimatefilenames.split(',')
npopcomp = len(inputfilenames)
for icomp in range(npopcomp):
fstfilename = inputfilenames[icomp]
print("reading Fst values from: " + fstfilename)
if checkFileExists(fstfilename):
allfst, nregions = readFstFile(fstfilename)
else:
print('missing ' + fstfilename)
target_mean, target_se = estimateFstByBootstrap_bysnp(allfst, nrep = nbootstraprep)
writeline = str(icomp) + "\t" + str(target_mean) + "\t" + str(target_se) + '\n'
writefile.write(writeline)
print("TOTAL: logged Fst values for " + str(len(allfst)) + " SNPs.\n")
writefile.close()
print("wrote to file: " + targetstats_filename)
return
def execute_point(args):
'''runs simulates of a point in parameter-space, comparing to specified target'''
################
## FILE PREP ###
################
print("generating " + str(args.nCoalescentReps) + " simulations from model: " + args.inputParamFile)
statfilename = args.outputDir
if args.outputDir[-1] != "/":
statfilename += "/"
statfilename += "n" + str(args.nCoalescentReps) + "stats.txt"
###############
## RUN SIMS ###
###############
runStatsCommand = args.cosiBuild + " -p " + args.inputParamFile + " -n " + str(args.nCoalescentReps)
if args.dropSings is not None:
runStatsCommand += " --drop-singletons " + str(args.dropSings)
if args.genmapRandomRegions:
runStatsCommand += " --genmapRandomRegions"
if args.stopAfterMinutes is not None:
runStatsCommand += " --stop-after-minutes " + str(args.stopAfterMinutes)
runStatsCommand += " --custom-stats > " + statfilename
if args.printOnly:
print(runStatsCommand)
else:
subprocess.check_call( runStatsCommand.split() )
#################
## CALC ERROR ###
#################
if args.calcError is not None:
if args.calcError == '': #no error dimension file given
error = calc_error(statfilename)
else:
stats, pops = read_error_dimensionsfile(args.calcError)
error = calc_error(statfilename, stats, pops)
print(" error: " + str(error)) #record?
################
## VISUALIZE ###
################
if args.plotStats:
plot_comparison(statfilename, args.nCoalescentReps)
return
def execute_grid(args):
'''run points in parameter-space according to specified grid'''
print("loading dimensions of grid to search from: " + args.grid_inputdimensionsfile)
gridname, keys, indices, values = read_dimensionsfile(args.grid_inputdimensionsfile, 'grid')
assert len(keys) == len(indices)
combos = [' '.join(str(y) for y in x) for x in product(*values)]
errors = []
for combo in combos:
argstring = combo + "\n"
theseValues = eval(combo) #list of values
error = sample_point(args.nCoalescentReps, keys, indices, theseValues)
errors.append(error)
for icombo in range(len(combos)):
print(combo[icombo] + "\t" + errors[icombo] + "\n")
return
def execute_optimize(args):
'''run scipy.optimize module according to specified parameters'''
print("loading dimensions to search from: " + args.optimize_inputdimensionsfile)
runname, keys, indices = read_dimensionsfile(args.optimize_inputdimensionsfile, runType='optimize')
rangeDict = get_ranges()
paramDict = generate_params()
x0 = []
bounds = []
for i in range(len(keys)):
key = keys[i]
index = indices[i]
value = paramDict[key][index]
interval = rangeDict[key][index]
low, high = float(interval[0]), float(interval[1])
scaled = get_scaled_value(value, low, high)
x0.append(scaled)
bounds.append([0,1])
x0 = np.array(x0)
stepdict = {'eps':float(args.stepSize)}
result = optimize.minimize(sample_point_wrapper, x0, method=args.method, bounds=bounds, options=stepdict)
print(result)
print( "******************")
#translate back to changes to model
bestparams = []
assert len(keys) == len(result.x)
for i in range(len(keys)):
key = keys[i]
index = indices[i]
interval = rangeDict[key][index]
low, high = float(interval[0]), float(interval[1])
realVal = get_real_value(result.x[i], low, high)
bestparams.append(result.x[i])
print("best " + str(key) + "|" + str(index) + "|" + str(realVal))
return
##########
## MAIN ##
##########
if __name__ == '__main__':
runparser = full_parser_cms_modeller()
args = runparser.parse_args()
# if called with no arguments, print help
if len(sys.argv)==1:
runparser.parse_args(['--help'])
elif len(sys.argv)==2:
runparser.parse_args([sys.argv[1], '--help'])
subcommand = sys.argv[1]
function_name = 'execute_' + subcommand + "(args)"
eval(function_name) #points to functions defined above, which wrap other programs in the pipeline
| {
"content_hash": "b109a715043fc3cfe56f68bb5d6c2d23",
"timestamp": "",
"source": "github",
"line_count": 449,
"max_line_length": 268,
"avg_line_length": 47.7728285077951,
"alnum_prop": 0.6762237762237763,
"repo_name": "broadinstitute/cms",
"id": "704ccf37a7cf93128f9598b8978b02954ab8c7e8",
"size": "21590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cms/cms_modeller.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "550664"
},
{
"name": "C++",
"bytes": "330"
},
{
"name": "Makefile",
"bytes": "5127"
},
{
"name": "Python",
"bytes": "1359651"
},
{
"name": "Shell",
"bytes": "3921"
}
],
"symlink_target": ""
} |
"""Fixtures for harmony tests."""
from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
from aioharmony.const import ClientCallbackType
import pytest
from homeassistant.components.harmony.const import ACTIVITY_POWER_OFF
from .const import NILE_TV_ACTIVITY_ID, PLAY_MUSIC_ACTIVITY_ID, WATCH_TV_ACTIVITY_ID
ACTIVITIES_TO_IDS = {
ACTIVITY_POWER_OFF: -1,
"Watch TV": WATCH_TV_ACTIVITY_ID,
"Play Music": PLAY_MUSIC_ACTIVITY_ID,
"Nile-TV": NILE_TV_ACTIVITY_ID,
}
IDS_TO_ACTIVITIES = {
-1: ACTIVITY_POWER_OFF,
WATCH_TV_ACTIVITY_ID: "Watch TV",
PLAY_MUSIC_ACTIVITY_ID: "Play Music",
NILE_TV_ACTIVITY_ID: "Nile-TV",
}
TV_DEVICE_ID = 1234
TV_DEVICE_NAME = "My TV"
DEVICES_TO_IDS = {
TV_DEVICE_NAME: TV_DEVICE_ID,
}
IDS_TO_DEVICES = {
TV_DEVICE_ID: TV_DEVICE_NAME,
}
class FakeHarmonyClient:
"""FakeHarmonyClient to mock away network calls."""
def __init__(
self, ip_address: str = "", callbacks: ClientCallbackType = MagicMock()
):
"""Initialize FakeHarmonyClient class."""
self._activity_name = "Watch TV"
self.close = AsyncMock()
self.send_commands = AsyncMock()
self.change_channel = AsyncMock()
self.sync = AsyncMock()
self._callbacks = callbacks
self.fw_version = "123.456"
async def connect(self):
"""Connect and call the appropriate callbacks."""
self._callbacks.connect(None)
return AsyncMock(return_value=(True))
def get_activity_name(self, activity_id):
"""Return the activity name with the given activity_id."""
return IDS_TO_ACTIVITIES.get(activity_id)
def get_activity_id(self, activity_name):
"""Return the mapping of an activity name to the internal id."""
return ACTIVITIES_TO_IDS.get(activity_name)
def get_device_name(self, device_id):
"""Return the device name with the given device_id."""
return IDS_TO_DEVICES.get(device_id)
def get_device_id(self, device_name):
"""Return the device id with the given device_name."""
return DEVICES_TO_IDS.get(device_name)
async def start_activity(self, activity_id):
"""Update the current activity and call the appropriate callbacks."""
self._activity_name = IDS_TO_ACTIVITIES.get(int(activity_id))
activity_tuple = (activity_id, self._activity_name)
self._callbacks.new_activity_starting(activity_tuple)
self._callbacks.new_activity(activity_tuple)
return AsyncMock(return_value=(True, "unused message"))
async def power_off(self):
"""Power off all activities."""
await self.start_activity(-1)
@property
def current_activity(self):
"""Return the current activity tuple."""
return (
self.get_activity_id(self._activity_name),
self._activity_name,
)
@property
def config(self):
"""Return the config object."""
return self.hub_config.config
@property
def json_config(self):
"""Return the json config as a dict."""
return {}
@property
def hub_config(self):
"""Return the client_config type."""
config = MagicMock()
type(config).activities = PropertyMock(
return_value=[
{"name": "Watch TV", "id": WATCH_TV_ACTIVITY_ID},
{"name": "Play Music", "id": PLAY_MUSIC_ACTIVITY_ID},
{"name": "Nile-TV", "id": NILE_TV_ACTIVITY_ID},
]
)
type(config).devices = PropertyMock(
return_value=[{"name": TV_DEVICE_NAME, "id": TV_DEVICE_ID}]
)
type(config).info = PropertyMock(return_value={})
type(config).hub_state = PropertyMock(return_value={})
type(config).config = PropertyMock(
return_value={
"activity": [
{"id": 10000, "label": None},
{"id": -1, "label": "PowerOff"},
{"id": WATCH_TV_ACTIVITY_ID, "label": "Watch TV"},
{"id": PLAY_MUSIC_ACTIVITY_ID, "label": "Play Music"},
{"id": NILE_TV_ACTIVITY_ID, "label": "Nile-TV"},
]
}
)
return config
@pytest.fixture()
def mock_hc():
"""Create a mock HarmonyClient."""
with patch(
"homeassistant.components.harmony.data.HarmonyClient",
side_effect=FakeHarmonyClient,
) as fake:
yield fake
@pytest.fixture()
def mock_write_config():
"""Patches write_config_file to remove side effects."""
with patch(
"homeassistant.components.harmony.remote.HarmonyRemote.write_config_file",
) as mock:
yield mock
| {
"content_hash": "1188cbad13c364d660a3c3e518afd619",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 84,
"avg_line_length": 31.473333333333333,
"alnum_prop": 0.6015674645202288,
"repo_name": "partofthething/home-assistant",
"id": "29e897916b9bbe68d4f823103fab4cb44ff7d85c",
"size": "4721",
"binary": false,
"copies": "2",
"ref": "refs/heads/dev",
"path": "tests/components/harmony/conftest.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1720"
},
{
"name": "Python",
"bytes": "31051838"
},
{
"name": "Shell",
"bytes": "4832"
}
],
"symlink_target": ""
} |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import rapidtide.fit as tide_fit
import rapidtide.miscmath as tide_math
from rapidtide.tests.utils import mse
def eval_phaseanalysis(phasestep=0.01, amplitude=1.0, numpoints=100, display=False):
# read in some data
phases = np.linspace(0.0, numpoints * phasestep, num=numpoints, endpoint=False)
testwaveform = amplitude * np.cos(phases)
if display:
plt.figure()
plt.plot(phases)
plt.show()
plt.figure()
plt.plot(testwaveform)
plt.show()
# now calculate the phase waveform
instantaneous_phase, amplitude_envelope, analytic_signal = tide_fit.phaseanalysis(testwaveform)
filtered_phase = tide_math.trendfilt(instantaneous_phase, order=3, ndevs=2.0)
if display:
plt.figure()
plt.plot(instantaneous_phase)
plt.plot(filtered_phase)
plt.plot(phases)
plt.show()
return mse(phases, instantaneous_phase), mse(phases, filtered_phase)
def test_phaseanalysis(debug=False, display=False):
msethresh = 1e-3
instantaneous_mse, filtered_mse = eval_phaseanalysis(
phasestep=0.1, amplitude=3.0, numpoints=1000, display=display
)
print(instantaneous_mse, filtered_mse)
assert instantaneous_mse < msethresh
assert filtered_mse < msethresh
def main():
test_phaseanalysis(debug=True, display=True)
if __name__ == "__main__":
mpl.use("TkAgg")
main()
| {
"content_hash": "f018db6a14406827f1889bce8b14aab9",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 99,
"avg_line_length": 27.9811320754717,
"alnum_prop": 0.6844234659474039,
"repo_name": "bbfrederick/rapidtide",
"id": "b06a849fd9099f762b5335aec63314fae2b860c7",
"size": "2142",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "rapidtide/tests/test_phaseanalysis.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1653"
},
{
"name": "Python",
"bytes": "1997784"
},
{
"name": "Shell",
"bytes": "23046"
}
],
"symlink_target": ""
} |
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
readme = open('README.rst').read()
history = open('HISTORY.rst').read().replace('.. :changelog:', '')
setup(
name='stefuna',
version='1.0.1',
description='AWS Step Function Activity server framework',
long_description=readme + '\n\n' + history,
author='Ivo Rothschild',
author_email='ivo@clarify.io',
url='https://github.com/irothschild/stefuna',
python_requires='>=3.4.0',
packages=[
'stefuna',
],
package_dir={'stefuna':
'stefuna'},
include_package_data=True,
install_requires=[
'boto3>=1.4.6, <2.0.0'
],
entry_points={
'console_scripts': [
'stefuna = stefuna.stefuna:main'
]
},
license="MIT",
zip_safe=False,
keywords='AWS Step Functions Activity task server worker',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
"Programming Language :: Python :: 3",
],
tests_require=[
],
test_suite='stefuna.test',
)
| {
"content_hash": "e5dfe4a165e73e00831950336c3bc8a2",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 66,
"avg_line_length": 25.0188679245283,
"alnum_prop": 0.5904977375565611,
"repo_name": "irothschild/stefuna",
"id": "48f02f459e391641a1dd7e32d55b703afe4942f9",
"size": "1373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "30564"
}
],
"symlink_target": ""
} |
import sys
sys.path.insert(1, "../../../")
import h2o
def binop_eq(ip,port):
iris = h2o.import_file(path=h2o.locate("smalldata/iris/iris_wheader.csv"))
rows, cols = iris.dim
iris.show()
#frame/scaler
res = iris == 4.7
res_rows, res_cols = res.dim
assert res_rows == rows and res_cols == cols, "dimension mismatch"
new_rows = iris[res[0]].nrow
assert new_rows == 2, "wrong number of rows returned"
res = 3.5 == iris
res_rows, res_cols = res.dim
assert res_rows == rows and res_cols == cols, "dimension mismatch"
new_rows = iris[res[1]].nrow
assert new_rows == 6, "wrong number of rows returned"
#frame/vec
#try:
# res = iris == iris[0]
# res.show()
# assert False, "expected error. objects of different dimensions not supported."
#except EnvironmentError:
# pass
#try:
# res = iris[2] == iris
# res.show()
# assert False, "expected error. objects of different dimensions not supported."
#except EnvironmentError:
# pass
#vec/vec
res = iris[0] == iris[1]
res_rows = res.nrow
assert res_rows == rows, "dimension mismatch"
new_rows = iris[res].nrow
assert new_rows == 0, "wrong number of rows returned"
res = iris[2] == iris[2]
res_rows = res.nrow
assert res_rows == rows, "dimension mismatch"
new_rows = iris[res].nrow
assert new_rows == 150, "wrong number of rows returned"
#vec/scaler
res = iris[0] == 4.7
res_rows = res.nrow
assert res_rows == rows, "dimension mismatch"
new_rows = iris[res].nrow
assert new_rows == 2, "wrong number of rows returned"
res = 3.5 == iris[1]
res_rows = res.nrow
assert res_rows == rows, "dimension mismatch"
new_rows = iris[res].nrow
assert new_rows == 6, "wrong number of rows returned"
# frame/frame
res = iris == iris
res_rows, res_cols = res.dim
assert res_rows == rows and res_cols == cols, "dimension mismatch"
res = iris[0:2] == iris[1:3]
res_rows, res_cols = res.dim
assert res_rows == rows and res_cols == 2, "dimension mismatch"
#try:
# res = iris == iris[0:3]
# res.show()
# assert False, "expected error. frames are different dimensions."
#except EnvironmentError:
# pass
if __name__ == "__main__":
h2o.run_test(sys.argv, binop_eq)
| {
"content_hash": "ee5fe93f969f8ca86276ab5ccb97f82f",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 87,
"avg_line_length": 28.404761904761905,
"alnum_prop": 0.5984911986588433,
"repo_name": "PawarPawan/h2o-v3",
"id": "bc5fa5b24f87290b39b06d65791a395ace8d0bb0",
"size": "2386",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "h2o-py/tests/testdir_munging/binop/pyunit_binop2_eq.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "5090"
},
{
"name": "CSS",
"bytes": "163561"
},
{
"name": "CoffeeScript",
"bytes": "261942"
},
{
"name": "Emacs Lisp",
"bytes": "8914"
},
{
"name": "Groovy",
"bytes": "78"
},
{
"name": "HTML",
"bytes": "140122"
},
{
"name": "Java",
"bytes": "5407730"
},
{
"name": "JavaScript",
"bytes": "88331"
},
{
"name": "Makefile",
"bytes": "31513"
},
{
"name": "Python",
"bytes": "2009340"
},
{
"name": "R",
"bytes": "1818630"
},
{
"name": "Rebol",
"bytes": "3997"
},
{
"name": "Ruby",
"bytes": "299"
},
{
"name": "Scala",
"bytes": "16336"
},
{
"name": "Shell",
"bytes": "44607"
},
{
"name": "TeX",
"bytes": "469926"
}
],
"symlink_target": ""
} |
"""A requests-compatible system for BIG-IP token-based authentication.
BIG-IP only allows users with the Administrator role to authenticate to
iControl using HTTP Basic auth. Non-Administrator users can use the
token-based authentication scheme described at:
https://devcentral.f5.com/wiki/icontrol.authentication_with_the_f5_rest_api.ashx
Use this module with requests to automatically get a new token, and attach
:class:`requests.Session` object, so that it is used to authenticate future
requests.
Instead of using this module directly, it is easiest to enable it by passing
a ``token=True`` argument when creating the
:class:`.iControlRESTSession`:
>>> iCRS = iControlRESTSession('bob', 'secret', token=True)
"""
import requests
import time
from icontrol.exceptions import iControlUnexpectedHTTPError
from icontrol.exceptions import InvalidScheme
from requests.auth import AuthBase
from requests.auth import HTTPBasicAuth
try:
# Python 3
from urllib.parse import urlsplit
except ImportError:
# Python 2
from urlparse import urlsplit
class iControlRESTTokenAuth(AuthBase):
"""Acquire and renew BigIP iControl REST authentication tokens.
:param str username: The username on BigIP
:param str password: The password for username on BigIP
:param str login_provider_name: The name of the login provider that \
BigIP should consult when creating the token.
:param str verify: The path to a CA bundle containing the \
CA certificate for SSL validation
:param proxies: A dict of proxy information for Requests to utilize \
on this connection to the BigIP
If ``username`` is configured locally on the BigIP,
``login_provider_name`` should be ``"tmos"`` (default). Otherwise
(for example, ``username`` is configured on LDAP that BigIP consults),
consult BigIP documentation or your system administrator for the value
of ``login_provider_name``.
"""
def __init__(self, username, password, login_provider_name='tmos',
verify=False, auth_provider=None, proxies=None):
self.username = username
self.password = password
self.login_provider_name = login_provider_name
self.proxies = proxies
self.token = None
self.expiration = None
self.attempts = 0
self.verify = verify
self.auth_provider = auth_provider
# We don't actually do auth at this point because we don't have a
# hostname to authenticate to.
def _check_token_validity(self):
if not self.token:
return False
if self.expiration and time.time() > self.expiration:
return False
return True
def get_auth_providers(self, netloc):
"""BIG-IQ specific query for auth providers
BIG-IP doesn't really need this because BIG-IP's multiple auth providers
seem to handle fallthrough just fine. BIG-IQ on the other hand, needs to
have its auth provider specified if you're using one of the non-default
ones.
:param netloc:
:return:
"""
url = "https://%s/info/system?null" % (netloc)
response = requests.get(url, verify=self.verify, proxies=self.proxies)
if not response.ok or not hasattr(response, "json"):
error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message, response=response)
respJson = response.json()
result = respJson['providers']
return result
def get_new_token(self, netloc):
"""Get a new token from BIG-IP and store it internally.
Throws relevant exception if it fails to get a new token.
This method will be called automatically if a request is attempted
but there is no authentication token, or the authentication token
is expired. It is usually not necessary for users to call it, but
it can be called if it is known that the authentication token has
been invalidated by other means.
"""
login_body = {
'username': self.username,
'password': self.password,
}
if self.auth_provider:
if self.auth_provider == 'local':
login_body['loginProviderName'] = 'local'
elif self.auth_provider == 'tmos':
login_body['loginProviderName'] = 'tmos'
elif self.auth_provider not in ['none', 'default']:
providers = self.get_auth_providers(netloc)
for provider in providers:
if self.auth_provider in provider['link']:
login_body['loginProviderName'] = provider['name']
break
elif self.auth_provider == provider['name']:
login_body['loginProviderName'] = provider['name']
break
else:
if self.login_provider_name == 'tmos':
login_body['loginProviderName'] = self.login_provider_name
login_url = "https://%s/mgmt/shared/authn/login" % (netloc)
response = requests.post(
login_url,
json=login_body,
verify=self.verify,
auth=HTTPBasicAuth(self.username, self.password),
proxies=self.proxies,
)
self.attempts += 1
if not response.ok or not hasattr(response, "json"):
error_message = '%s Unexpected Error: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message,
response=response)
respJson = response.json()
token = self._get_token_from_response(respJson)
created_bigip = self._get_last_update_micros(token)
try:
expiration_bigip = self._get_expiration_micros(
token, created_bigip
)
except (KeyError, ValueError):
error_message = \
'%s Unparseable Response: %s for uri: %s\nText: %r' %\
(response.status_code,
response.reason,
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message,
response=response)
try:
self.expiration = self._get_token_expiration_time(
created_bigip, expiration_bigip
)
except iControlUnexpectedHTTPError:
error_message = \
'%s Token already expired: %s for uri: %s\nText: %r' % \
(response.status_code,
time.ctime(expiration_bigip),
response.url,
response.text)
raise iControlUnexpectedHTTPError(error_message,
response=response)
def _get_expiration_micros(self, token, created_bigip=None):
if 'expirationMicros' in token:
expiration = token['expirationMicros']
expiration_bigip = int(expiration) / 1000000.0
elif 'timeout' in token:
expiration_bigip = created_bigip + token['timeout']
else:
raise iControlUnexpectedHTTPError
return expiration_bigip
def _get_token_expiration_time(self, created_bigip, expiration_bigip):
req_start_time = time.time()
# Set our token expiration time.
# The expirationMicros field is when BIG-IP will expire the token
# relative to its local clock. To avoid issues caused by incorrect
# clocks or network latency, we'll compute an expiration time that is
# referenced to our local clock, and expires slightly before the token
# should actually expire on BIG-IP
# Reference to our clock: compute for how long this token is valid as
# the difference between when it expires and when it was created,
# according to BIG-IP.
if expiration_bigip < created_bigip:
raise iControlUnexpectedHTTPError
valid_duration = expiration_bigip - created_bigip
# Assign new expiration time that is 1 minute earlier than BIG-IP's
# expiration time, as long as that would still be at least a minute in
# the future. This should account for clock skew between us and
# BIG-IP. By default tokens last for 60 minutes so getting one every
# 59 minutes instead of 60 is harmless.
if valid_duration > 120.0:
valid_duration -= 60.0
return req_start_time + valid_duration
def _get_last_update_micros(self, token):
try:
last_updated = token['lastUpdateMicros']
created_bigip = int(last_updated) / 1000000.0
except (KeyError, ValueError):
raise iControlUnexpectedHTTPError(
"lastUpdateMicros field was not found in the response"
)
return created_bigip
def _get_token_from_response(self, respJson):
try:
token = respJson['token']
self.token = token['token']
except KeyError:
raise iControlUnexpectedHTTPError(
"Token field not found in the response"
)
return token
def __call__(self, request):
if not self._check_token_validity():
scheme, netloc, path, _, _ = urlsplit(request.url)
if scheme != "https":
raise InvalidScheme(scheme)
self.get_new_token(netloc)
request.headers['X-F5-Auth-Token'] = self.token
return request
| {
"content_hash": "606baa9319d9bfab4983056ca13c75d3",
"timestamp": "",
"source": "github",
"line_count": 247,
"max_line_length": 82,
"avg_line_length": 40.4251012145749,
"alnum_prop": 0.6053079619429144,
"repo_name": "F5Networks/f5-icontrol-rest-python",
"id": "b2aa0fc6b31d539f0f7568d66bdd139310ee792b",
"size": "10578",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.0",
"path": "icontrol/authtoken.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "361"
},
{
"name": "Makefile",
"bytes": "660"
},
{
"name": "Python",
"bytes": "93524"
},
{
"name": "Shell",
"bytes": "4198"
}
],
"symlink_target": ""
} |
"""
pygments.lexers.robotframework
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Robot Framework.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
# Copyright 2012 Nokia Siemens Networks Oyj
#
# 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 writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from pygments.lexer import Lexer
from pygments.token import Token
__all__ = ['RobotFrameworkLexer']
HEADING = Token.Generic.Heading
SETTING = Token.Keyword.Namespace
IMPORT = Token.Name.Namespace
TC_KW_NAME = Token.Generic.Subheading
KEYWORD = Token.Name.Function
ARGUMENT = Token.String
VARIABLE = Token.Name.Variable
COMMENT = Token.Comment
SEPARATOR = Token.Punctuation
SYNTAX = Token.Punctuation
GHERKIN = Token.Generic.Emph
ERROR = Token.Error
def normalize(string, remove=''):
string = string.lower()
for char in remove + ' ':
if char in string:
string = string.replace(char, '')
return string
class RobotFrameworkLexer(Lexer):
"""
For Robot Framework test data.
Supports both space and pipe separated plain text formats.
.. versionadded:: 1.6
"""
name = 'RobotFramework'
url = 'http://robotframework.org'
aliases = ['robotframework']
filenames = ['*.robot', '*.resource']
mimetypes = ['text/x-robotframework']
def __init__(self, **options):
options['tabsize'] = 2
options['encoding'] = 'UTF-8'
Lexer.__init__(self, **options)
def get_tokens_unprocessed(self, text):
row_tokenizer = RowTokenizer()
var_tokenizer = VariableTokenizer()
index = 0
for row in text.splitlines():
for value, token in row_tokenizer.tokenize(row):
for value, token in var_tokenizer.tokenize(value, token):
if value:
yield index, token, str(value)
index += len(value)
class VariableTokenizer:
def tokenize(self, string, token):
var = VariableSplitter(string, identifiers='$@%&')
if var.start < 0 or token in (COMMENT, ERROR):
yield string, token
return
for value, token in self._tokenize(var, string, token):
if value:
yield value, token
def _tokenize(self, var, string, orig_token):
before = string[:var.start]
yield before, orig_token
yield var.identifier + '{', SYNTAX
yield from self.tokenize(var.base, VARIABLE)
yield '}', SYNTAX
if var.index is not None:
yield '[', SYNTAX
yield from self.tokenize(var.index, VARIABLE)
yield ']', SYNTAX
yield from self.tokenize(string[var.end:], orig_token)
class RowTokenizer:
def __init__(self):
self._table = UnknownTable()
self._splitter = RowSplitter()
testcases = TestCaseTable()
settings = SettingTable(testcases.set_default_template)
variables = VariableTable()
keywords = KeywordTable()
self._tables = {'settings': settings, 'setting': settings,
'metadata': settings,
'variables': variables, 'variable': variables,
'testcases': testcases, 'testcase': testcases,
'tasks': testcases, 'task': testcases,
'keywords': keywords, 'keyword': keywords,
'userkeywords': keywords, 'userkeyword': keywords}
def tokenize(self, row):
commented = False
heading = False
for index, value in enumerate(self._splitter.split(row)):
# First value, and every second after that, is a separator.
index, separator = divmod(index-1, 2)
if value.startswith('#'):
commented = True
elif index == 0 and value.startswith('*'):
self._table = self._start_table(value)
heading = True
yield from self._tokenize(value, index, commented,
separator, heading)
self._table.end_row()
def _start_table(self, header):
name = normalize(header, remove='*')
return self._tables.get(name, UnknownTable())
def _tokenize(self, value, index, commented, separator, heading):
if commented:
yield value, COMMENT
elif separator:
yield value, SEPARATOR
elif heading:
yield value, HEADING
else:
yield from self._table.tokenize(value, index)
class RowSplitter:
_space_splitter = re.compile('( {2,})')
_pipe_splitter = re.compile(r'((?:^| +)\|(?: +|$))')
def split(self, row):
splitter = (row.startswith('| ') and self._split_from_pipes
or self._split_from_spaces)
yield from splitter(row)
yield '\n'
def _split_from_spaces(self, row):
yield '' # Start with (pseudo)separator similarly as with pipes
yield from self._space_splitter.split(row)
def _split_from_pipes(self, row):
_, separator, rest = self._pipe_splitter.split(row, 1)
yield separator
while self._pipe_splitter.search(rest):
cell, separator, rest = self._pipe_splitter.split(rest, 1)
yield cell
yield separator
yield rest
class Tokenizer:
_tokens = None
def __init__(self):
self._index = 0
def tokenize(self, value):
values_and_tokens = self._tokenize(value, self._index)
self._index += 1
if isinstance(values_and_tokens, type(Token)):
values_and_tokens = [(value, values_and_tokens)]
return values_and_tokens
def _tokenize(self, value, index):
index = min(index, len(self._tokens) - 1)
return self._tokens[index]
def _is_assign(self, value):
if value.endswith('='):
value = value[:-1].strip()
var = VariableSplitter(value, identifiers='$@&')
return var.start == 0 and var.end == len(value)
class Comment(Tokenizer):
_tokens = (COMMENT,)
class Setting(Tokenizer):
_tokens = (SETTING, ARGUMENT)
_keyword_settings = ('suitesetup', 'suiteprecondition', 'suiteteardown',
'suitepostcondition', 'testsetup', 'tasksetup', 'testprecondition',
'testteardown','taskteardown', 'testpostcondition', 'testtemplate', 'tasktemplate')
_import_settings = ('library', 'resource', 'variables')
_other_settings = ('documentation', 'metadata', 'forcetags', 'defaulttags',
'testtimeout','tasktimeout')
_custom_tokenizer = None
def __init__(self, template_setter=None):
Tokenizer.__init__(self)
self._template_setter = template_setter
def _tokenize(self, value, index):
if index == 1 and self._template_setter:
self._template_setter(value)
if index == 0:
normalized = normalize(value)
if normalized in self._keyword_settings:
self._custom_tokenizer = KeywordCall(support_assign=False)
elif normalized in self._import_settings:
self._custom_tokenizer = ImportSetting()
elif normalized not in self._other_settings:
return ERROR
elif self._custom_tokenizer:
return self._custom_tokenizer.tokenize(value)
return Tokenizer._tokenize(self, value, index)
class ImportSetting(Tokenizer):
_tokens = (IMPORT, ARGUMENT)
class TestCaseSetting(Setting):
_keyword_settings = ('setup', 'precondition', 'teardown', 'postcondition',
'template')
_import_settings = ()
_other_settings = ('documentation', 'tags', 'timeout')
def _tokenize(self, value, index):
if index == 0:
type = Setting._tokenize(self, value[1:-1], index)
return [('[', SYNTAX), (value[1:-1], type), (']', SYNTAX)]
return Setting._tokenize(self, value, index)
class KeywordSetting(TestCaseSetting):
_keyword_settings = ('teardown',)
_other_settings = ('documentation', 'arguments', 'return', 'timeout', 'tags')
class Variable(Tokenizer):
_tokens = (SYNTAX, ARGUMENT)
def _tokenize(self, value, index):
if index == 0 and not self._is_assign(value):
return ERROR
return Tokenizer._tokenize(self, value, index)
class KeywordCall(Tokenizer):
_tokens = (KEYWORD, ARGUMENT)
def __init__(self, support_assign=True):
Tokenizer.__init__(self)
self._keyword_found = not support_assign
self._assigns = 0
def _tokenize(self, value, index):
if not self._keyword_found and self._is_assign(value):
self._assigns += 1
return SYNTAX # VariableTokenizer tokenizes this later.
if self._keyword_found:
return Tokenizer._tokenize(self, value, index - self._assigns)
self._keyword_found = True
return GherkinTokenizer().tokenize(value, KEYWORD)
class GherkinTokenizer:
_gherkin_prefix = re.compile('^(Given|When|Then|And|But) ', re.IGNORECASE)
def tokenize(self, value, token):
match = self._gherkin_prefix.match(value)
if not match:
return [(value, token)]
end = match.end()
return [(value[:end], GHERKIN), (value[end:], token)]
class TemplatedKeywordCall(Tokenizer):
_tokens = (ARGUMENT,)
class ForLoop(Tokenizer):
def __init__(self):
Tokenizer.__init__(self)
self._in_arguments = False
def _tokenize(self, value, index):
token = self._in_arguments and ARGUMENT or SYNTAX
if value.upper() in ('IN', 'IN RANGE'):
self._in_arguments = True
return token
class _Table:
_tokenizer_class = None
def __init__(self, prev_tokenizer=None):
self._tokenizer = self._tokenizer_class()
self._prev_tokenizer = prev_tokenizer
self._prev_values_on_row = []
def tokenize(self, value, index):
if self._continues(value, index):
self._tokenizer = self._prev_tokenizer
yield value, SYNTAX
else:
yield from self._tokenize(value, index)
self._prev_values_on_row.append(value)
def _continues(self, value, index):
return value == '...' and all(self._is_empty(t)
for t in self._prev_values_on_row)
def _is_empty(self, value):
return value in ('', '\\')
def _tokenize(self, value, index):
return self._tokenizer.tokenize(value)
def end_row(self):
self.__init__(prev_tokenizer=self._tokenizer)
class UnknownTable(_Table):
_tokenizer_class = Comment
def _continues(self, value, index):
return False
class VariableTable(_Table):
_tokenizer_class = Variable
class SettingTable(_Table):
_tokenizer_class = Setting
def __init__(self, template_setter, prev_tokenizer=None):
_Table.__init__(self, prev_tokenizer)
self._template_setter = template_setter
def _tokenize(self, value, index):
if index == 0 and normalize(value) == 'testtemplate':
self._tokenizer = Setting(self._template_setter)
return _Table._tokenize(self, value, index)
def end_row(self):
self.__init__(self._template_setter, prev_tokenizer=self._tokenizer)
class TestCaseTable(_Table):
_setting_class = TestCaseSetting
_test_template = None
_default_template = None
@property
def _tokenizer_class(self):
if self._test_template or (self._default_template and
self._test_template is not False):
return TemplatedKeywordCall
return KeywordCall
def _continues(self, value, index):
return index > 0 and _Table._continues(self, value, index)
def _tokenize(self, value, index):
if index == 0:
if value:
self._test_template = None
return GherkinTokenizer().tokenize(value, TC_KW_NAME)
if index == 1 and self._is_setting(value):
if self._is_template(value):
self._test_template = False
self._tokenizer = self._setting_class(self.set_test_template)
else:
self._tokenizer = self._setting_class()
if index == 1 and self._is_for_loop(value):
self._tokenizer = ForLoop()
if index == 1 and self._is_empty(value):
return [(value, SYNTAX)]
return _Table._tokenize(self, value, index)
def _is_setting(self, value):
return value.startswith('[') and value.endswith(']')
def _is_template(self, value):
return normalize(value) == '[template]'
def _is_for_loop(self, value):
return value.startswith(':') and normalize(value, remove=':') == 'for'
def set_test_template(self, template):
self._test_template = self._is_template_set(template)
def set_default_template(self, template):
self._default_template = self._is_template_set(template)
def _is_template_set(self, template):
return normalize(template) not in ('', '\\', 'none', '${empty}')
class KeywordTable(TestCaseTable):
_tokenizer_class = KeywordCall
_setting_class = KeywordSetting
def _is_template(self, value):
return False
# Following code copied directly from Robot Framework 2.7.5.
class VariableSplitter:
def __init__(self, string, identifiers):
self.identifier = None
self.base = None
self.index = None
self.start = -1
self.end = -1
self._identifiers = identifiers
self._may_have_internal_variables = False
try:
self._split(string)
except ValueError:
pass
else:
self._finalize()
def get_replaced_base(self, variables):
if self._may_have_internal_variables:
return variables.replace_string(self.base)
return self.base
def _finalize(self):
self.identifier = self._variable_chars[0]
self.base = ''.join(self._variable_chars[2:-1])
self.end = self.start + len(self._variable_chars)
if self._has_list_or_dict_variable_index():
self.index = ''.join(self._list_and_dict_variable_index_chars[1:-1])
self.end += len(self._list_and_dict_variable_index_chars)
def _has_list_or_dict_variable_index(self):
return self._list_and_dict_variable_index_chars\
and self._list_and_dict_variable_index_chars[-1] == ']'
def _split(self, string):
start_index, max_index = self._find_variable(string)
self.start = start_index
self._open_curly = 1
self._state = self._variable_state
self._variable_chars = [string[start_index], '{']
self._list_and_dict_variable_index_chars = []
self._string = string
start_index += 2
for index, char in enumerate(string[start_index:]):
index += start_index # Giving start to enumerate only in Py 2.6+
try:
self._state(char, index)
except StopIteration:
return
if index == max_index and not self._scanning_list_variable_index():
return
def _scanning_list_variable_index(self):
return self._state in [self._waiting_list_variable_index_state,
self._list_variable_index_state]
def _find_variable(self, string):
max_end_index = string.rfind('}')
if max_end_index == -1:
raise ValueError('No variable end found')
if self._is_escaped(string, max_end_index):
return self._find_variable(string[:max_end_index])
start_index = self._find_start_index(string, 1, max_end_index)
if start_index == -1:
raise ValueError('No variable start found')
return start_index, max_end_index
def _find_start_index(self, string, start, end):
index = string.find('{', start, end) - 1
if index < 0:
return -1
if self._start_index_is_ok(string, index):
return index
return self._find_start_index(string, index+2, end)
def _start_index_is_ok(self, string, index):
return string[index] in self._identifiers\
and not self._is_escaped(string, index)
def _is_escaped(self, string, index):
escaped = False
while index > 0 and string[index-1] == '\\':
index -= 1
escaped = not escaped
return escaped
def _variable_state(self, char, index):
self._variable_chars.append(char)
if char == '}' and not self._is_escaped(self._string, index):
self._open_curly -= 1
if self._open_curly == 0:
if not self._is_list_or_dict_variable():
raise StopIteration
self._state = self._waiting_list_variable_index_state
elif char in self._identifiers:
self._state = self._internal_variable_start_state
def _is_list_or_dict_variable(self):
return self._variable_chars[0] in ('@','&')
def _internal_variable_start_state(self, char, index):
self._state = self._variable_state
if char == '{':
self._variable_chars.append(char)
self._open_curly += 1
self._may_have_internal_variables = True
else:
self._variable_state(char, index)
def _waiting_list_variable_index_state(self, char, index):
if char != '[':
raise StopIteration
self._list_and_dict_variable_index_chars.append(char)
self._state = self._list_variable_index_state
def _list_variable_index_state(self, char, index):
self._list_and_dict_variable_index_chars.append(char)
if char == ']':
raise StopIteration
| {
"content_hash": "57a4eb4fecfa134712a3a79cf01d7b0c",
"timestamp": "",
"source": "github",
"line_count": 552,
"max_line_length": 108,
"avg_line_length": 33.42210144927536,
"alnum_prop": 0.5939617323432165,
"repo_name": "pygments/pygments",
"id": "91794d0f2b3362c63e3f11226428f7f9d78678e0",
"size": "18449",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "pygments/lexers/robotframework.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "APL",
"bytes": "587"
},
{
"name": "ASP.NET",
"bytes": "636"
},
{
"name": "ActionScript",
"bytes": "5686"
},
{
"name": "Ada",
"bytes": "6951"
},
{
"name": "Agda",
"bytes": "3155"
},
{
"name": "Alloy",
"bytes": "6579"
},
{
"name": "AppleScript",
"bytes": "421"
},
{
"name": "Assembly",
"bytes": "3577"
},
{
"name": "Asymptote",
"bytes": "10210"
},
{
"name": "AutoHotkey",
"bytes": "3733"
},
{
"name": "AutoIt",
"bytes": "732"
},
{
"name": "Awk",
"bytes": "4528"
},
{
"name": "Batchfile",
"bytes": "4275"
},
{
"name": "Berry",
"bytes": "8606"
},
{
"name": "BlitzBasic",
"bytes": "1824"
},
{
"name": "BlitzMax",
"bytes": "2387"
},
{
"name": "Boo",
"bytes": "1111"
},
{
"name": "Boogie",
"bytes": "4482"
},
{
"name": "C",
"bytes": "108863"
},
{
"name": "C#",
"bytes": "17784"
},
{
"name": "C++",
"bytes": "85604"
},
{
"name": "CMake",
"bytes": "2150"
},
{
"name": "COBOL",
"bytes": "117432"
},
{
"name": "CSS",
"bytes": "982"
},
{
"name": "Cap'n Proto",
"bytes": "390"
},
{
"name": "Ceylon",
"bytes": "1387"
},
{
"name": "Chapel",
"bytes": "4934"
},
{
"name": "Cirru",
"bytes": "3285"
},
{
"name": "Clean",
"bytes": "8739"
},
{
"name": "Clojure",
"bytes": "25885"
},
{
"name": "CoffeeScript",
"bytes": "20149"
},
{
"name": "ColdFusion",
"bytes": "9263"
},
{
"name": "Common Lisp",
"bytes": "49017"
},
{
"name": "Coq",
"bytes": "66"
},
{
"name": "Crystal",
"bytes": "36037"
},
{
"name": "Csound",
"bytes": "1135"
},
{
"name": "Csound Document",
"bytes": "209"
},
{
"name": "Csound Score",
"bytes": "310"
},
{
"name": "Cuda",
"bytes": "776"
},
{
"name": "Cypher",
"bytes": "3365"
},
{
"name": "D",
"bytes": "5475"
},
{
"name": "Dart",
"bytes": "591"
},
{
"name": "Dylan",
"bytes": "6343"
},
{
"name": "Eiffel",
"bytes": "2145"
},
{
"name": "Elixir",
"bytes": "4340"
},
{
"name": "Elm",
"bytes": "1187"
},
{
"name": "Emacs Lisp",
"bytes": "198742"
},
{
"name": "Erlang",
"bytes": "6048"
},
{
"name": "F#",
"bytes": "19734"
},
{
"name": "F*",
"bytes": "42435"
},
{
"name": "Factor",
"bytes": "10194"
},
{
"name": "Fancy",
"bytes": "2581"
},
{
"name": "Fantom",
"bytes": "25331"
},
{
"name": "Fennel",
"bytes": "6994"
},
{
"name": "Forth",
"bytes": "48"
},
{
"name": "Fortran",
"bytes": "38732"
},
{
"name": "Futhark",
"bytes": "507"
},
{
"name": "G-code",
"bytes": "2791"
},
{
"name": "GAP",
"bytes": "19390"
},
{
"name": "GDScript",
"bytes": "1240"
},
{
"name": "GLSL",
"bytes": "450"
},
{
"name": "Gherkin",
"bytes": "1267"
},
{
"name": "Gnuplot",
"bytes": "10376"
},
{
"name": "Go",
"bytes": "430"
},
{
"name": "Golo",
"bytes": "1649"
},
{
"name": "Gosu",
"bytes": "2853"
},
{
"name": "Groovy",
"bytes": "2663"
},
{
"name": "HLSL",
"bytes": "5123"
},
{
"name": "HTML",
"bytes": "146106"
},
{
"name": "Handlebars",
"bytes": "1738"
},
{
"name": "Haskell",
"bytes": "49856"
},
{
"name": "Haxe",
"bytes": "16812"
},
{
"name": "Hy",
"bytes": "7237"
},
{
"name": "IDL",
"bytes": "57251"
},
{
"name": "Idris",
"bytes": "2771"
},
{
"name": "Inform 7",
"bytes": "2046"
},
{
"name": "Ioke",
"bytes": "469"
},
{
"name": "Isabelle",
"bytes": "62868"
},
{
"name": "J",
"bytes": "25519"
},
{
"name": "Jasmin",
"bytes": "9428"
},
{
"name": "Java",
"bytes": "20381"
},
{
"name": "JavaScript",
"bytes": "2686"
},
{
"name": "Jsonnet",
"bytes": "1217"
},
{
"name": "Julia",
"bytes": "11904"
},
{
"name": "Kotlin",
"bytes": "971"
},
{
"name": "LSL",
"bytes": "160"
},
{
"name": "Lasso",
"bytes": "18650"
},
{
"name": "Lean",
"bytes": "8611"
},
{
"name": "LilyPond",
"bytes": "2804"
},
{
"name": "Limbo",
"bytes": "9891"
},
{
"name": "Liquid",
"bytes": "862"
},
{
"name": "LiveScript",
"bytes": "972"
},
{
"name": "Logos",
"bytes": "306"
},
{
"name": "Logtalk",
"bytes": "7260"
},
{
"name": "Lua",
"bytes": "9184"
},
{
"name": "MAXScript",
"bytes": "8464"
},
{
"name": "MQL4",
"bytes": "6230"
},
{
"name": "MQL5",
"bytes": "4866"
},
{
"name": "Macaulay2",
"bytes": "409"
},
{
"name": "Makefile",
"bytes": "60153"
},
{
"name": "Mako",
"bytes": "1023"
},
{
"name": "Mask",
"bytes": "855"
},
{
"name": "Mathematica",
"bytes": "355"
},
{
"name": "Meson",
"bytes": "965"
},
{
"name": "Modula-2",
"bytes": "23838"
},
{
"name": "Monkey",
"bytes": "2587"
},
{
"name": "Moocode",
"bytes": "3343"
},
{
"name": "MoonScript",
"bytes": "14862"
},
{
"name": "Motoko",
"bytes": "6213"
},
{
"name": "Myghty",
"bytes": "3939"
},
{
"name": "NCL",
"bytes": "473"
},
{
"name": "NSIS",
"bytes": "7663"
},
{
"name": "Nemerle",
"bytes": "1517"
},
{
"name": "NewLisp",
"bytes": "42726"
},
{
"name": "Nim",
"bytes": "37191"
},
{
"name": "Nit",
"bytes": "55581"
},
{
"name": "Nix",
"bytes": "2448"
},
{
"name": "OCaml",
"bytes": "42416"
},
{
"name": "Objective-C",
"bytes": "3385"
},
{
"name": "Objective-J",
"bytes": "15340"
},
{
"name": "Opa",
"bytes": "172"
},
{
"name": "OpenEdge ABL",
"bytes": "318"
},
{
"name": "PHP",
"bytes": "17903"
},
{
"name": "POV-Ray SDL",
"bytes": "1455"
},
{
"name": "Pan",
"bytes": "1241"
},
{
"name": "Pascal",
"bytes": "84520"
},
{
"name": "Pawn",
"bytes": "6555"
},
{
"name": "Perl",
"bytes": "47698"
},
{
"name": "PigLatin",
"bytes": "6657"
},
{
"name": "Pike",
"bytes": "8479"
},
{
"name": "Pony",
"bytes": "247"
},
{
"name": "PostScript",
"bytes": "8648"
},
{
"name": "PowerShell",
"bytes": "6127"
},
{
"name": "Procfile",
"bytes": "128"
},
{
"name": "Prolog",
"bytes": "9661"
},
{
"name": "Puppet",
"bytes": "130"
},
{
"name": "Python",
"bytes": "4303681"
},
{
"name": "QML",
"bytes": "3912"
},
{
"name": "R",
"bytes": "4057"
},
{
"name": "REXX",
"bytes": "862"
},
{
"name": "Racket",
"bytes": "11341"
},
{
"name": "Raku",
"bytes": "4692"
},
{
"name": "Reason",
"bytes": "1316"
},
{
"name": "Rebol",
"bytes": "1887"
},
{
"name": "Red",
"bytes": "10792"
},
{
"name": "Redcode",
"bytes": "830"
},
{
"name": "Roff",
"bytes": "49294"
},
{
"name": "Ruby",
"bytes": "91403"
},
{
"name": "Rust",
"bytes": "23551"
},
{
"name": "SWIG",
"bytes": "6153"
},
{
"name": "SaltStack",
"bytes": "1040"
},
{
"name": "Scala",
"bytes": "11132"
},
{
"name": "Scaml",
"bytes": "166"
},
{
"name": "Scheme",
"bytes": "46229"
},
{
"name": "Scilab",
"bytes": "1639"
},
{
"name": "Shell",
"bytes": "132777"
},
{
"name": "ShellSession",
"bytes": "320"
},
{
"name": "Shen",
"bytes": "3134"
},
{
"name": "Sieve",
"bytes": "1205"
},
{
"name": "Singularity",
"bytes": "1070"
},
{
"name": "Slim",
"bytes": "679"
},
{
"name": "Smali",
"bytes": "832"
},
{
"name": "Smalltalk",
"bytes": "156665"
},
{
"name": "Smithy",
"bytes": "14242"
},
{
"name": "Solidity",
"bytes": "1544"
},
{
"name": "SourcePawn",
"bytes": "130"
},
{
"name": "Stan",
"bytes": "2547"
},
{
"name": "Standard ML",
"bytes": "36869"
},
{
"name": "SuperCollider",
"bytes": "1578"
},
{
"name": "Swift",
"bytes": "2035"
},
{
"name": "SystemVerilog",
"bytes": "265"
},
{
"name": "TSQL",
"bytes": "1576"
},
{
"name": "TeX",
"bytes": "2234"
},
{
"name": "Tea",
"bytes": "391"
},
{
"name": "Thrift",
"bytes": "167"
},
{
"name": "VBA",
"bytes": "846"
},
{
"name": "VBScript",
"bytes": "1199"
},
{
"name": "VCL",
"bytes": "4128"
},
{
"name": "VHDL",
"bytes": "4446"
},
{
"name": "Vim Script",
"bytes": "16922"
},
{
"name": "Visual Basic .NET",
"bytes": "16364"
},
{
"name": "WebAssembly",
"bytes": "916"
},
{
"name": "Whiley",
"bytes": "9029"
},
{
"name": "X10",
"bytes": "198"
},
{
"name": "XQuery",
"bytes": "11179"
},
{
"name": "XSLT",
"bytes": "755"
},
{
"name": "Xtend",
"bytes": "741"
},
{
"name": "Zeek",
"bytes": "10863"
},
{
"name": "Zephir",
"bytes": "485"
},
{
"name": "Zig",
"bytes": "8703"
},
{
"name": "eC",
"bytes": "26388"
},
{
"name": "mcfunction",
"bytes": "6450"
},
{
"name": "mupad",
"bytes": "2443"
},
{
"name": "nesC",
"bytes": "23697"
},
{
"name": "q",
"bytes": "3349"
},
{
"name": "sed",
"bytes": "1614"
},
{
"name": "xBase",
"bytes": "3349"
}
],
"symlink_target": ""
} |
from flask import request
from flask.ext.restful import Resource
from tracker.extensions import db, api
from tracker.models import Comment, Expense
from tracker.forms import CommentCreateForm
from flask.ext.login import current_user
from tracker.utils import seconds_since_week
from tracker.decorators import login_required
class CommentView(Resource):
@login_required
def post(self,expense_id):
form = CommentCreateForm()
if not form.validate_on_submit():
return form.errors, 422
comment = Comment()
form.populate_obj(comment)
comment.expense_id = expense_id
comment.user = current_user
comment.save()
return comment.to_dict()
class CommentListView(Resource):
@login_required
def get(self,expense_id):
comments = Expense.get_comments(expense_id)
return [comment.to_dict() for comment in comments]
api.add_resource(CommentView, '/api/v1/comment/<int:expense_id>', endpoint = 'comment')
api.add_resource(CommentListView, '/api/v1/comments/<int:expense_id>', endpoint = 'comments')
| {
"content_hash": "9e550a6b95608a89bdf0ba14e950a7aa",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 93,
"avg_line_length": 26.842105263157894,
"alnum_prop": 0.7627450980392156,
"repo_name": "ahsanali/expense-tracker",
"id": "95eb66af3f55024d1763cd6600c7d86b79da5259",
"size": "1020",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tracker/views/comments.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "397"
},
{
"name": "HTML",
"bytes": "11251"
},
{
"name": "JavaScript",
"bytes": "9575"
},
{
"name": "Python",
"bytes": "41983"
}
],
"symlink_target": ""
} |
class Maybe(object):
"""Maybe a"""
def is_defined(self):
pass
def get_or_else(self, default):
"""get_or_else :: a -> a"""
pass
def or_else(self, default):
"""or_else :: Maybe a -> Maybe a"""
pass
def map(self, f):
"""map :: (a -> b) -> Maybe b"""
pass
def flatmap(self, f):
"""flatmap :: (a -> Maybe b) -> Maybe b"""
pass
def foreach(self, f):
pass
def fold(self, z, f):
"""fold :: b -> (b -> a -> b) -> b"""
pass
@staticmethod
def pure(value):
if value is None:
return Nothing
else:
return Just(value)
class Just(Maybe):
def __init__(self, value):
self.__value = value
def is_defined(self):
return True
def get_or_else(self, default):
return self.__value
def or_else(self, default):
return self
def map(self, f):
return Maybe.pure(f(self.__value))
def flatmap(self, f):
return f(self.__value)
def foreach(self, f):
f(self.__value)
def fold(self, z, f):
return f(z, self.__value)
def __hash__(self):
return hash(self.__class__) ^ hash(self.__value)
def __repr__(self):
return "Just(%s)" % self.__value
def __eq__(self, other):
return self.__class__ == other.__class__ and self.__value == other.__value
def __iter__(self):
yield self.__value
class _Nothing(Maybe):
def is_defined(self):
pass
def get_or_else(self, default):
return default
def or_else(self, default):
return default
def map(self, f):
return self
def flatmap(self, f):
return self
def fold(self, z, f):
return z
def __hash__(self):
return hash(self.__class__)
def __repr__(self):
return "Nothing"
def __eq__(self, other):
return self.__class__ == other.__class__
def __iter__(self):
yield from ()
Nothing = _Nothing()
| {
"content_hash": "5ea52d62dbe8ba580cb7cd51bdb19792",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 82,
"avg_line_length": 18.871559633027523,
"alnum_prop": 0.49586776859504134,
"repo_name": "fsarradin/pythonz",
"id": "44d844d62f0144f55806a2daa8b597a93ed167e8",
"size": "2057",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pythonz/maybe.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "2873"
}
],
"symlink_target": ""
} |
import datetime
from decimal import Decimal
from django.db import models
from django.utils.translation import ugettext_lazy as _
from budget.categories.models import Category, StandardMetadata, ActiveManager
TRANSACTION_TYPES = (
('expense', _('Expense')),
('income', _('Income')),
)
class TransactionManager(ActiveManager):
def get_latest(self, limit=10):
return self.get_query_set().order_by('-date', '-created')[0:limit]
class TransactionExpenseManager(TransactionManager):
def get_query_set(self):
return super(TransactionExpenseManager, self).get_query_set().filter(transaction_type='expense')
class TransactionIncomeManager(TransactionManager):
def get_query_set(self):
return super(TransactionIncomeManager, self).get_query_set().filter(transaction_type='income')
class Transaction(StandardMetadata):
"""
Represents incomes/expenses for the party doing the budgeting.
Transactions are not tied to individual budgets because this allows
different budgets to applied (like a filter) to a set of transactions.
It also allows for budgets to change through time without altering the
actual incoming/outgoing funds.
"""
transaction_type = models.CharField(_('Transaction type'), max_length=32, choices=TRANSACTION_TYPES, default='expense', db_index=True)
notes = models.CharField(_('Notes'), max_length=255, blank=True)
category = models.ForeignKey(Category, verbose_name=_('Category'))
amount = models.DecimalField(_('Amount'), max_digits=11, decimal_places=2)
date = models.DateField(_('Date'), default=datetime.date.today, db_index=True)
objects = models.Manager()
active = ActiveManager()
expenses = TransactionExpenseManager()
incomes = TransactionIncomeManager()
def __unicode__(self):
return u"%s (%s) - %s" % (self.notes, self.get_transaction_type_display(), self.amount)
class Meta:
verbose_name = _('Transaction')
verbose_name_plural = _('Transactions')
| {
"content_hash": "19690df8c7dac758f5f5e97fcee0b7b5",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 138,
"avg_line_length": 36.375,
"alnum_prop": 0.708885616102111,
"repo_name": "toastdriven/django-budget",
"id": "64700d19452a3dd4b83317ae7eba4aee1ed06e47",
"size": "2037",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "budget/transactions/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "77611"
},
{
"name": "Python",
"bytes": "44920"
}
],
"symlink_target": ""
} |
"""Responible for launching the server process."""
import subprocess, sys, os
shutdown_requested = False
while not shutdown_requested:
server_process = subprocess.Popen([sys.executable, os.path.join(os.getcwd(), "start_server.py")])
out, errors = server_process.communicate()
print(server_process.returncode, "return code", out, errors)
shutdown_requested = server_process.returncode == 0
| {
"content_hash": "1940b08fcd50fa6169ed236d78cc8204",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 101,
"avg_line_length": 40.7,
"alnum_prop": 0.7346437346437347,
"repo_name": "marky1991/Legend-of-Wumpus",
"id": "5cce6958c97d05936a372ef10cc8b8c7a9b292af",
"size": "407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wumpus/server_launcher.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "80388"
}
],
"symlink_target": ""
} |
import boto.ec2
import boto.ec2.elb
if __name__ == '__main__':
ec2_conn = boto.ec2.connection.EC2Connection()
instances = {}
for r in ec2_conn.get_all_instances():
for i in r.instances:
instances[i.id] = i
elb_conn = boto.ec2.elb.connect_to_region('us-east-1')
lb = elb_conn.get_all_load_balancers(['bannerstalker'])[0]
for i in lb.instances:
print instances[i.id].public_dns_name
| {
"content_hash": "5892b51e4e408e9e15a7d95bbe8f01b2",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 62,
"avg_line_length": 31.142857142857142,
"alnum_prop": 0.6192660550458715,
"repo_name": "nejstastnejsistene/bannerstalker-yesod",
"id": "e694ffa9d2ed6bd129121b1239fbacc46cf574dd",
"size": "459",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deploy/list-instances.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "146970"
},
{
"name": "Haskell",
"bytes": "79842"
},
{
"name": "Python",
"bytes": "892"
},
{
"name": "Shell",
"bytes": "1228"
}
],
"symlink_target": ""
} |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['RelativeDifference'] , ['PolyTrend'] , ['Seasonal_WeekOfYear'] , ['LSTM'] ); | {
"content_hash": "a4379a45f6e351891941c0f06813c9f0",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 99,
"avg_line_length": 43,
"alnum_prop": 0.7325581395348837,
"repo_name": "antoinecarme/pyaf",
"id": "c9ce924c6ae30d0f29ba1203b53b24dbec712bed",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/model_control/detailed/transf_RelativeDifference/model_control_one_enabled_RelativeDifference_PolyTrend_Seasonal_WeekOfYear_LSTM.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Makefile",
"bytes": "6773299"
},
{
"name": "Procfile",
"bytes": "24"
},
{
"name": "Python",
"bytes": "54209093"
},
{
"name": "R",
"bytes": "807"
},
{
"name": "Shell",
"bytes": "3619"
}
],
"symlink_target": ""
} |
import pysam
import sys
import csv
import os
import argparse
from quicksect import IntervalNode
from random import randint, seed
def getOverlap(a, b):
return max(0, min(a[1], b[1]) - max(a[0], b[0]))
def is_junction(read):
for c in read.cigartuples:
if c[0]==3:
return True
return False
#------
def find(start, end, tree):
"Returns a list with the overlapping intervals"
out = []
tree.intersect( start, end, lambda x: out.append(x) )
return [ (x.start, x.end) for x in out ]
'''
tree = IntervalNode( 5, 20 )
overlap = find(27, 28 , tree)
if overlap==[]:
print "----"
'''
ap = argparse.ArgumentParser()
ap.add_argument('bam', help='sorted bam file')
ap.add_argument('outPrefix', help='file to save number of reads per genome category')
args = ap.parse_args()
print os.path.dirname(os.path.realpath(__file__))
chr_list=[]
for i in range(1,23):
chr_list.append(str(i))
chr_list.append('X')
chr_list.append('Y')
repeat_file=os.path.dirname(os.path.realpath(__file__))+'/annotations/human/bedPrepared/hg19_rmsk_TE_prepared_noCDS.bed'
base=os.path.basename(args.bam)
prefix=os.path.splitext(base)[0]
#DATA STRUCTURE
tree_repeat={}
for chr in chr_list:
tree_repeat[chr]=IntervalNode(0,0)
print "Load repeat annotations from ",repeat_file
dictClass={}
dictFamily={}
dictGene={}
dictClassCount={}
dictFamilyCount={}
dictGeneCount={}
class_list=[]
family_list=[]
#1,AluSp,Alu,SINE,16777161,16777470
k=0
with open(repeat_file,'r') as f:
reader=csv.reader(f)
for line in reader:
chr=line[0]
if chr in chr_list:
Class=line[3]
Family=line[3]+"____"+line[2]
Gene=line[2]+"____"+line[3]+"____"+line[1]
x=int(line[4])
y=int(line[5])
tree_repeat[chr]=tree_repeat[chr].insert( x, y )
dictClass[(x,y,chr)]=Class
dictFamily[(x,y,chr)]=Family
dictGene[x,y,chr]=Gene
dictClassCount[Class]=[0]
dictFamilyCount[Family]=[0]
dictGeneCount[Gene]=[0]
k+=1
if k%100000==0:
print k, "repeat elements were loaded "
#
#======================================================================
#BAM
kOverlapClass=0
kOverlapFamily=0
kOverlapGene=0
print "Open bam file",args.bam
bamfile = pysam.Samfile(args.bam, "rb")
for chr in chr_list:
print "Process chr",chr
for read in bamfile.fetch(chr):
readName=read.query_name
if read.mapq==50 and not is_junction(read):
#feature=whichFeature(read,chr)
#outFile[chr].write( readName+','+chr + ',' + feature + '\n' )
find_list_repeat=find(read.reference_start, read.reference_end , tree_repeat[chr])
if len(find_list_repeat)>1:
overlap_list=[]
overlap_list[:]=[]
for f in find_list_repeat:
overlap=getOverlap((read.reference_start,read.reference_end),f)
if overlap==len(read.query_sequence):
overlap_list.append(overlap)
if len(overlap_list)>1:
print find_list_repeat
classT=[]
familyT=[]
for f in find_list_repeat:
classT.append(dictClass[((f[0],f[1],chr))])
familyT.append(dictFamily[((f[0],f[1],chr))])
print "overlapping-elements",dictGene[((f[0],f[1],chr))]
classT=set(classT)
familyT=set(familyT)
kOverlapGene+=1
if (len(classT)==1):
print classT
#dictClassCount[classT[0]][0]+=1
else:
kOverlapClass+=1
if (len(familyT)==1):
print familyT
#dictClassCount[familyT[0]][0]+=1
else:
kOverlapFamily+=1
if len(find_list_repeat)!=0:
for f in find_list_repeat:
overlap=getOverlap((read.reference_start,read.reference_end),f)
if overlap==len(read.query_sequence):
#print overlap
#print read
#print find_list_repeat
Class=dictClass[((f[0],f[1],chr))]
Family=dictFamily[((f[0],f[1],chr))]
Gene=dictGene[((f[0],f[1],chr))]
#Class
dictClassCount[Class][0]+=1
#Family
dictFamilyCount[Family][0]+=1
#Gene
dictGeneCount[Gene][0]+=1
#Class
class_names=['sample']
class_counts=[prefix]
for key,val in dictClassCount.items():
class_names.append(key)
class_counts.append(val[0])
c = csv.writer(open(args.outPrefix+"repeatClass.csv", "w"))
c.writerow(class_names)
c.writerow(class_counts)
#Family
family_names=['sample']
family_counts=[prefix]
for key,val in dictFamilyCount.items():
family_names.append(key)
family_counts.append(val[0])
c = csv.writer(open(args.outPrefix+"repeatFamily.csv", "w"))
c.writerow(family_names)
c.writerow(family_counts)
#Gene
gene_names=['sample']
gene_counts=[prefix]
gene_names=['sample']
gene_counts=[prefix]
for key,val in dictGeneCount.items():
gene_names.append(key)
gene_counts.append(val[0])
c = csv.writer(open(args.outPrefix+"repeatGene.csv", "w"))
c.writerow(gene_names)
c.writerow(gene_counts)
print 'kOverlapClass', 'kOverlapFamily','kOverlapGene'
print kOverlapClass, kOverlapFamily,kOverlapGene
print "DONE!"
| {
"content_hash": "08001d2a020c21abc2327abae120dedc",
"timestamp": "",
"source": "github",
"line_count": 300,
"max_line_length": 120,
"avg_line_length": 20.936666666666667,
"alnum_prop": 0.503900652762299,
"repo_name": "smangul1/rprofile",
"id": "de27e932eb0981e683b2b4e910db612f6e275501",
"size": "6281",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rprofile.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "12150"
}
],
"symlink_target": ""
} |
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Commodity(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
value = db.Column(db.Float)
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return '<Commodity({}, {})>'.format(self.name, self.value)
class LastCheck(db.Model):
id = db.Column(db.Integer, primary_key=True)
last = db.Column(db.DateTime)
def __init__(self, last):
self.last = last
def __repr__(self):
return '<LastCheck({})>'.format(str(self.last))
| {
"content_hash": "a12f34d36a2b10509fd5d4ae2fe3d9d1",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 66,
"avg_line_length": 21.862068965517242,
"alnum_prop": 0.6025236593059937,
"repo_name": "ThaWeatherman/spot_price",
"id": "e1486a000289133ac41e6d4b6ec684c9adc7073b",
"size": "634",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spot/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "151"
},
{
"name": "HTML",
"bytes": "777"
},
{
"name": "Python",
"bytes": "4640"
}
],
"symlink_target": ""
} |
import contextlib
import os
import tempfile
import unittest
import torch
from torchvision.utils import save_image
from densepose.data.image_list_dataset import ImageListDataset
from densepose.data.transform import ImageResizeTransform
@contextlib.contextmanager
def temp_image(height, width):
random_image = torch.rand(height, width)
with tempfile.NamedTemporaryFile(suffix=".jpg") as f:
f.close()
save_image(random_image, f.name)
yield f.name
os.unlink(f.name)
class TestImageListDataset(unittest.TestCase):
def test_image_list_dataset(self):
height, width = 720, 1280
with temp_image(height, width) as image_fpath:
image_list = [image_fpath]
category_list = [None]
dataset = ImageListDataset(image_list, category_list)
self.assertEqual(len(dataset), 1)
data1, categories1 = dataset[0]["images"], dataset[0]["categories"]
self.assertEqual(data1.shape, torch.Size((1, 3, height, width)))
self.assertEqual(data1.dtype, torch.float32)
self.assertIsNone(categories1[0])
def test_image_list_dataset_with_transform(self):
height, width = 720, 1280
with temp_image(height, width) as image_fpath:
image_list = [image_fpath]
category_list = [None]
transform = ImageResizeTransform()
dataset = ImageListDataset(image_list, category_list, transform)
self.assertEqual(len(dataset), 1)
data1, categories1 = dataset[0]["images"], dataset[0]["categories"]
self.assertEqual(data1.shape, torch.Size((1, 3, 749, 1333)))
self.assertEqual(data1.dtype, torch.float32)
self.assertIsNone(categories1[0])
| {
"content_hash": "9bf3b9b73973098828ae40c223a90853",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 79,
"avg_line_length": 38.43478260869565,
"alnum_prop": 0.6555429864253394,
"repo_name": "facebookresearch/detectron2",
"id": "7932602448b49b9be4fcea9645fe7a9c4d53c00e",
"size": "1820",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "projects/DensePose/tests/test_image_list_dataset.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "79417"
},
{
"name": "CMake",
"bytes": "616"
},
{
"name": "Cuda",
"bytes": "112955"
},
{
"name": "Dockerfile",
"bytes": "3209"
},
{
"name": "Python",
"bytes": "3261609"
},
{
"name": "Shell",
"bytes": "14448"
}
],
"symlink_target": ""
} |
from ctypes import *
import ctypes
import struct, os, threading, platform, atexit, inspect
from acq4.util.clibrary import *
from MultiClampTelegraph import *
from acq4.util.debug import *
DEBUG=False ## Global flag for debugging hangups
if DEBUG:
print "MultiClamp driver debug:", DEBUG
__all__ = ['MultiClamp', 'axlib', 'getAxlib', 'wmlib']
## Load windows definitions
windowsDefs = winDefs() #verbose=True)
# Load AxMultiClampMsg header
d = os.path.dirname(__file__)
axonDefs = CParser(
copyFrom=windowsDefs,
cache=os.path.join(d, 'AxMultiClampMsg.h.cache'),
macros={'EXPORT':''}, ## needed for reading version 2.2.0.x headers (64bit)
verbose=DEBUG
)
### the 700B software default location is C:/ProgramFiles or ProgramFiles(x86)/Molecular Devices
### the 700A software default location seems to be C:/Axon
searchPaths = [
'C:\\Program Files\\Molecular Devices',
'C:\\Program Files (x86)\\Molecular Devices',
'C:\\Program Files\\Axon',
'C:\\Program Files (x86)\\Axon',
'C:\\Axon',
]
axlib = None
def getAxlib(libPath=None):
"""Return the handle to the axon library (CLibrary instance).
If libPath is specified, then it must give the location of the AxMultiClampMsg.dll
file that should be loaded. Otherwise, a predefined set of paths will be searched.
Note: if you want to specify the DLL file using libPath, then this function must
be called before MultiClamp.instance().
"""
global axlib
if axlib is None:
if libPath is None:
libPath = find_lib('AxMultiClampMsg.dll', paths=searchPaths)
if not os.path.isfile(libPath):
raise ValueError('MultiClamp DLL file "%s" does not exist' % libPath)
print "Using MultiClamp DLL at ", libPath
axlib = CLibrary(windll.LoadLibrary(libPath), axonDefs, prefix='MCCMSG_')
initializeGlobals()
return axlib
class MultiClampChannel:
"""Class used to run MultiClamp commander functions for a specific channel.
Instances of this class are created via MultiClamp.getChannel"""
def __init__(self, mc, desc, debug=DEBUG):
self.debug = debug
if debug:
print "Creating MultiClampChannel"
self.mc = mc
self.desc = desc
self.state = None
self.callback = None
self.lock = threading.RLock(verbose=debug)
## handle for axon mccmsg library
self.axonDesc = {
'pszSerialNum': desc['sn'],
'uModel': desc['model'],
'uCOMPortID': desc['com'],
'uDeviceID': desc['dev'],
'uChannelID': desc['chan']
}
def setCallback(self, cb):
if self.debug:
print "MCChannel.setCallback called. callback:", cb
with self.lock:
if self.debug:
print " lock acquired (setCallback)"
self.callback = cb
def getState(self):
if self.debug:
print "MCChannel.getState called. caller:", inspect.getouterframes(inspect.currentframe())[1][3]
with self.lock:
return self.state
def getMode(self):
if self.debug:
print "MCChannel.getMode called."
with self.lock:
return self.state['mode']
def updateState(self, state):
"""Called by MultiClamp when changes have occurred in MCC."""
if self.debug:
print "MCChannel.updateState called."
with self.lock:
self.state = state
cb = self.callback
if cb is not None:
if self.debug:
print " calling callback:", cb
cb(state)
def getParam(self, param):
if self.debug:
print "MCChannel.getParam called. param:", param
self.select()
fn = 'Get' + param
v = self.mc.call(fn)[1]
## perform return value mapping for a few specific functions
if fn in INV_NAME_MAPS:
if v not in INV_NAME_MAPS[fn]:
raise Exception("Return from %s was %s; expected one of %s." % (fn, v, INV_NAME_MAPS[fn].keys()))
v = INV_NAME_MAPS[fn][v]
## Silly workaround--MC700A likes to tell us that secondary signal gain is 0
if fn == 'GetSecondarySignalGain' and self.desc['model'] == axlib.HW_TYPE_MC700A:
return 1.0
return v
def setParam(self, param, value):
if self.debug:
print "MCChannel.setParam called. param: %s value: %s" % (str(param), str(value))
self.select()
fn = "Set" + param
## Perform value mapping for a few functions (SetMode, SetPrimarySignal, SetSecondarySignal)
if fn in NAME_MAPS:
if value not in NAME_MAPS[fn]:
raise Exception("Argument to %s must be one of %s" % (fn, NAME_MAPS[fn].keys()))
value = NAME_MAPS[fn][value]
#print fn, value
self.mc.call(fn, value)
def getParams(self, params):
"""Reads multiple parameters from multiclamp.
Arguments:
chan -- Use the multiclamp device associated with this channel
params -- List of parameters to request.
Each parameter "SomeValue" must have a corresponding
function "getSomeValue" in AxMultiClampMsg.h
"""
res = {}
for p in params:
res[p] = self.getParam(p)
return res
def setParams(self, params):
"""Sets multiple parameters on multiclamp.
Arguments:
chan -- Use the multiclamp device associated with this channel
params -- Dict of parameters to set.
"""
res = {}
for p in params:
#print "Setting", p, params[p]
try:
self.setParam(p, params[p])
res[p] = True
except:
printExc("Error while setting parameter %s=%s" % (p, str(params[p])))
res[p] = False
return res
def setMode(self, mode):
return self.setParam('Mode', mode)
def setSignal(self, signal, primary):
"""Set the signal of a MC primary/secondary channel by name.
Use this function instead of setParam('PrimarySignal', ...). Bugs in the axon driver
prevent that call from working correctly."""
if self.debug:
print "MCChannel.setSignal called."
model = self.desc['model']
priMap = ['PRI', 'SEC']
mode = self.getMode()
if mode == 'I=0':
mode = 'IC'
sigMap = SIGNAL_MAP[model][mode][priMap[primary]]
if signal not in sigMap:
raise Exception("Signal name '%s' not found. (Using map for model=%s, mode=%s, pri=%s)" % (signal, model, mode, priMap[primary]))
sig = 'SIGNAL_' + sigMap[signal]
if primary == 0:
self.setParam('PrimarySignal', sig)
elif primary == 1:
self.setParam('SecondarySignal', sig)
def getPrimarySignalInfo(self):
return self.getSignalInfo(0)
def getSecondarySignalInfo(self):
return self.getSignalInfo(1)
def setPrimarySignal(self, signal):
return self.setSignal(signal, 0)
def setSecondarySignal(self, signal):
return self.setSignal(signal, 1)
def listSignals(self, mode=None):
"""Return two lists of signal names that may be used for this channel:
#( [primary signals], [secondary signals] )
#If mode is omitted, then the current mode of the channel is used."""
if mode is None:
mode = self.getMode()
if mode == 'I=0':
mode = 'IC'
model = self.desc['model']
return (SIGNAL_MAP[model][mode]['PRI'].keys(), SIGNAL_MAP[model][mode]['SEC'].keys())
def select(self):
"""Select this channel for parameter get/set"""
if self.debug:
print "MCChannel.select called."
self.mc.call('SelectMultiClamp', **self.axonDesc)
class MultiClamp:
"""Class used to interface with remote multiclamp server.
Only one instance of this class should be created.
Example usage:
mc = MultiClamp.instance()
devs = mc.listDevices()
chan0 = mc.getChannel(devs[0])
chan0.setMode('IC')
signal, gain, units = chan0.getSignalInfo()
"""
INSTANCE = None
@classmethod
def instance(cls):
if cls.INSTANCE is None:
# make sure dll has been initialized first
getAxlib()
cls.INSTANCE = cls()
return cls.INSTANCE
def __init__(self, debug=DEBUG):
self.debug = debug
if debug:
print "Creating MultiClamp driver object"
self.telegraph = None
if MultiClamp.INSTANCE is not None:
raise Exception("Already created MultiClamp driver object; use MultiClamp.INSTANCE")
self.handle = None
self.lock = threading.RLock(verbose=debug)
self.channels = {}
self.chanDesc = {}
self.connect()
self.telegraph = MultiClampTelegraph(self.chanDesc, self.telegraphMessage)
MultiClamp.INSTANCE = self
atexit.register(self.quit)
def quit(self):
## do other things to shut down driver?
self.disconnect()
if self.telegraph is not None:
self.telegraph.quit()
MultiClamp.INSTANCE = None
def getChannel(self, channel, callback=None):
"""Return a MultiClampChannel object for the specified device/channel. The
channel argument should be the same as a single item from listDevices().
The callback will be called when certain (but not any) changes are made
to the multiclamp state."""
if self.debug:
print "MCDriver.getChannel called. Channel: %s callback: %s" %(str(channel), str(callback))
caller = inspect.getouterframes(inspect.currentframe())[1][3]
#caller = "nevermind"
print " caller:", caller
if channel not in self.channels:
raise Exception("No channel with description '%s'. Options are %s" % (str(channel), str(self.listChannels())))
ch = self.channels[channel]
if callback is not None:
if self.debug:
print " setting callback:", str(callback)
ch.setCallback(callback)
return ch
def listChannels(self):
"""Return a list of strings used to identify all devices/channels.
These strings should be used to identify the same channel across invocations."""
if self.debug:
print "MCDriver.listChannels called."
return self.channels.keys()
def connect(self):
"""(re)create connection to commander."""
#print "connect to commander.."
if self.debug:
print "MCDriver.connect called."
with self.lock:
if self.handle is not None:
#print " disconnect first"
self.disconnect()
(self.handle, err) = axlib.CreateObject()
if self.handle == 0:
self.handle = None
self.raiseError("Error while initializing Axon library:", err)
self.findDevices()
#print " now connected:", self.chanDesc
def disconnect(self):
"""Destroy connection to commander"""
if self.debug:
print "MCDriver.disconnect called."
with self.lock:
if self.handle is not None and axlib is not None:
axlib.DestroyObject(self.handle)
self.handle = None
def findDevices(self):
if self.debug:
print "MCDriver.findDevices called."
while True:
ch = self.findMultiClamp()
if ch is None:
break
else:
## Make sure the order of keys is well defined; string must be identical every time.
ch1 = ch.copy()
ch1['model'] = MODELS[ch1['model']]
if ch1['model'] == 'MC700A':
strDesc = ",".join("%s:%s" % (k, ch1[k]) for k in ['model', 'com', 'dev', 'chan'])
elif ch1['model'] == 'MC700B':
strDesc = ",".join("%s:%s" % (k, ch1[k]) for k in ['model', 'sn', 'chan'])
if strDesc not in self.channels:
self.channels[strDesc] = MultiClampChannel(self, ch)
self.chanDesc[strDesc] = ch
def findMultiClamp(self):
if self.debug:
print "MCDriver.findMultiClamp called."
if len(self.channels) == 0:
fn = 'FindFirstMultiClamp'
else:
fn = 'FindNextMultiClamp'
try:
serial = create_string_buffer('\0'*16)
ret = self.call(fn, pszSerialNum=serial, uBufSize=16)
except:
if sys.exc_info()[1][0] == 6000: ## We have reached the end of the device list
return None
raise
desc = {'sn': ret['pszSerialNum'], 'model': ret['puModel'], 'com': ret['puCOMPortID'], 'dev': ret['puDeviceID'], 'chan': ret['puChannelID']}
return desc
def call(self, fName, *args, **kargs): ## call is only used for functions that return a bool error status and have a pnError argument passed by reference.
if self.debug:
print "MC_driver.call called. fName:", fName
with self.lock:
ret = axlib('functions', fName)(self.handle, *args, **kargs)
if ret() == 0:
funcStr = "%s(%s)" % (fName, ', '.join(map(str, args) + ["%s=%s" % (k, str(kargs[k])) for k in kargs]))
self.raiseError("Error while running function %s\n Error:" % funcStr, ret['pnError'])
if self.debug:
print " %s returned." % fName
return ret
def raiseError(self, msg, err):
if self.debug:
print "MCDriver.raiseError called:"
print " ", msg
raise Exception(err, msg + " " + self.errString(err))
def errString(self, err):
try:
return axlib.BuildErrorText(self.handle, err, create_string_buffer('\0'*256), 256)['sTxtBuf']
except:
sys.excepthook(*sys.exc_info())
return "<could not generate error message>"
def telegraphMessage(self, msg, chID=None, state=None):
if self.debug:
print "MCDriver.telegraphMessage called. msg:", msg
if msg == 'update':
self.channels[chID].updateState(state)
elif msg == 'reconnect':
self.connect()
def initializeGlobals():
global MODELS, MODE_LIST, MODE_LIST_INV, PRI_OUT_MODE_LIST, SEC_OUT_MODE_LIST
global PRI_OUT_MODE_LIST_INV, SEC_OUT_MODE_LIST_INV, NAME_MAPS, INV_NAME_MAPS
global SIGNAL_MAP
## Crapton of stuff to remember that is not provided by header files
def invertDict(d):
return dict([(x[1], x[0]) for x in d.items()])
MODELS = {
axlib.HW_TYPE_MC700A: 'MC700A',
axlib.HW_TYPE_MC700B: 'MC700B'
}
MODE_LIST = {
"VC": axlib.MODE_VCLAMP,
"IC": axlib.MODE_ICLAMP,
"I=0": axlib.MODE_ICLAMPZERO,
}
MODE_LIST_INV = invertDict(MODE_LIST)
## Extract all signal names from library
PRI_OUT_MODE_LIST = {}
SEC_OUT_MODE_LIST = {}
for k in axlib['values']:
if k[:18] == 'MCCMSG_PRI_SIGNAL_':
PRI_OUT_MODE_LIST[k[11:]] = axlib('values', k)
elif k[:18] == 'MCCMSG_SEC_SIGNAL_':
SEC_OUT_MODE_LIST[k[11:]] = axlib('values', k)
PRI_OUT_MODE_LIST_INV = invertDict(PRI_OUT_MODE_LIST)
SEC_OUT_MODE_LIST_INV = invertDict(SEC_OUT_MODE_LIST)
NAME_MAPS = {
'SetMode': MODE_LIST,
'SetPrimarySignal': PRI_OUT_MODE_LIST,
'SetSecondarySignal': SEC_OUT_MODE_LIST
}
INV_NAME_MAPS = {
'GetMode': MODE_LIST_INV,
'GetPrimarySignal': PRI_OUT_MODE_LIST_INV,
'GetSecondarySignal': SEC_OUT_MODE_LIST_INV
}
## Build a map for connecting signal strings from telegraph headers to signal values from axon headers.
## Note: Completely retarded.
SIGNAL_MAP = {
axlib.HW_TYPE_MC700A: {
'VC': {
'PRI': {
"Membrane Potential": "VC_MEMBPOTENTIAL",
"Membrane Current": "VC_MEMBCURRENT",
"Pipette Potential": "VC_PIPPOTENTIAL",
"100 x AC Pipette Potential": "VC_100XACMEMBPOTENTIAL",
"Bath Potential": "VC_AUXILIARY1"
},
'SEC': {
"Membrane plus Offset Potential": "VC_MEMBPOTENTIAL",
"Membrane Current": "VC_MEMBCURRENT",
"Pipette Potential": "VC_PIPPOTENTIAL",
"100 x AC Pipette Potential": "VC_100XACMEMBPOTENTIAL",
"Bath Potential": "VC_AUXILIARY1"
}
},
'IC': {
'PRI': { ## Driver bug? Primary IC signals use VC values. Bah.
"Command Current": "VC_MEMBPOTENTIAL",
"Membrane Current": "VC_MEMBCURRENT",
"Membrane Potential": "VC_PIPPOTENTIAL",
"100 x AC Membrane Potential": "VC_100XACMEMBPOTENTIAL",
"Bath Potential": "VC_AUXILIARY1"
#"Command Current": "IC_CMDCURRENT",
#"Membrane Current": "IC_MEMBCURRENT",
#"Membrane Potential": "IC_MEMBPOTENTIAL",
#"100 x AC Membrane Potential": "IC_100XACMEMBPOTENTIAL",
#"Bath Potential": "IC_AUXILIARY1"
},
'SEC': {
"Command Current": "IC_CMDCURRENT",
"Membrane Current": "IC_MEMBCURRENT",
"Membrane plus Offset Potential": "IC_MEMBPOTENTIAL",
"100 x AC Membrane Potential": "IC_100XACMEMBPOTENTIAL",
"Bath Potential": "IC_AUXILIARY1"
}
}
},
axlib.HW_TYPE_MC700B: {
'VC': {
'PRI': {
"Membrane Current": "VC_MEMBCURRENT",
"Membrane Potential": "VC_MEMBPOTENTIAL",
"Pipette Potential": "VC_PIPPOTENTIAL",
"100x AC Membrane Potential": "VC_100XACMEMBPOTENTIAL",
"External Command Potential": "VC_EXTCMDPOTENTIAL",
"Auxiliaryl": "VC_AUXILIARY1",
"Auxiliary2": "VC_AUXILIARY2",
},
'SEC': {
"Membrane Current":"VC_MEMBCURRENT" ,
"Membrane Potential": "VC_MEMBPOTENTIAL",
"Pipette Potential": "VC_PIPPOTENTIAL",
"100x AC Membrane Potential": "VC_100XACMEMBPOTENTIAL",
"External Command Potential": "VC_EXTCMDPOTENTIAL",
"Auxiliaryl": "VC_AUXILIARY1",
"Auxiliary2": "VC_AUXILIARY2",
}
},
'IC': {
'PRI': {
"Membrane Potential": "IC_MEMBPOTENTIAL",
"Membrane Current": "IC_MEMBCURRENT",
"Command Current": "IC_CMDCURRENT",
"100x AC Membrane Potential": "IC_100XACMEMBPOTENTIAL",
"External Command Current": "IC_EXTCMDCURRENT",
"Auxiliary1": "IC_AUXILIARY1",
"Auxiliary2": "IC_AUXILIARY2",
},
'SEC': {
"Membrane Potential": "IC_MEMBPOTENTIAL",
"Membrane Current": "IC_MEMBCURRENT",
"Pipette Potential": "IC_PIPPOTENTIAL",
"100x AC Membrane Potential": "IC_100XACMEMBPOTENTIAL",
"External Command Current": "IC_EXTCMDCURRENT",
"Auxiliary1": "IC_AUXILIARY1",
"Auxiliary2": "IC_AUXILIARY2",
}
}
}
}
| {
"content_hash": "f9edd54f16c439e279c3f5ffc86a1740",
"timestamp": "",
"source": "github",
"line_count": 550,
"max_line_length": 160,
"avg_line_length": 36.97818181818182,
"alnum_prop": 0.5498082407316354,
"repo_name": "mgraupe/acq4",
"id": "b680657fcaf959d52f898912a217cb1dcdd6a3c5",
"size": "20362",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "acq4/drivers/MultiClamp/multiclamp.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AMPL",
"bytes": "3037"
},
{
"name": "Batchfile",
"bytes": "247"
},
{
"name": "C",
"bytes": "757367"
},
{
"name": "C++",
"bytes": "1222891"
},
{
"name": "CSS",
"bytes": "716"
},
{
"name": "Inno Setup",
"bytes": "1606"
},
{
"name": "MATLAB",
"bytes": "1752"
},
{
"name": "Makefile",
"bytes": "30"
},
{
"name": "Processing",
"bytes": "13403"
},
{
"name": "Python",
"bytes": "6110588"
},
{
"name": "Shell",
"bytes": "70"
}
],
"symlink_target": ""
} |
class BaseCartModifier(object):
"""
Price modifiers are the cart's counterpart to backends.
It allows to implement Taxes and rebates / bulk prices in an elegant manner:
Everytime the cart is refreshed (via it's update() method), the cart will
call all subclasses of this registered with their full path in the
settings.SHOP_CART_MODIFIERS setting.
"""
def process_cart_item(self, cart_item):
"""
This will be called for every line item in the Cart:
Line items typically contain: product, unit_price, quantity...
Subtotal for every line (unit price * quantity) is already computed, but
the line total is 0, and is expected to be calculated in the Cart's
update() method
"""
return self.add_extra_cart_item_price_field(cart_item)
def process_cart(self, cart):
"""
This will be called once per Cart, after every line item was treated
The subtotal for the cart is already known, but the Total is 0.
Like for the line items, total is expected to be calculated in the cart's
update() method.
Line items should be complete by now, so all of their fields are accessible
"""
return self.add_extra_cart_price_field(cart)
def add_extra_cart_item_price_field(self, cart_item):
"""
Add an extra price field on cart_item.extra_price_fields:
This allows to modify the price easily, simply add a
{'Label':Decimal(difference)} entry to it.
A tax modifier would do something like this:
>>> cart_item.extra_price_fields.update({'taxes': Decimal(9)})
And a rebate modifier would do something along the lines of:
>>> cart_item.extra_price_fields.update({'rebate': Decimal(-9)})
More examples can be found in shop.cart.modifiers.*
"""
return cart_item # Does nothing by default
def add_extra_cart_price_field(self, cart):
"""
Add a field on cart.extra_price_fields:
In a similar fashion, this allows to easily add price modifications to
the general Cart object,
>>> cart.extra_price_fields.update({'Taxes total': 19.00})
"""
return cart | {
"content_hash": "ed0de23a68a9852e51808114930682fa",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 83,
"avg_line_length": 39.083333333333336,
"alnum_prop": 0.6200426439232409,
"repo_name": "eduardostalinho/django-shop",
"id": "4d59815bb4745448505e5bcab38a2a40bce5b668",
"size": "2370",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "shop/cart/cart_modifiers_base.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
"""Contains LossScale classes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.distribute import distribution_strategy_context
from tensorflow.python.framework import ops
from tensorflow.python.framework import smart_cond
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.training import optimizer
from tensorflow.python.training.experimental import loss_scale as loss_scale_module
from tensorflow.python.util.tf_export import tf_export
@tf_export(v1=['train.experimental.MixedPrecisionLossScaleOptimizer'])
class MixedPrecisionLossScaleOptimizer(optimizer.Optimizer):
"""An optimizer that applies loss scaling.
Loss scaling is a process that multiplies the loss by a multiplier called the
loss scale, and divides each gradient by the same multiplier. The pseudocode
for this process is:
```
loss = ...
loss *= loss_scale
grads = gradients(loss, vars)
grads /= loss_scale
```
Mathematically, loss scaling has no effect, but can help avoid numerical
underflow in intermediate gradients when float16 tensors are used for mixed
precision training. By multiplying the loss, each intermediate gradient will
have the same multiplier applied.
The loss scale can either be a fixed constant, chosen by the user, or be
dynamically determined. Dynamically determining the loss scale is convenient
as a loss scale does not have to be explicitly chosen. However it reduces
performance.
This optimizer wraps another optimizer and applies loss scaling to it via a
`LossScale`. Loss scaling is applied whenever gradients are
computed, such as through `minimize()`.
"""
def __init__(self, opt, loss_scale):
if not isinstance(opt, optimizer.Optimizer):
raise ValueError('"opt" must be an instance of Optimizer, but got: %s' %
type(opt))
self._optimizer = opt
use_locking = opt._use_locking # pylint: disable=protected-access
name = opt.get_name()
super(MixedPrecisionLossScaleOptimizer, self).__init__(use_locking, name)
self._loss_scale = loss_scale_module.get(loss_scale)
if self._loss_scale is None:
raise ValueError('loss_scale cannot be None')
self._track_trackable(self._optimizer, 'base_optimizer')
self._track_trackable(self._loss_scale, 'loss_scale')
def _doing_dynamic_loss_scaling(self):
"""Check if `_loss_scale` dynamically manages the loss scale."""
return isinstance(self._loss_scale, loss_scale_module.DynamicLossScale)
def compute_gradients(self,
loss,
var_list=None,
gate_gradients=optimizer.Optimizer.GATE_OP,
aggregation_method=None,
colocate_gradients_with_ops=False,
grad_loss=None):
"""Compute gradients of `loss` for the variables in `var_list`.
This adjusts the dynamic range of the gradient evaluation by scaling up
the `loss` value. The gradient values are then scaled back down by the
reciprocal of the loss scale. This is useful in reduced precision training
where small gradient values would otherwise underflow the representable
range.
Args:
loss: A Tensor containing the value to minimize or a callable taking no
arguments which returns the value to minimize. When eager execution is
enabled it must be a callable.
var_list: Optional list or tuple of `tf.Variable` to update to minimize
`loss`. Defaults to the list of variables collected in the graph under
the key `GraphKeys.TRAINABLE_VARIABLES`.
gate_gradients: How to gate the computation of gradients. Can be
`GATE_NONE`, `GATE_OP`, or `GATE_GRAPH`.
aggregation_method: Specifies the method used to combine gradient terms.
Valid values are defined in the class `AggregationMethod`.
colocate_gradients_with_ops: If True, try colocating gradients with the
corresponding op.
grad_loss: Optional. A `Tensor` holding the gradient computed for `loss`.
Returns:
A list of (gradient, variable) pairs. Variable is always present, but
gradient can be `None`.
"""
loss = self._scale_loss(loss)
grads_and_vars = self._optimizer.compute_gradients(
loss=loss,
var_list=var_list,
gate_gradients=gate_gradients,
aggregation_method=aggregation_method,
colocate_gradients_with_ops=colocate_gradients_with_ops,
grad_loss=grad_loss)
grads = [g for g, _ in grads_and_vars]
variables = [v for _, v in grads_and_vars]
unscaled_grads = self._unscale_grads(grads)
return list(zip(unscaled_grads, variables))
def _scale_loss(self, loss):
loss_scale = self._loss_scale()
if callable(loss):
def new_loss():
loss_val = loss()
return loss_val * math_ops.cast(loss_scale, loss_val.dtype)
return new_loss
else:
return loss * math_ops.cast(loss_scale, loss.dtype)
def _unscale_grads(self, grads):
loss_scale = self._loss_scale()
loss_scale_reciprocal = 1 / loss_scale
return [
None if g is None else self._scale_grad(g, loss_scale_reciprocal)
for g in grads
]
def _scale_grad(self, grad, loss_scale_reciprocal):
if isinstance(grad, ops.IndexedSlices):
grad_vals = grad.values * loss_scale_reciprocal
return ops.IndexedSlices(grad_vals, grad.indices, grad.dense_shape)
return grad * loss_scale_reciprocal
def apply_gradients(self, grads_and_vars, global_step=None, name=None):
"""Apply gradients to variables.
This is the second part of `minimize()`. It returns an `Operation` that
conditionally applies gradients if all gradient values are finite.
Otherwise no update is performed (nor is `global_step` incremented).
Args:
grads_and_vars: List of (gradient, variable) pairs as returned by
`compute_gradients()`.
global_step: Optional `Variable` to increment by one after the variables
have been updated.
name: Optional name for the returned operation. Default to the name
passed to the `Optimizer` constructor.
Returns:
An `Operation` that conditionally applies the specified gradients. If
`global_step` was not None, that operation also increments `global_step`.
Raises:
RuntimeError: If you should use `_distributed_apply()` instead.
"""
if distribution_strategy_context.in_cross_replica_context():
raise ValueError('apply_gradients() must be called in a replica context.')
if not self._doing_dynamic_loss_scaling():
return self._optimizer.apply_gradients(grads_and_vars, global_step, name)
replica_context = distribution_strategy_context.get_replica_context()
grads_and_vars = tuple(grads_and_vars)
# TODO(nluehr) cleanup GraphKeys.TRAIN_OP
return replica_context.merge_call(
self._distributed_apply, args=(grads_and_vars, global_step, name))
def _distributed_apply(self,
distribution,
grads_and_vars,
global_step=None,
name=None):
"""A version of `apply_gradients` for cross replica context.
When users are in a cross replica strategy, they must call this rather than
`apply_gradients()`.
Args:
distribution: a `DistributionStrategy` object.
grads_and_vars: List of (gradient, variable) pairs as returned by
`compute_gradients()` and then aggregated across replicas.
global_step: Optional (mirrored) `Variable` to increment by one after the
variables have been updated.
name: Optional name for the returned operation. Default to the name passed
to the `Optimizer` constructor.
Returns:
An `Operation` that applies the specified gradients across all
replicas. If `global_step` was not None, that operation also
increments `global_step`
"""
name = name if name is not None else self.get_name()
grads = [g for g, _ in grads_and_vars]
loss_scale_update_op, should_apply_grads = (self._loss_scale.update(grads))
def apply_fn():
return self._apply_gradients(distribution, grads_and_vars, global_step,
name + '-wrapped')
maybe_apply_op = smart_cond.smart_cond(should_apply_grads, apply_fn,
control_flow_ops.no_op)
return control_flow_ops.group(
maybe_apply_op, loss_scale_update_op, name=name)
def _apply_gradients(self, distribution, grads_and_vars, global_step, name):
"""Unconditionally apply gradients in cross replica context."""
update_ops = distribution.extended.call_for_each_replica(
self._optimizer.apply_gradients,
args=(grads_and_vars, global_step, name))
return distribution.group(update_ops)
def _apply_sparse(self, grad, var):
"""This function should never be called."""
raise RuntimeError('This function should never be called')
def _apply_dense(self, grad, var):
"""This function should never be called."""
raise RuntimeError('This function should never be called')
def _resource_apply_sparse(self, grad, handle, indices):
"""This function should never be called."""
raise RuntimeError('This function should never be called')
def _resource_apply_dense(self, grad, handle):
"""This function should never be called."""
raise RuntimeError('This function should never be called')
def variables(self):
"""Returns the variables of the Optimizer."""
return (self._optimizer.variables() +
list(self._loss_scale._weights.values())) # pylint: disable=protected-access
| {
"content_hash": "8ab4ab223f40379eab81ba5f8f3c1822",
"timestamp": "",
"source": "github",
"line_count": 236,
"max_line_length": 89,
"avg_line_length": 41.66949152542373,
"alnum_prop": 0.685784014643075,
"repo_name": "gunan/tensorflow",
"id": "c07c8cca60a2b0ce235d2838eb2fcb2a3a36c47d",
"size": "10523",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "tensorflow/python/training/experimental/loss_scale_optimizer.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "5003"
},
{
"name": "Batchfile",
"bytes": "45924"
},
{
"name": "C",
"bytes": "774953"
},
{
"name": "C#",
"bytes": "8562"
},
{
"name": "C++",
"bytes": "77908225"
},
{
"name": "CMake",
"bytes": "6500"
},
{
"name": "Dockerfile",
"bytes": "104215"
},
{
"name": "Go",
"bytes": "1841471"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "962443"
},
{
"name": "Jupyter Notebook",
"bytes": "556650"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "1479029"
},
{
"name": "Makefile",
"bytes": "58603"
},
{
"name": "Objective-C",
"bytes": "104667"
},
{
"name": "Objective-C++",
"bytes": "297830"
},
{
"name": "PHP",
"bytes": "23994"
},
{
"name": "Pascal",
"bytes": "3739"
},
{
"name": "Pawn",
"bytes": "17039"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "39476740"
},
{
"name": "RobotFramework",
"bytes": "891"
},
{
"name": "Roff",
"bytes": "2472"
},
{
"name": "Ruby",
"bytes": "7459"
},
{
"name": "Shell",
"bytes": "650007"
},
{
"name": "Smarty",
"bytes": "34649"
},
{
"name": "Swift",
"bytes": "62814"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
"""Test the Uonet+ Vulcan config flow."""
import json
from unittest import mock
from unittest.mock import patch
from vulcan import (
Account,
ExpiredTokenException,
InvalidPINException,
InvalidSymbolException,
InvalidTokenException,
UnauthorizedCertificateException,
)
from vulcan.model import Student
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.vulcan import config_flow, const, register
from homeassistant.components.vulcan.config_flow import ClientConnectionError, Keystore
from homeassistant.const import CONF_PIN, CONF_REGION, CONF_TOKEN
from tests.common import MockConfigEntry, load_fixture
fake_keystore = Keystore("", "", "", "", "")
fake_account = Account(
login_id=1,
user_login="example@example.com",
user_name="example@example.com",
rest_url="rest_url",
)
async def test_show_form(hass):
"""Test that the form is served with no input."""
flow = config_flow.VulcanFlowHandler()
flow.hass = hass
result = await flow.async_step_user(user_input=None)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
@mock.patch("homeassistant.components.vulcan.config_flow.Account.register")
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
async def test_config_flow_auth_success(
mock_keystore, mock_account, mock_student, hass
):
"""Test a successful config flow initialized by the user."""
mock_keystore.return_value = fake_keystore
mock_account.return_value = fake_account
mock_student.return_value = [
Student.load(load_fixture("fake_student_1.json", "vulcan"))
]
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] is None
with patch(
"homeassistant.components.vulcan.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
await hass.async_block_till_done()
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "Jan Kowalski"
assert len(mock_setup_entry.mock_calls) == 1
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
@mock.patch("homeassistant.components.vulcan.config_flow.Account.register")
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
async def test_config_flow_auth_success_with_multiple_students(
mock_keystore, mock_account, mock_student, hass
):
"""Test a successful config flow with multiple students."""
mock_keystore.return_value = fake_keystore
mock_account.return_value = fake_account
mock_student.return_value = [
Student.load(student)
for student in [load_fixture("fake_student_1.json", "vulcan")]
+ [load_fixture("fake_student_2.json", "vulcan")]
]
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "select_student"
assert result["errors"] == {}
with patch(
"homeassistant.components.vulcan.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"student": "0"},
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "Jan Kowalski"
assert len(mock_setup_entry.mock_calls) == 1
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
@mock.patch("homeassistant.components.vulcan.config_flow.Account.register")
async def test_config_flow_reauth_success(
mock_account, mock_keystore, mock_student, hass
):
"""Test a successful config flow reauth."""
mock_keystore.return_value = fake_keystore
mock_account.return_value = fake_account
mock_student.return_value = [
Student.load(load_fixture("fake_student_1.json", "vulcan"))
]
MockConfigEntry(
domain=const.DOMAIN,
unique_id="0",
data={"student_id": "0"},
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_REAUTH}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {}
with patch(
"homeassistant.components.vulcan.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert len(mock_setup_entry.mock_calls) == 1
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
@mock.patch("homeassistant.components.vulcan.config_flow.Account.register")
async def test_config_flow_reauth_without_matching_entries(
mock_account, mock_keystore, mock_student, hass
):
"""Test a aborted config flow reauth caused by leak of matching entries."""
mock_keystore.return_value = fake_keystore
mock_account.return_value = fake_account
mock_student.return_value = [
Student.load(load_fixture("fake_student_1.json", "vulcan"))
]
MockConfigEntry(
domain=const.DOMAIN,
unique_id="0",
data={"student_id": "1"},
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_REAUTH}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.ABORT
assert result["reason"] == "no_matching_entries"
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
@mock.patch("homeassistant.components.vulcan.config_flow.Account.register")
async def test_config_flow_reauth_with_errors(mock_account, mock_keystore, hass):
"""Test reauth config flow with errors."""
mock_keystore.return_value = fake_keystore
mock_account.return_value = fake_account
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_REAUTH}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {}
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=InvalidTokenException,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": "invalid_token"}
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=ExpiredTokenException,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": "expired_token"}
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=InvalidPINException,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": "invalid_pin"}
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=InvalidSymbolException,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": "invalid_symbol"}
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=ClientConnectionError,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": "cannot_connect"}
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=Exception,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": "unknown"}
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
@mock.patch("homeassistant.components.vulcan.config_flow.Account.register")
async def test_multiple_config_entries(mock_account, mock_keystore, mock_student, hass):
"""Test a successful config flow for multiple config entries."""
mock_keystore.return_value = fake_keystore
mock_account.return_value = fake_account
mock_student.return_value = [
Student.load(load_fixture("fake_student_1.json", "vulcan"))
]
MockConfigEntry(
domain=const.DOMAIN,
unique_id="123456",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan")),
).add_to_hass(hass)
await register.register(hass, "token", "region", "000000")
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "add_next_config_entry"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"use_saved_credentials": False},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] is None
with patch(
"homeassistant.components.vulcan.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "token", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "Jan Kowalski"
assert len(mock_setup_entry.mock_calls) == 2
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
async def test_multiple_config_entries_using_saved_credentials(mock_student, hass):
"""Test a successful config flow for multiple config entries using saved credentials."""
mock_student.return_value = [
Student.load(load_fixture("fake_student_1.json", "vulcan"))
]
MockConfigEntry(
domain=const.DOMAIN,
unique_id="123456",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan")),
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "add_next_config_entry"
assert result["errors"] == {}
with patch(
"homeassistant.components.vulcan.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"use_saved_credentials": True},
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "Jan Kowalski"
assert len(mock_setup_entry.mock_calls) == 2
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
async def test_multiple_config_entries_using_saved_credentials_2(mock_student, hass):
"""Test a successful config flow for multiple config entries using saved credentials (different situation)."""
mock_student.return_value = [
Student.load(load_fixture("fake_student_1.json", "vulcan"))
] + [Student.load(load_fixture("fake_student_2.json", "vulcan"))]
MockConfigEntry(
domain=const.DOMAIN,
unique_id="123456",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan")),
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "add_next_config_entry"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"use_saved_credentials": True},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "select_student"
assert result["errors"] == {}
with patch(
"homeassistant.components.vulcan.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"student": "0"},
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "Jan Kowalski"
assert len(mock_setup_entry.mock_calls) == 2
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
async def test_multiple_config_entries_using_saved_credentials_3(mock_student, hass):
"""Test a successful config flow for multiple config entries using saved credentials."""
mock_student.return_value = [
Student.load(load_fixture("fake_student_1.json", "vulcan"))
]
MockConfigEntry(
entry_id="456",
domain=const.DOMAIN,
unique_id="234567",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan"))
| {"student_id": "456"},
).add_to_hass(hass)
MockConfigEntry(
entry_id="123",
domain=const.DOMAIN,
unique_id="123456",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan")),
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "add_next_config_entry"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"use_saved_credentials": True},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "select_saved_credentials"
assert result["errors"] is None
with patch(
"homeassistant.components.vulcan.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"credentials": "123"},
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "Jan Kowalski"
assert len(mock_setup_entry.mock_calls) == 3
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
async def test_multiple_config_entries_using_saved_credentials_4(mock_student, hass):
"""Test a successful config flow for multiple config entries using saved credentials (different situation)."""
mock_student.return_value = [
Student.load(load_fixture("fake_student_1.json", "vulcan"))
] + [Student.load(load_fixture("fake_student_2.json", "vulcan"))]
MockConfigEntry(
entry_id="456",
domain=const.DOMAIN,
unique_id="234567",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan"))
| {"student_id": "456"},
).add_to_hass(hass)
MockConfigEntry(
entry_id="123",
domain=const.DOMAIN,
unique_id="123456",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan")),
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "add_next_config_entry"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"use_saved_credentials": True},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "select_saved_credentials"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"credentials": "123"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "select_student"
assert result["errors"] == {}
with patch(
"homeassistant.components.vulcan.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"student": "0"},
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "Jan Kowalski"
assert len(mock_setup_entry.mock_calls) == 3
async def test_multiple_config_entries_without_valid_saved_credentials(hass):
"""Test a unsuccessful config flow for multiple config entries without valid saved credentials."""
MockConfigEntry(
entry_id="456",
domain=const.DOMAIN,
unique_id="234567",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan"))
| {"student_id": "456"},
).add_to_hass(hass)
MockConfigEntry(
entry_id="123",
domain=const.DOMAIN,
unique_id="123456",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan")),
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "add_next_config_entry"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"use_saved_credentials": True},
)
with patch(
"homeassistant.components.vulcan.config_flow.Vulcan.get_students",
side_effect=UnauthorizedCertificateException,
):
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "select_saved_credentials"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"credentials": "123"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "expired_credentials"}
async def test_multiple_config_entries_using_saved_credentials_with_connections_issues(
hass,
):
"""Test a unsuccessful config flow for multiple config entries without valid saved credentials."""
MockConfigEntry(
entry_id="456",
domain=const.DOMAIN,
unique_id="234567",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan"))
| {"student_id": "456"},
).add_to_hass(hass)
MockConfigEntry(
entry_id="123",
domain=const.DOMAIN,
unique_id="123456",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan")),
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "add_next_config_entry"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"use_saved_credentials": True},
)
with patch(
"homeassistant.components.vulcan.config_flow.Vulcan.get_students",
side_effect=ClientConnectionError,
):
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "select_saved_credentials"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"credentials": "123"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "select_saved_credentials"
assert result["errors"] == {"base": "cannot_connect"}
async def test_multiple_config_entries_using_saved_credentials_with_unknown_error(hass):
"""Test a unsuccessful config flow for multiple config entries without valid saved credentials."""
MockConfigEntry(
entry_id="456",
domain=const.DOMAIN,
unique_id="234567",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan"))
| {"student_id": "456"},
).add_to_hass(hass)
MockConfigEntry(
entry_id="123",
domain=const.DOMAIN,
unique_id="123456",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan")),
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "add_next_config_entry"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"use_saved_credentials": True},
)
with patch(
"homeassistant.components.vulcan.config_flow.Vulcan.get_students",
side_effect=Exception,
):
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "select_saved_credentials"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"credentials": "123"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "unknown"}
@mock.patch("homeassistant.components.vulcan.config_flow.Vulcan.get_students")
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
@mock.patch("homeassistant.components.vulcan.config_flow.Account.register")
async def test_student_already_exists(mock_account, mock_keystore, mock_student, hass):
"""Test config entry when student's entry already exists."""
mock_keystore.return_value = fake_keystore
mock_account.return_value = fake_account
mock_student.return_value = [
Student.load(load_fixture("fake_student_1.json", "vulcan"))
]
MockConfigEntry(
domain=const.DOMAIN,
unique_id="0",
data=json.loads(load_fixture("fake_config_entry_data.json", "vulcan"))
| {"student_id": "0"},
).add_to_hass(hass)
await register.register(hass, "token", "region", "000000")
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "add_next_config_entry"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"use_saved_credentials": True},
)
assert result["type"] == data_entry_flow.FlowResultType.ABORT
assert result["reason"] == "all_student_already_configured"
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
async def test_config_flow_auth_invalid_token(mock_keystore, hass):
"""Test a config flow initialized by the user using invalid token."""
mock_keystore.return_value = fake_keystore
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=InvalidTokenException,
):
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "3S20000", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "invalid_token"}
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
async def test_config_flow_auth_invalid_region(mock_keystore, hass):
"""Test a config flow initialized by the user using invalid region."""
mock_keystore.return_value = fake_keystore
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=InvalidSymbolException,
):
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "3S10000", CONF_REGION: "invalid_region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "invalid_symbol"}
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
async def test_config_flow_auth_invalid_pin(mock_keystore, hass):
"""Test a config flow initialized by the with invalid pin."""
mock_keystore.return_value = fake_keystore
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=InvalidPINException,
):
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "3S10000", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "invalid_pin"}
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
async def test_config_flow_auth_expired_token(mock_keystore, hass):
"""Test a config flow initialized by the with expired token."""
mock_keystore.return_value = fake_keystore
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=ExpiredTokenException,
):
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "3S10000", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "expired_token"}
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
async def test_config_flow_auth_connection_error(mock_keystore, hass):
"""Test a config flow with connection error."""
mock_keystore.return_value = fake_keystore
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=ClientConnectionError,
):
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "3S10000", CONF_REGION: "region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "cannot_connect"}
@mock.patch("homeassistant.components.vulcan.config_flow.Keystore.create")
async def test_config_flow_auth_unknown_error(mock_keystore, hass):
"""Test a config flow with unknown error."""
mock_keystore.return_value = fake_keystore
with patch(
"homeassistant.components.vulcan.config_flow.Account.register",
side_effect=Exception,
):
result = await hass.config_entries.flow.async_init(
const.DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TOKEN: "3S10000", CONF_REGION: "invalid_region", CONF_PIN: "000000"},
)
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "unknown"}
| {
"content_hash": "eff209f209b5a37b4cfd6cdc5c6cb0d8",
"timestamp": "",
"source": "github",
"line_count": 857,
"max_line_length": 114,
"avg_line_length": 37.858809801633605,
"alnum_prop": 0.651471721374634,
"repo_name": "mezz64/home-assistant",
"id": "c45ab430c2e1c55c1650fea70ad0cfd1e407bb2b",
"size": "32445",
"binary": false,
"copies": "3",
"ref": "refs/heads/dev",
"path": "tests/components/vulcan/test_config_flow.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "2963"
},
{
"name": "PLSQL",
"bytes": "840"
},
{
"name": "Python",
"bytes": "52481895"
},
{
"name": "Shell",
"bytes": "6252"
}
],
"symlink_target": ""
} |
from django import template
register = template.Library()
@register.filter
def get_computational_value_by_answer(hierarchial_data):
options = {}
for location, answers in hierarchial_data.items():
for option, answer in answers.items():
if not options.has_key(option):
options[option] = []
options[option].append(answer)
data = []
for key, value in options.items():
data.append({
'name': str(key),
'data': value
})
return data | {
"content_hash": "939f082d8168a575b063044fd6708ec5",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 56,
"avg_line_length": 28.105263157894736,
"alnum_prop": 0.5880149812734082,
"repo_name": "unicefuganda/mics",
"id": "9e47a1183d89c7dd90e9f8f99a98971f72b37365",
"size": "534",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "survey/templatetags/chart_template_tags.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "37725"
},
{
"name": "JavaScript",
"bytes": "390607"
},
{
"name": "Python",
"bytes": "5209696"
},
{
"name": "Shell",
"bytes": "1277"
}
],
"symlink_target": ""
} |
import json
import threading
import time
import os
import stat
import ssl
from decimal import Decimal
from typing import Union, Optional, Dict, Sequence, Tuple
from numbers import Real
from copy import deepcopy
from aiorpcx import NetAddress
from . import util
from . import constants
from .util import base_units, base_unit_name_to_decimal_point, decimal_point_to_base_unit_name, UnknownBaseUnit, DECIMAL_POINT_DEFAULT
from .util import format_satoshis, format_fee_satoshis, os_chmod
from .util import user_dir, make_dir, NoDynamicFeeEstimates, quantize_feerate
from .i18n import _
from .logging import get_logger, Logger
FEE_ETA_TARGETS = [25, 10, 5, 2]
FEE_DEPTH_TARGETS = [10_000_000, 5_000_000, 2_000_000, 1_000_000,
800_000, 600_000, 400_000, 250_000, 100_000]
FEE_LN_ETA_TARGET = 2 # note: make sure the network is asking for estimates for this target
# satoshi per kbyte
FEERATE_MAX_DYNAMIC = 1000000
FEERATE_WARNING_HIGH_FEE = 600000
FEERATE_FALLBACK_STATIC_FEE = 100000
FEERATE_DEFAULT_RELAY = 1000
FEERATE_MAX_RELAY = 50000
FEERATE_STATIC_VALUES = [1000, 2000, 5000, 10000, 20000, 30000,
50000, 70000, 100000, 150000, 200000, 300000]
FEERATE_REGTEST_HARDCODED = 180000 # for eclair compat
# The min feerate_per_kw that can be used in lightning so that
# the resulting onchain tx pays the min relay fee.
# This would be FEERATE_DEFAULT_RELAY / 4 if not for rounding errors,
# see https://github.com/ElementsProject/lightning/commit/2e687b9b352c9092b5e8bd4a688916ac50b44af0
FEERATE_PER_KW_MIN_RELAY_LIGHTNING = 253
FEE_RATIO_HIGH_WARNING = 0.05 # warn user if fee/amount for on-chain tx is higher than this
_logger = get_logger(__name__)
FINAL_CONFIG_VERSION = 3
class SimpleConfig(Logger):
"""
The SimpleConfig class is responsible for handling operations involving
configuration files.
There are two different sources of possible configuration values:
1. Command line options.
2. User configuration (in the user's config directory)
They are taken in order (1. overrides config options set in 2.)
"""
def __init__(self, options=None, read_user_config_function=None,
read_user_dir_function=None):
if options is None:
options = {}
Logger.__init__(self)
# This lock needs to be acquired for updating and reading the config in
# a thread-safe way.
self.lock = threading.RLock()
self.mempool_fees = None # type: Optional[Sequence[Tuple[Union[float, int], int]]]
self.fee_estimates = {} # type: Dict[int, int]
self.last_time_fee_estimates_requested = 0 # zero ensures immediate fees
# The following two functions are there for dependency injection when
# testing.
if read_user_config_function is None:
read_user_config_function = read_user_config
if read_user_dir_function is None:
self.user_dir = user_dir
else:
self.user_dir = read_user_dir_function
# The command line options
self.cmdline_options = deepcopy(options)
# don't allow to be set on CLI:
self.cmdline_options.pop('config_version', None)
# Set self.path and read the user config
self.user_config = {} # for self.get in electrum_path()
self.path = self.electrum_path()
self.user_config = read_user_config_function(self.path)
if not self.user_config:
# avoid new config getting upgraded
self.user_config = {'config_version': FINAL_CONFIG_VERSION}
self._not_modifiable_keys = set()
# config "upgrade" - CLI options
self.rename_config_keys(
self.cmdline_options, {'auto_cycle': 'auto_connect'}, True)
# config upgrade - user config
if self.requires_upgrade():
self.upgrade()
self._check_dependent_keys()
# units and formatting
self.decimal_point = self.get('decimal_point', DECIMAL_POINT_DEFAULT)
try:
decimal_point_to_base_unit_name(self.decimal_point)
except UnknownBaseUnit:
self.decimal_point = DECIMAL_POINT_DEFAULT
self.num_zeros = int(self.get('num_zeros', 0))
self.amt_precision_post_satoshi = int(self.get('amt_precision_post_satoshi', 0))
self.amt_add_thousands_sep = bool(self.get('amt_add_thousands_sep', False))
def electrum_path(self):
# Read electrum_path from command line
# Otherwise use the user's default data directory.
path = self.get('electrum_path')
if path is None:
path = self.user_dir()
make_dir(path, allow_symlink=False)
if self.get('testnet'):
path = os.path.join(path, 'testnet')
make_dir(path, allow_symlink=False)
elif self.get('regtest'):
path = os.path.join(path, 'regtest')
make_dir(path, allow_symlink=False)
elif self.get('simnet'):
path = os.path.join(path, 'simnet')
make_dir(path, allow_symlink=False)
elif self.get('signet'):
path = os.path.join(path, 'signet')
make_dir(path, allow_symlink=False)
self.logger.info(f"electrum directory {path}")
return path
def rename_config_keys(self, config, keypairs, deprecation_warning=False):
"""Migrate old key names to new ones"""
updated = False
for old_key, new_key in keypairs.items():
if old_key in config:
if new_key not in config:
config[new_key] = config[old_key]
if deprecation_warning:
self.logger.warning('Note that the {} variable has been deprecated. '
'You should use {} instead.'.format(old_key, new_key))
del config[old_key]
updated = True
return updated
def set_key(self, key, value, save=True):
if not self.is_modifiable(key):
self.logger.warning(f"not changing config key '{key}' set on the command line")
return
try:
json.dumps(key)
json.dumps(value)
except:
self.logger.info(f"json error: cannot save {repr(key)} ({repr(value)})")
return
self._set_key_in_user_config(key, value, save)
def _set_key_in_user_config(self, key, value, save=True):
with self.lock:
if value is not None:
self.user_config[key] = value
else:
self.user_config.pop(key, None)
if save:
self.save_user_config()
def get(self, key, default=None):
with self.lock:
out = self.cmdline_options.get(key)
if out is None:
out = self.user_config.get(key, default)
return out
def _check_dependent_keys(self) -> None:
if self.get('serverfingerprint'):
if not self.get('server'):
raise Exception("config key 'serverfingerprint' requires 'server' to also be set")
self.make_key_not_modifiable('server')
def requires_upgrade(self):
return self.get_config_version() < FINAL_CONFIG_VERSION
def upgrade(self):
with self.lock:
self.logger.info('upgrading config')
self.convert_version_2()
self.convert_version_3()
self.set_key('config_version', FINAL_CONFIG_VERSION, save=True)
def convert_version_2(self):
if not self._is_upgrade_method_needed(1, 1):
return
self.rename_config_keys(self.user_config, {'auto_cycle': 'auto_connect'})
try:
# change server string FROM host:port:proto TO host:port:s
server_str = self.user_config.get('server')
host, port, protocol = str(server_str).rsplit(':', 2)
assert protocol in ('s', 't')
int(port) # Throw if cannot be converted to int
server_str = '{}:{}:s'.format(host, port)
self._set_key_in_user_config('server', server_str)
except BaseException:
self._set_key_in_user_config('server', None)
self.set_key('config_version', 2)
def convert_version_3(self):
if not self._is_upgrade_method_needed(2, 2):
return
base_unit = self.user_config.get('base_unit')
if isinstance(base_unit, str):
self._set_key_in_user_config('base_unit', None)
map_ = {'ltc':8, 'mltc':5, 'ultc':2, 'bits':2, 'sat':0}
decimal_point = map_.get(base_unit.lower())
self._set_key_in_user_config('decimal_point', decimal_point)
self.set_key('config_version', 3)
def _is_upgrade_method_needed(self, min_version, max_version):
cur_version = self.get_config_version()
if cur_version > max_version:
return False
elif cur_version < min_version:
raise Exception(
('config upgrade: unexpected version %d (should be %d-%d)'
% (cur_version, min_version, max_version)))
else:
return True
def get_config_version(self):
config_version = self.get('config_version', 1)
if config_version > FINAL_CONFIG_VERSION:
self.logger.warning('config version ({}) is higher than latest ({})'
.format(config_version, FINAL_CONFIG_VERSION))
return config_version
def is_modifiable(self, key) -> bool:
return (key not in self.cmdline_options
and key not in self._not_modifiable_keys)
def make_key_not_modifiable(self, key) -> None:
self._not_modifiable_keys.add(key)
def save_user_config(self):
if self.get('forget_config'):
return
if not self.path:
return
path = os.path.join(self.path, "config")
s = json.dumps(self.user_config, indent=4, sort_keys=True)
try:
with open(path, "w", encoding='utf-8') as f:
f.write(s)
os_chmod(path, stat.S_IREAD | stat.S_IWRITE)
except FileNotFoundError:
# datadir probably deleted while running...
if os.path.exists(self.path): # or maybe not?
raise
def get_backup_dir(self):
# this is used to save wallet file backups (without active lightning channels)
# on Android, the export backup button uses android_backup_dir()
if 'ANDROID_DATA' in os.environ:
return None
else:
return self.get('backup_dir')
def get_wallet_path(self, *, use_gui_last_wallet=False):
"""Set the path of the wallet."""
# command line -w option
if self.get('wallet_path'):
return os.path.join(self.get('cwd', ''), self.get('wallet_path'))
if use_gui_last_wallet:
path = self.get('gui_last_wallet')
if path and os.path.exists(path):
return path
new_path = self.get_fallback_wallet_path()
# default path in pre 1.9 versions
old_path = os.path.join(self.path, "electrum-ltc.dat")
if os.path.exists(old_path) and not os.path.exists(new_path):
os.rename(old_path, new_path)
return new_path
def get_fallback_wallet_path(self):
util.assert_datadir_available(self.path)
dirpath = os.path.join(self.path, "wallets")
make_dir(dirpath, allow_symlink=False)
path = os.path.join(self.path, "wallets", "default_wallet")
return path
def remove_from_recently_open(self, filename):
recent = self.get('recently_open', [])
if filename in recent:
recent.remove(filename)
self.set_key('recently_open', recent)
def set_session_timeout(self, seconds):
self.logger.info(f"session timeout -> {seconds} seconds")
self.set_key('session_timeout', seconds)
def get_session_timeout(self):
return self.get('session_timeout', 300)
def save_last_wallet(self, wallet):
if self.get('wallet_path') is None:
path = wallet.storage.path
self.set_key('gui_last_wallet', path)
def impose_hard_limits_on_fee(func):
def get_fee_within_limits(self, *args, **kwargs):
fee = func(self, *args, **kwargs)
if fee is None:
return fee
fee = min(FEERATE_MAX_DYNAMIC, fee)
fee = max(FEERATE_DEFAULT_RELAY, fee)
return fee
return get_fee_within_limits
def eta_to_fee(self, slider_pos) -> Optional[int]:
"""Returns fee in sat/kbyte."""
slider_pos = max(slider_pos, 0)
slider_pos = min(slider_pos, len(FEE_ETA_TARGETS))
if slider_pos < len(FEE_ETA_TARGETS):
num_blocks = FEE_ETA_TARGETS[int(slider_pos)]
fee = self.eta_target_to_fee(num_blocks)
else:
fee = self.eta_target_to_fee(1)
return fee
@impose_hard_limits_on_fee
def eta_target_to_fee(self, num_blocks: int) -> Optional[int]:
"""Returns fee in sat/kbyte."""
if num_blocks == 1:
fee = self.fee_estimates.get(2)
if fee is not None:
fee += fee / 2
fee = int(fee)
else:
fee = self.fee_estimates.get(num_blocks)
if fee is not None:
fee = int(fee)
return fee
def fee_to_depth(self, target_fee: Real) -> Optional[int]:
"""For a given sat/vbyte fee, returns an estimate of how deep
it would be in the current mempool in vbytes.
Pessimistic == overestimates the depth.
"""
if self.mempool_fees is None:
return None
depth = 0
for fee, s in self.mempool_fees:
depth += s
if fee <= target_fee:
break
return depth
def depth_to_fee(self, slider_pos) -> Optional[int]:
"""Returns fee in sat/kbyte."""
target = self.depth_target(slider_pos)
return self.depth_target_to_fee(target)
@impose_hard_limits_on_fee
def depth_target_to_fee(self, target: int) -> Optional[int]:
"""Returns fee in sat/kbyte.
target: desired mempool depth in vbytes
"""
if self.mempool_fees is None:
return None
depth = 0
for fee, s in self.mempool_fees:
depth += s
if depth > target:
break
else:
return 0
# add one sat/byte as currently that is the max precision of the histogram
# note: precision depends on server.
# old ElectrumX <1.16 has 1 s/b prec, >=1.16 has 0.1 s/b prec.
# electrs seems to use untruncated double-precision floating points.
# # TODO decrease this to 0.1 s/b next time we bump the required protocol version
fee += 1
# convert to sat/kbyte
return int(fee * 1000)
def depth_target(self, slider_pos: int) -> int:
"""Returns mempool depth target in bytes for a fee slider position."""
slider_pos = max(slider_pos, 0)
slider_pos = min(slider_pos, len(FEE_DEPTH_TARGETS)-1)
return FEE_DEPTH_TARGETS[slider_pos]
def eta_target(self, slider_pos: int) -> int:
"""Returns 'num blocks' ETA target for a fee slider position."""
if slider_pos == len(FEE_ETA_TARGETS):
return 1
return FEE_ETA_TARGETS[slider_pos]
def fee_to_eta(self, fee_per_kb: Optional[int]) -> int:
"""Returns 'num blocks' ETA estimate for given fee rate,
or -1 for low fee.
"""
import operator
lst = list(self.fee_estimates.items())
next_block_fee = self.eta_target_to_fee(1)
if next_block_fee is not None:
lst += [(1, next_block_fee)]
if not lst or fee_per_kb is None:
return -1
dist = map(lambda x: (x[0], abs(x[1] - fee_per_kb)), lst)
min_target, min_value = min(dist, key=operator.itemgetter(1))
if fee_per_kb < self.fee_estimates.get(FEE_ETA_TARGETS[0])/2:
min_target = -1
return min_target
def get_depth_mb_str(self, depth: int) -> str:
# e.g. 500_000 -> "0.50 MB"
depth_mb = "{:.2f}".format(depth / 1_000_000) # maybe .rstrip("0") ?
return f"{depth_mb} MB"
def depth_tooltip(self, depth: Optional[int]) -> str:
"""Returns text tooltip for given mempool depth (in vbytes)."""
if depth is None:
return "unknown from tip"
depth_mb = self.get_depth_mb_str(depth)
return _("{} from tip").format(depth_mb)
def eta_tooltip(self, x):
if x < 0:
return _('Low fee')
elif x == 1:
return _('In the next block')
else:
return _('Within {} blocks').format(x)
def get_fee_target(self):
dyn = self.is_dynfee()
mempool = self.use_mempool_fees()
pos = self.get_depth_level() if mempool else self.get_fee_level()
fee_rate = self.fee_per_kb()
target, tooltip = self.get_fee_text(pos, dyn, mempool, fee_rate)
return target, tooltip, dyn
def get_fee_status(self):
target, tooltip, dyn = self.get_fee_target()
return tooltip + ' [%s]'%target if dyn else target + ' [Static]'
def get_fee_text(
self,
slider_pos: int,
dyn: bool,
mempool: bool,
fee_per_kb: Optional[int],
):
"""Returns (text, tooltip) where
text is what we target: static fee / num blocks to confirm in / mempool depth
tooltip is the corresponding estimate (e.g. num blocks for a static fee)
fee_rate is in sat/kbyte
"""
if fee_per_kb is None:
rate_str = 'unknown'
fee_per_byte = None
else:
fee_per_byte = fee_per_kb/1000
rate_str = format_fee_satoshis(fee_per_byte) + ' sat/byte'
if dyn:
if mempool:
depth = self.depth_target(slider_pos)
text = self.depth_tooltip(depth)
else:
eta = self.eta_target(slider_pos)
text = self.eta_tooltip(eta)
tooltip = rate_str
else: # using static fees
assert fee_per_kb is not None
assert fee_per_byte is not None
text = rate_str
if mempool and self.has_fee_mempool():
depth = self.fee_to_depth(fee_per_byte)
tooltip = self.depth_tooltip(depth)
elif not mempool and self.has_fee_etas():
eta = self.fee_to_eta(fee_per_kb)
tooltip = self.eta_tooltip(eta)
else:
tooltip = ''
return text, tooltip
def get_depth_level(self):
maxp = len(FEE_DEPTH_TARGETS) - 1
return min(maxp, self.get('depth_level', 2))
def get_fee_level(self):
maxp = len(FEE_ETA_TARGETS) # not (-1) to have "next block"
return min(maxp, self.get('fee_level', 2))
def get_fee_slider(self, dyn, mempool) -> Tuple[int, int, Optional[int]]:
if dyn:
if mempool:
pos = self.get_depth_level()
maxp = len(FEE_DEPTH_TARGETS) - 1
fee_rate = self.depth_to_fee(pos)
else:
pos = self.get_fee_level()
maxp = len(FEE_ETA_TARGETS) # not (-1) to have "next block"
fee_rate = self.eta_to_fee(pos)
else:
fee_rate = self.fee_per_kb(dyn=False)
pos = self.static_fee_index(fee_rate)
maxp = len(FEERATE_STATIC_VALUES) - 1
return maxp, pos, fee_rate
def static_fee(self, i):
return FEERATE_STATIC_VALUES[i]
def static_fee_index(self, fee_per_kb: Optional[int]) -> int:
if fee_per_kb is None:
raise TypeError('static fee cannot be None')
dist = list(map(lambda x: abs(x - fee_per_kb), FEERATE_STATIC_VALUES))
return min(range(len(dist)), key=dist.__getitem__)
def has_fee_etas(self):
return len(self.fee_estimates) == 4
def has_fee_mempool(self) -> bool:
return self.mempool_fees is not None
def has_dynamic_fees_ready(self):
if self.use_mempool_fees():
return self.has_fee_mempool()
else:
return self.has_fee_etas()
def is_dynfee(self):
return bool(self.get('dynamic_fees', False))
def use_mempool_fees(self):
return bool(self.get('mempool_fees', False))
def _feerate_from_fractional_slider_position(self, fee_level: float, dyn: bool,
mempool: bool) -> Union[int, None]:
fee_level = max(fee_level, 0)
fee_level = min(fee_level, 1)
if dyn:
max_pos = (len(FEE_DEPTH_TARGETS) - 1) if mempool else len(FEE_ETA_TARGETS)
slider_pos = round(fee_level * max_pos)
fee_rate = self.depth_to_fee(slider_pos) if mempool else self.eta_to_fee(slider_pos)
else:
max_pos = len(FEERATE_STATIC_VALUES) - 1
slider_pos = round(fee_level * max_pos)
fee_rate = FEERATE_STATIC_VALUES[slider_pos]
return fee_rate
def fee_per_kb(self, dyn: bool=None, mempool: bool=None, fee_level: float=None) -> Optional[int]:
"""Returns sat/kvB fee to pay for a txn.
Note: might return None.
fee_level: float between 0.0 and 1.0, representing fee slider position
"""
if constants.net is constants.BitcoinRegtest:
return FEERATE_REGTEST_HARDCODED
if dyn is None:
dyn = self.is_dynfee()
if mempool is None:
mempool = self.use_mempool_fees()
if fee_level is not None:
return self._feerate_from_fractional_slider_position(fee_level, dyn, mempool)
# there is no fee_level specified; will use config.
# note: 'depth_level' and 'fee_level' in config are integer slider positions,
# unlike fee_level here, which (when given) is a float in [0.0, 1.0]
if dyn:
if mempool:
fee_rate = self.depth_to_fee(self.get_depth_level())
else:
fee_rate = self.eta_to_fee(self.get_fee_level())
else:
fee_rate = self.get('fee_per_kb', FEERATE_FALLBACK_STATIC_FEE)
if fee_rate is not None:
fee_rate = int(fee_rate)
return fee_rate
def fee_per_byte(self):
"""Returns sat/vB fee to pay for a txn.
Note: might return None.
"""
fee_per_kb = self.fee_per_kb()
return fee_per_kb / 1000 if fee_per_kb is not None else None
def estimate_fee(self, size: Union[int, float, Decimal], *,
allow_fallback_to_static_rates: bool = False) -> int:
fee_per_kb = self.fee_per_kb()
if fee_per_kb is None:
if allow_fallback_to_static_rates:
fee_per_kb = FEERATE_FALLBACK_STATIC_FEE
else:
raise NoDynamicFeeEstimates()
return self.estimate_fee_for_feerate(fee_per_kb, size)
@classmethod
def estimate_fee_for_feerate(cls, fee_per_kb: Union[int, float, Decimal],
size: Union[int, float, Decimal]) -> int:
size = Decimal(size)
fee_per_kb = Decimal(fee_per_kb)
fee_per_byte = fee_per_kb / 1000
# to be consistent with what is displayed in the GUI,
# the calculation needs to use the same precision:
fee_per_byte = quantize_feerate(fee_per_byte)
return round(fee_per_byte * size)
def update_fee_estimates(self, nblock_target: int, fee_per_kb: int):
assert isinstance(nblock_target, int), f"expected int, got {nblock_target!r}"
assert isinstance(fee_per_kb, int), f"expected int, got {fee_per_kb!r}"
self.fee_estimates[nblock_target] = fee_per_kb
def is_fee_estimates_update_required(self):
"""Checks time since last requested and updated fee estimates.
Returns True if an update should be requested.
"""
now = time.time()
return now - self.last_time_fee_estimates_requested > 60
def requested_fee_estimates(self):
self.last_time_fee_estimates_requested = time.time()
def get_video_device(self):
device = self.get("video_device", "default")
if device == 'default':
device = ''
return device
def get_ssl_context(self):
ssl_keyfile = self.get('ssl_keyfile')
ssl_certfile = self.get('ssl_certfile')
if ssl_keyfile and ssl_certfile:
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(ssl_certfile, ssl_keyfile)
return ssl_context
def get_ssl_domain(self):
from .paymentrequest import check_ssl_config
if self.get('ssl_keyfile') and self.get('ssl_certfile'):
SSL_identity = check_ssl_config(self)
else:
SSL_identity = None
return SSL_identity
def get_netaddress(self, key: str) -> Optional[NetAddress]:
text = self.get(key)
if text:
try:
return NetAddress.from_string(text)
except:
pass
def format_amount(self, x, is_diff=False, whitespaces=False):
return format_satoshis(
x,
num_zeros=self.num_zeros,
decimal_point=self.decimal_point,
is_diff=is_diff,
whitespaces=whitespaces,
precision=self.amt_precision_post_satoshi,
add_thousands_sep=self.amt_add_thousands_sep,
)
def format_amount_and_units(self, amount):
return self.format_amount(amount) + ' '+ self.get_base_unit()
def format_fee_rate(self, fee_rate):
return format_fee_satoshis(fee_rate/1000, num_zeros=self.num_zeros) + ' sat/byte'
def get_base_unit(self):
return decimal_point_to_base_unit_name(self.decimal_point)
def set_base_unit(self, unit):
assert unit in base_units.keys()
self.decimal_point = base_unit_name_to_decimal_point(unit)
self.set_key('decimal_point', self.decimal_point, True)
def get_decimal_point(self):
return self.decimal_point
def read_user_config(path):
"""Parse and store the user config settings in electrum-ltc.conf into user_config[]."""
if not path:
return {}
config_path = os.path.join(path, "config")
if not os.path.exists(config_path):
return {}
try:
with open(config_path, "r", encoding='utf-8') as f:
data = f.read()
result = json.loads(data)
except Exception as exc:
_logger.warning(f"Cannot read config file at {config_path}: {exc}")
return {}
if not type(result) is dict:
return {}
return result
| {
"content_hash": "8c63ca02ca0cece60678e9d0eff71b48",
"timestamp": "",
"source": "github",
"line_count": 725,
"max_line_length": 134,
"avg_line_length": 37.358620689655176,
"alnum_prop": 0.5822041720509508,
"repo_name": "pooler/electrum-ltc",
"id": "e6e5464d4a98905c5d5b048e27563a268e5f3fe0",
"size": "27085",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "electrum_ltc/simple_config.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "13024"
},
{
"name": "GLSL",
"bytes": "289"
},
{
"name": "Java",
"bytes": "2929"
},
{
"name": "Makefile",
"bytes": "2193"
},
{
"name": "NSIS",
"bytes": "7354"
},
{
"name": "Python",
"bytes": "5325268"
},
{
"name": "QML",
"bytes": "318745"
},
{
"name": "Ruby",
"bytes": "16856"
},
{
"name": "Shell",
"bytes": "105672"
},
{
"name": "kvlang",
"bytes": "70748"
}
],
"symlink_target": ""
} |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
import os
import signal
import subprocess
import time
import traceback
from contextlib import contextmanager
import psutil
from pants.base.build_environment import get_buildroot
from pants.util.dirutil import rm_rf, safe_mkdir, safe_open
logger = logging.getLogger(__name__)
@contextmanager
def swallow_psutil_exceptions():
"""A contextmanager that swallows standard psutil access exceptions."""
try:
yield
except (psutil.AccessDenied, psutil.NoSuchProcess):
# This masks common, but usually benign psutil process access exceptions that might be seen
# when accessing attributes/methods on psutil.Process objects.
pass
class ProcessGroup(object):
"""Wraps a logical group of processes and provides convenient access to ProcessManager objects."""
def __init__(self, name):
self._name = name
def _instance_from_process(self, process):
"""Default converter from psutil.Process to process instance classes for subclassing."""
return ProcessManager(name=process.name(), pid=process.pid, process_name=process.name())
def iter_processes(self, proc_filter=None):
proc_filter = proc_filter or (lambda x: True)
with swallow_psutil_exceptions():
for proc in (x for x in psutil.process_iter() if proc_filter(x)):
yield proc
def iter_instances(self, *args, **kwargs):
for item in self.iter_processes(*args, **kwargs):
yield self._instance_from_process(item)
class ProcessManager(object):
"""Subprocess/daemon management mixin/superclass. Not intended to be thread-safe."""
class ExecutionError(Exception): pass
class MetadataError(Exception): pass
class InvalidCommandOutput(Exception): pass
class NonResponsiveProcess(Exception): pass
class Timeout(Exception): pass
WAIT_INTERVAL_SEC = .1
FILE_WAIT_SEC = 10
KILL_WAIT_SEC = 5
KILL_CHAIN = (signal.SIGTERM, signal.SIGKILL)
def __init__(self, name, pid=None, socket=None, process_name=None, socket_type=None):
self._name = name
self._pid = pid
self._socket = socket
self._socket_type = socket_type or int
self._process_name = process_name
self._buildroot = get_buildroot()
self._process = None
@property
def name(self):
"""The logical name/label of the process."""
return self._name
@property
def process_name(self):
"""The logical process name. If defined, this is compared to exe_name for stale pid checking."""
return self._process_name
@property
def cmdline(self):
"""The process commandline. e.g. ['/usr/bin/python2.7', 'pants.pex'].
:returns: The command line or else `None` if the underlying process has died.
"""
with swallow_psutil_exceptions():
process = self._as_process()
if process:
return process.cmdline()
return None
@property
def cmd(self):
"""The first element of the process commandline e.g. '/usr/bin/python2.7'.
:returns: The first element of the process command line or else `None` if the underlying
process has died.
"""
return (self.cmdline or [None])[0]
@property
def pid(self):
"""The running processes pid (or None)."""
return self._pid or self._get_pid()
@property
def socket(self):
"""The running processes socket/port information (or None)."""
return self._socket or self._get_socket()
@staticmethod
def _maybe_cast(x, caster):
try:
return caster(x)
except (TypeError, ValueError):
return x
def _as_process(self):
"""Returns a psutil `Process` object wrapping our pid.
NB: Even with a process object in hand, subsequent method calls against it can always raise
`NoSuchProcess`. Care is needed to document the raises in the public API or else trap them and
do something sensible for the API.
:returns: a psutil Process object or else None if we have no pid.
:rtype: :class:`psutil.Process`
:raises: :class:`psutil.NoSuchProcess` if the process identified by our pid has died.
"""
if self._process is None and self.pid:
self._process = psutil.Process(self.pid)
return self._process
def _read_file(self, filename):
with safe_open(filename, 'rb') as f:
return f.read().strip()
def _write_file(self, filename, payload):
with safe_open(filename, 'wb') as f:
f.write(payload)
def _deadline_until(self, closure, timeout, wait_interval=WAIT_INTERVAL_SEC):
"""Execute a function/closure repeatedly until a True condition or timeout is met.
:param func closure: the function/closure to execute (should not block for long periods of time
and must return True on success).
:param float timeout: the maximum amount of time to wait for a true result from the closure in
seconds. N.B. this is timing based, so won't be exact if the runtime of
the closure exceeds the timeout.
:param float wait_interval: the amount of time to sleep between closure invocations.
:raises: :class:`ProcessManager.Timeout` on execution timeout.
"""
deadline = time.time() + timeout
while 1:
if closure():
return True
elif time.time() > deadline:
raise self.Timeout('exceeded timeout of {} seconds for {}'.format(timeout, closure))
elif wait_interval:
time.sleep(wait_interval)
def _wait_for_file(self, filename, timeout=FILE_WAIT_SEC, want_content=True):
"""Wait up to timeout seconds for filename to appear with a non-zero size or raise Timeout()."""
def file_waiter():
return os.path.exists(filename) and (not want_content or os.path.getsize(filename))
try:
return self._deadline_until(file_waiter, timeout)
except self.Timeout:
# Re-raise with a more helpful exception message.
raise self.Timeout('exceeded timeout of {} seconds while waiting for file {} to appear'
.format(timeout, filename))
def await_pid(self, timeout):
"""Wait up to a given timeout for a process to launch."""
self._wait_for_file(self.get_pid_path(), timeout)
return self._get_pid()
def await_socket(self, timeout):
"""Wait up to a given timeout for a process to write socket info."""
self._wait_for_file(self.get_socket_path(), timeout)
return self._get_socket()
def get_metadata_dir(self):
"""Return a metadata path for the process.
This should always live outside of the .pants.d dir to survive a clean-all.
"""
return os.path.join(self._buildroot, '.pids', self._name)
def purge_metadata(self, force=False):
"""Purge a processes metadata directory.
:param bool force: If True, skip process liveness check before purging metadata.
:raises: `ProcessManager.MetadataError` when OSError is encountered on metadata dir removal.
"""
if not force:
assert not self.is_alive(), 'aborting attempt to purge metadata for a running process!'
meta_dir = self.get_metadata_dir()
logging.debug('purging metadata directory: {}'.format(meta_dir))
try:
rm_rf(meta_dir)
except OSError as e:
raise self.MetadataError('failed to purge metadata directory {}: {!r}'.format(meta_dir, e))
def get_pid_path(self):
"""Return the path to the file containing the processes pid."""
return os.path.join(self.get_metadata_dir(), 'pid')
def get_socket_path(self):
"""Return the path to the file containing the processes socket."""
return os.path.join(self.get_metadata_dir(), 'socket')
def _maybe_init_metadata_dir(self):
safe_mkdir(self.get_metadata_dir())
def write_pid(self, pid):
"""Write the current processes PID to the pidfile location"""
self._maybe_init_metadata_dir()
self._write_file(self.get_pid_path(), str(pid))
def write_socket(self, socket_info):
"""Write the local processes socket information (TCP port or UNIX socket)."""
self._maybe_init_metadata_dir()
self._write_file(self.get_socket_path(), str(socket_info))
def _get_pid(self):
"""Retrieve and return the running PID."""
try:
return self._maybe_cast(self._read_file(self.get_pid_path()), int) or None
except (IOError, OSError):
return None
def _get_socket(self):
"""Retrieve and return the running processes socket info."""
try:
return self._maybe_cast(self._read_file(self.get_socket_path()), self._socket_type) or None
except (IOError, OSError):
return None
def is_dead(self):
"""Return a boolean indicating whether the process is dead or not."""
return not self.is_alive()
def is_alive(self):
"""Return a boolean indicating whether the process is running or not."""
try:
process = self._as_process()
if not process:
# Can happen if we don't find our pid.
return False
if (process.status() == psutil.STATUS_ZOMBIE or # Check for walkers.
(self.process_name and self.process_name != process.name())): # Check for stale pids.
return False
except (psutil.NoSuchProcess, psutil.AccessDenied):
# On some platforms, accessing attributes of a zombie'd Process results in NoSuchProcess.
return False
return True
def _kill(self, kill_sig):
"""Send a signal to the current process."""
if self.pid:
os.kill(self.pid, kill_sig)
def terminate(self, signal_chain=KILL_CHAIN, kill_wait=KILL_WAIT_SEC, purge=True):
"""Ensure a process is terminated by sending a chain of kill signals (SIGTERM, SIGKILL)."""
alive = self.is_alive()
if alive:
for signal_type in signal_chain:
try:
self._kill(signal_type)
except OSError as e:
logger.warning('caught OSError({e!s}) during attempt to kill -{signal} {pid}!'
.format(e=e, signal=signal_type, pid=self.pid))
# Wait up to kill_wait seconds to terminate or move onto the next signal.
try:
if self._deadline_until(self.is_dead, kill_wait):
alive = False
break
except self.Timeout:
# Loop to the next kill signal on timeout.
pass
if alive:
raise self.NonResponsiveProcess('failed to kill pid {pid} with signals {chain}'
.format(pid=self.pid, chain=signal_chain))
if purge:
self.purge_metadata(force=True)
def get_subprocess_output(self, *args):
try:
return subprocess.check_output(*args)
except (OSError, subprocess.CalledProcessError) as e:
raise self.ExecutionError(str(e))
def daemonize(self, pre_fork_opts=None, post_fork_parent_opts=None, post_fork_child_opts=None,
write_pid=True):
"""Perform a double-fork, execute callbacks and write the child pid file.
The double-fork here is necessary to truly daemonize the subprocess such that it can never
take control of a tty. The initial fork and setsid() creates a new, isolated process group
and also makes the first child a session leader (which can still acquire a tty). By forking a
second time, we ensure that the second child can never acquire a controlling terminal because
it's no longer a session leader - but it now has its own separate process group.
Additionally, a normal daemon implementation would typically perform an os.umask(0) to reset
the processes file mode creation mask post-fork. We do not do this here (and in daemon_spawn
below) due to the fact that the daemons that pants would run are typically personal user
daemons. Having a disparate umask from pre-vs-post fork causes files written in each phase to
differ in their permissions without good reason - in this case, we want to inherit the umask.
"""
self.purge_metadata()
self.pre_fork(**pre_fork_opts or {})
pid = os.fork()
if pid == 0:
os.setsid()
second_pid = os.fork()
if second_pid == 0:
try:
os.chdir(self._buildroot)
self.post_fork_child(**post_fork_child_opts or {})
except Exception:
logging.critical(traceback.format_exc())
os._exit(0)
else:
try:
if write_pid: self.write_pid(second_pid)
self.post_fork_parent(**post_fork_parent_opts or {})
except Exception:
logging.critical(traceback.format_exc())
os._exit(0)
def daemon_spawn(self, pre_fork_opts=None, post_fork_parent_opts=None, post_fork_child_opts=None):
"""Perform a single-fork to run a subprocess and write the child pid file.
Use this if your post_fork_child block invokes a subprocess via subprocess.Popen(). In this
case, a second fork such as used in daemonize() is extraneous given that Popen() also forks.
Using this daemonization method vs daemonize() leaves the responsibility of writing the pid
to the caller to allow for library-agnostic flexibility in subprocess execution.
"""
self.purge_metadata()
self.pre_fork(**pre_fork_opts or {})
pid = os.fork()
if pid == 0:
try:
os.setsid()
os.chdir(self._buildroot)
self.post_fork_child(**post_fork_child_opts or {})
except Exception:
logging.critical(traceback.format_exc())
os._exit(0)
else:
try:
self.post_fork_parent(**post_fork_parent_opts or {})
except Exception:
logging.critical(traceback.format_exc())
def pre_fork(self):
"""Pre-fork callback for subclasses."""
pass
def post_fork_child(self):
"""Pre-fork child callback for subclasses."""
pass
def post_fork_parent(self):
"""Post-fork parent callback for subclasses."""
pass
| {
"content_hash": "db4547cf413f1417d60ed672646e728e",
"timestamp": "",
"source": "github",
"line_count": 380,
"max_line_length": 100,
"avg_line_length": 36.46052631578947,
"alnum_prop": 0.6660411403825334,
"repo_name": "jtrobec/pants",
"id": "7422dc47f2763c41e774027dea759e1022928e47",
"size": "14002",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/python/pants/pantsd/process_manager.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "781"
},
{
"name": "CSS",
"bytes": "11572"
},
{
"name": "GAP",
"bytes": "2459"
},
{
"name": "Gherkin",
"bytes": "919"
},
{
"name": "Go",
"bytes": "1569"
},
{
"name": "HTML",
"bytes": "64616"
},
{
"name": "Java",
"bytes": "281600"
},
{
"name": "JavaScript",
"bytes": "31040"
},
{
"name": "Protocol Buffer",
"bytes": "3783"
},
{
"name": "Python",
"bytes": "4241664"
},
{
"name": "Scala",
"bytes": "84066"
},
{
"name": "Shell",
"bytes": "50645"
},
{
"name": "Thrift",
"bytes": "2898"
}
],
"symlink_target": ""
} |
import os
import os.path as path
import re
from pelican import signals
import logging
logger = logging.getLogger(__name__)
try:
from PIL import Image, ImageOps
enabled = True
except ImportError:
logging.warning("Unable to load PIL, disabling thumbnailer")
enabled = False
DEFAULT_IMAGE_DIR = "pictures"
DEFAULT_THUMBNAIL_DIR = "thumbnails"
DEFAULT_THUMBNAIL_SIZES = {
'thumbnail_square': '150',
'thumbnail_wide': '150x?',
'thumbnail_tall': '?x150',
}
DEFAULT_TEMPLATE = """<a href="{url}" rel="shadowbox" title="{filename}"><img src="{thumbnail}" alt="{filename}"></a>"""
DEFAULT_GALLERY_THUMB = "thumbnail_square"
class _resizer(object):
""" Resizes based on a text specification, see readme """
REGEX = re.compile(r'(\d+|\?)x(\d+|\?)')
def __init__(self, name, spec):
self._name = name
self._spec = spec
def _null_resize(self, w, h, image):
return image
def _exact_resize(self, w, h, image):
retval = ImageOps.fit(image, (w,h), Image.BICUBIC)
return retval
def _aspect_resize(self, w, h, image):
retval = image.copy()
retval.thumbnail((w, h), Image.ANTIALIAS)
return retval
def resize(self, image):
resizer = self._null_resize
# Square resize and crop
if 'x' not in self._spec:
resizer = self._exact_resize
targetw = int(self._spec)
targeth = targetw
else:
matches = self.REGEX.search(self._spec)
tmpw = matches.group(1)
tmph = matches.group(2)
# Full Size
if tmpw == '?' and tmph == '?':
targetw = image.size[0]
targeth = image.size[1]
resizer = self._null_resize
# Set Height Size
if tmpw == '?':
targetw = image.size[0]
targeth = int(tmph)
resizer = self._aspect_resize
# Set Width Size
elif tmph == '?':
targetw = int(tmpw)
targeth = image.size[1]
resizer = self._aspect_resize
# Scale and Crop
else:
targetw = int(tmpw)
targeth = int(tmph)
resizer = self._exact_resize
logging.debug("Using resizer {0}".format(resizer.__name__))
return resizer(targetw, targeth, image)
def get_thumbnail_name(self, in_path):
new_filename = path.basename(in_path)
(basename, ext) = path.splitext(new_filename)
basename = "{0}_{1}".format(basename, self._name)
new_filename = "{0}{1}".format(basename, ext)
return new_filename
def resize_file_to(self, in_path, out_path, keep_filename=False):
""" Given a filename, resize and save the image per the specification into out_path
:param in_path: path to image file to save. Must be supposed by PIL
:param out_path: path to the directory root for the outputted thumbnails to be stored
:return: None
"""
if keep_filename:
filename = path.join(out_path, path.basename(in_path))
else:
filename = path.join(out_path, self.get_thumbnail_name(in_path))
if not path.exists(out_path):
os.makedirs(out_path)
if not path.exists(filename):
image = Image.open(in_path)
thumbnail = self.resize(image)
thumbnail.save(filename)
logger.info("Generated Thumbnail {0}".format(path.basename(filename)))
def resize_thumbnails(pelican):
""" Resize a directory tree full of images into thumbnails
:param pelican: The pelican instance
:return: None
"""
global enabled
if not enabled:
return
in_path = _image_path(pelican)
out_path = path.join(pelican.settings['OUTPUT_PATH'],
pelican.settings.get('THUMBNAIL_DIR', DEFAULT_THUMBNAIL_DIR))
sizes = pelican.settings.get('THUMBNAIL_SIZES', DEFAULT_THUMBNAIL_SIZES)
resizers = dict((k, _resizer(k, v)) for k,v in sizes.items())
logger.debug("Thumbnailer Started")
for dirpath, _, filenames in os.walk(in_path):
for filename in filenames:
for name, resizer in resizers.items():
in_filename = path.join(dirpath, filename)
logger.debug("Processing thumbnail {0}=>{1}".format(filename, name))
if pelican.settings.get('THUMBNAIL_KEEP_NAME', False):
resizer.resize_file_to(in_filename, path.join(out_path, name), True)
else:
resizer.resize_file_to(in_filename, out_path)
def _image_path(pelican):
return path.join(pelican.settings['PATH'],
pelican.settings.get("IMAGE_PATH", DEFAULT_IMAGE_DIR))
def expand_gallery(generator, metadata):
""" Expand a gallery tag to include all of the files in a specific directory under IMAGE_PATH
:param pelican: The pelican instance
:return: None
"""
if "gallery" not in metadata or metadata['gallery'] is None:
return # If no gallery specified, we do nothing
lines = [ ]
base_path = _image_path(generator)
in_path = path.join(base_path, metadata['gallery'])
template = generator.settings.get('GALLERY_TEMPLATE', DEFAULT_TEMPLATE)
thumbnail_name = generator.settings.get("GALLERY_THUMBNAIL", DEFAULT_GALLERY_THUMB)
thumbnail_prefix = generator.settings.get("")
resizer = _resizer(thumbnail_name, '?x?')
for dirpath, _, filenames in os.walk(in_path):
for filename in filenames:
url = path.join(dirpath, filename).replace(base_path, "")[1:]
url = path.join('/static', generator.settings.get('IMAGE_PATH', DEFAULT_IMAGE_DIR), url).replace('\\', '/')
logger.debug("GALLERY: {0}".format(url))
thumbnail = resizer.get_thumbnail_name(filename)
thumbnail = path.join('/', generator.settings.get('THUMBNAIL_DIR', DEFAULT_THUMBNAIL_DIR), thumbnail).replace('\\', '/')
lines.append(template.format(
filename=filename,
url=url,
thumbnail=thumbnail,
))
metadata['gallery_content'] = "\n".join(lines)
def register():
signals.finalized.connect(resize_thumbnails)
signals.article_generator_context.connect(expand_gallery)
| {
"content_hash": "9bce84288185472c8dd86dc52076b7d5",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 132,
"avg_line_length": 35.370165745856355,
"alnum_prop": 0.5938769134645423,
"repo_name": "BenoitDherin/data-analysis-with-R",
"id": "1cf91deba26624da2e751edf3b3d637b93f56dce",
"size": "6402",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "website/plugins/thumbnailer/thumbnailer.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "130934"
},
{
"name": "JavaScript",
"bytes": "3952"
},
{
"name": "Python",
"bytes": "170607"
},
{
"name": "Shell",
"bytes": "2178"
}
],
"symlink_target": ""
} |
from __future__ import annotations
import contextlib
import logging
import os.path
import time
from typing import Generator
from pre_commit import git
from pre_commit.util import CalledProcessError
from pre_commit.util import cmd_output
from pre_commit.util import cmd_output_b
from pre_commit.xargs import xargs
logger = logging.getLogger('pre_commit')
# without forcing submodule.recurse=0, changes in nested submodules will be
# discarded if `submodule.recurse=1` is configured
# we choose this instead of `--no-recurse-submodules` because it works on
# versions of git before that option was added to `git checkout`
_CHECKOUT_CMD = ('git', '-c', 'submodule.recurse=0', 'checkout', '--', '.')
def _git_apply(patch: str) -> None:
args = ('apply', '--whitespace=nowarn', patch)
try:
cmd_output_b('git', *args)
except CalledProcessError:
# Retry with autocrlf=false -- see #570
cmd_output_b('git', '-c', 'core.autocrlf=false', *args)
@contextlib.contextmanager
def _intent_to_add_cleared() -> Generator[None, None, None]:
intent_to_add = git.intent_to_add_files()
if intent_to_add:
logger.warning('Unstaged intent-to-add files detected.')
xargs(('git', 'rm', '--cached', '--'), intent_to_add)
try:
yield
finally:
xargs(('git', 'add', '--intent-to-add', '--'), intent_to_add)
else:
yield
@contextlib.contextmanager
def _unstaged_changes_cleared(patch_dir: str) -> Generator[None, None, None]:
tree = cmd_output('git', 'write-tree')[1].strip()
retcode, diff_stdout_binary, _ = cmd_output_b(
'git', 'diff-index', '--ignore-submodules', '--binary',
'--exit-code', '--no-color', '--no-ext-diff', tree, '--',
check=False,
)
if retcode and diff_stdout_binary.strip():
patch_filename = f'patch{int(time.time())}-{os.getpid()}'
patch_filename = os.path.join(patch_dir, patch_filename)
logger.warning('Unstaged files detected.')
logger.info(f'Stashing unstaged files to {patch_filename}.')
# Save the current unstaged changes as a patch
os.makedirs(patch_dir, exist_ok=True)
with open(patch_filename, 'wb') as patch_file:
patch_file.write(diff_stdout_binary)
# prevent recursive post-checkout hooks (#1418)
no_checkout_env = dict(os.environ, _PRE_COMMIT_SKIP_POST_CHECKOUT='1')
try:
cmd_output_b(*_CHECKOUT_CMD, env=no_checkout_env)
yield
finally:
# Try to apply the patch we saved
try:
_git_apply(patch_filename)
except CalledProcessError:
logger.warning(
'Stashed changes conflicted with hook auto-fixes... '
'Rolling back fixes...',
)
# We failed to apply the patch, presumably due to fixes made
# by hooks.
# Roll back the changes made by hooks.
cmd_output_b(*_CHECKOUT_CMD, env=no_checkout_env)
_git_apply(patch_filename)
logger.info(f'Restored changes from {patch_filename}.')
else:
# There weren't any staged files so we don't need to do anything
# special
yield
@contextlib.contextmanager
def staged_files_only(patch_dir: str) -> Generator[None, None, None]:
"""Clear any unstaged changes from the git working directory inside this
context.
"""
with _intent_to_add_cleared(), _unstaged_changes_cleared(patch_dir):
yield
| {
"content_hash": "40ac44232cbee3d5e734fbfcdd923a57",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 78,
"avg_line_length": 35.43564356435643,
"alnum_prop": 0.6174909192511875,
"repo_name": "pre-commit/pre-commit",
"id": "172fb20b17c04f94d6a6251357a164b9cffe7812",
"size": "3579",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "pre_commit/staged_files_only.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "753"
},
{
"name": "Dart",
"bytes": "142"
},
{
"name": "Dockerfile",
"bytes": "508"
},
{
"name": "Go",
"bytes": "240"
},
{
"name": "JavaScript",
"bytes": "128"
},
{
"name": "Lua",
"bytes": "513"
},
{
"name": "Perl",
"bytes": "532"
},
{
"name": "PowerShell",
"bytes": "744"
},
{
"name": "Python",
"bytes": "511310"
},
{
"name": "R",
"bytes": "24268"
},
{
"name": "Ruby",
"bytes": "829"
},
{
"name": "Rust",
"bytes": "56"
},
{
"name": "Shell",
"bytes": "3952"
},
{
"name": "Swift",
"bytes": "181"
}
],
"symlink_target": ""
} |
'''
Latent Dirichlet Allocation
References:
Heinrich, Gregor. Parameter estimation for text analysis. Technical report. 2005 (revised 2009)
Minka, Thomas P. Estimating a Dirichlet distribution. 2000. (revised 2012)
'''
import math
import numpy as np
import numpy.random as nprand
import scipy as sp
import scipy.misc as spmisc
import scipy.special as spspecial
def word_iter(doc):
'''Return an iterator over words in a document.
:param doc: doc[w] is the number of times word w appears
'''
for w, count in enumerate(doc):
for i in xrange(count):
yield w
def sample(dist):
'''Sample from the given distribution.
:param dist: array of probabilities
:returns: a randomly sampled integer in [0, len(dist))
'''
cdf = np.cumsum(dist)
uniform = nprand.random_sample()
try:
result = next(n for n in range(0, len(cdf)) if cdf[n] > uniform)
except StopIteration:
print "%f %f" % (cdf[len(dist)-1], uniform)
return result
def polya_iteration(ndm, nd, guess, rtol=1e-7, max_iter=25):
'''Estimate the parameter of a dirichlet-multinomial distribution
with num_dir draws from the dirichlet and num_out possible outcomes.
:param ndm: Counts as (num_dir, num_out) array
:param nd: Counts as (num_dir) array
:param guess: Initial guess for dirichlet parameter
:param rtol: Relative tolerance to achieve before stopping
:param max_iter: Maximum number of iterations to allow
:returns: An updated estimate of the dirichlet parameter
'''
num_dir, num_out = ndm.shape
param = guess
for i in range(max_iter):
# Heinrich2005 Eq. 83
# Minka2000 Eq. 55
new = np.zeros(num_out)
param_sum = param.sum()
den = 0
for d in range(num_dir):
den += spspecial.psi(nd[d] + param_sum)
den -= num_dir * spspecial.psi(param_sum)
for m in range(num_out):
for d in range(num_dir):
new[m] += spspecial.psi(ndm[d,m] + param[m])
new[m] -= num_dir * spspecial.psi(param[m])
new[m] /= den
new[m] *= param[m]
if new[m] <= 0:
new[m] = 1e-3/param[m].sum()
rel_change = np.abs((new-param)).sum()/new.sum()
if (rel_change < rtol):
return new
param = new
print 'Warning: reached %d polya iterations with rtol %f > %f' % (max_iter, rel_change, rtol)
return param
def estimate_dirichlet_newton(alpha, nlogtheta, rtol=1e-7, max_iter=30):
'''Estimate parameters of a dirichlet distribuiton using Newton's method.'''
M = nlogtheta.shape[0]
nlogtheta = nlogtheta.sum(0)
psi = spspecial.psi
polyg = spspecial.polygamma
for i in range(max_iter):
old = alpha
sumalpha = sum(alpha)
g = -M*psi(alpha) + M*psi(sumalpha) + nlogtheta
q = -M*polyg(1,alpha)
qa = M*polyg(1,sumalpha)
b = sum(g / q) / (1/qa + sum(1/q))
alpha = alpha - (g - b) / q
for i in [i for i, ak in enumerate(alpha) if ak <= 0.0]:
alpha[i] = 1e-3 / alpha.sum()
rel_change = np.abs(alpha - old).sum()/alpha.sum()
if rel_change < rtol:
return alpha
print 'Warning: reached %d newton iterations with rtol %f > %f' % (max_iter, rel_change, rtol)
return alpha
def log_multinomial_beta(a, axis=0):
'''Log of multinomial beta function along a given axis (default 0).'''
return spspecial.gammaln(a).sum(axis) - spspecial.gammaln(a.sum(axis))
def multinomial_beta(a, axis=0):
'''Multinomial beta function along a given axis (default 0).'''
return np.exp(log_multinomial_beta(a, axis))
def merge_query_stats(train, test):
'''Merge training and test statistics.'''
# We do not include training topics in the list so they aren't resampled
# We don't change indices on the topics dict so test data must be first!
stats = {
'nmk': np.concatenate((test['nmk'], train['nmk']))
, 'nm': np.concatenate((test['nm'], train['nm']))
, 'nkw': train['nkw'] + test['nkw']
, 'nk': train['nk'] + test['nk']
, 'topics': dict(test['topics'])
}
return stats
def split_query_stats(train, combined):
'''Get test stats from combined training-test stats after a query.'''
num_test = combined['nmk'].shape[0] - train['nmk'].shape[0]
stats = {
'nmk': combined['nmk'][:num_test,:]
, 'nm': combined['nm'][:num_test]
, 'nkw': combined['nkw'] - train['nkw']
, 'nk': combined['nk'] - train['nk']
, 'topics': dict(combined['topics'])
}
return stats
class LdaModel(object):
def __init__(self, training, num_topics, alpha=0.1, eta=0.1, burn=50, lag=4):
'''Creates an LDA model.
:param training: training corpus as (num_doc, vocab_size) array
:param num_topics: number of topics
:param alpha: document-topic dirichlet parameter, scalar or array,
defaults to 0.1
:param eta: topic-word dirichlet parameter, scalar or array,
defaults to 0.1
:param burn: number of "burn-in" gibbs iterations, default 50
:param lag: number of gibbs iterations between samples, default 4
'''
self.num_topics = num_topics
# Validate alpha and eta, and convert to array if necessary
try:
if len(alpha) != num_topics:
raise ValueError("alpha must be a number or a num_topic-length vector")
self.alpha = alpha
except TypeError:
self.alpha = np.ones(num_topics)*alpha
try:
if len(eta) != training.shape[1]:
raise ValueError("eta must be a number or a vocab_size-length vector")
self.eta = eta
except TypeError:
self.eta = np.ones(training.shape[1])*eta
# Initialize gibbs sampler
self.burn = burn
self.lag = lag
self.stats = self._gibbs_init(training)
self._gibbs_sample_n(self.stats, burn)
def em_iterate(self, n=1):
'''Do n (default 1) EM iterations.'''
for i in range(n):
self.e_step()
self.m_step()
def e_step(self):
'''Associate each word with a topic using Gibbs sampling.'''
self._gibbs_sample(self.stats)
def m_step(self):
'''Update estimates for alpha and eta to maximize likelihood.'''
self._m_alpha()
self._m_eta()
def beta(self, stats=None):
'''Per-topic word distributions as a (num_topics, vocab_size) array.
:param stats: Optionally specify stats, otherwise use model stats
'''
if stats is None:
stats = self.stats
result = stats['nkw'] + self.eta
result = np.divide(result, result.sum(1)[:,np.newaxis])
return result
def theta(self, stats=None):
'''Per-document topic distributions as a (num_docs, vocab_size) array.
:param stats: Optionally specify stats, otherwise use model stats
'''
if stats is None:
stats = self.stats
result = stats['nmk'] + self.alpha
result = np.divide(result, result.sum(1)[:,np.newaxis])
return result
def query(self, corpus):
'''Find topic distributions for new documents based on trained model.
:param corpus: new documents as (num_docs, vocab_size) array
:return: topic statistics for new documents
'''
# Initialize the gibbs sampler for the test corpus
test_stats = self._gibbs_init(corpus)
# Merge training and test stats then burn in and sample
all_stats = merge_query_stats(self.stats, test_stats)
self._gibbs_sample_n(all_stats, self.burn + 1)
# Split test corpus stats back out
test_stats = split_query_stats(self.stats, all_stats)
return test_stats
def perplexity(self, corpus):
'''Estimated (with Gibbs sampling) perplexity of a test corpus.'''
# Heinrich2005 Eq. 94
stats = self.query(corpus)
lik = self.log_likelihood(corpus, stats)
return np.exp(-1 * lik.sum() / stats['nm'].sum())
def log_likelihood(self, corpus, stats):
'''Log-likeliehood of generating a test corpus with the given corpus.'''
# Heinrich2005 Eq. 96
# Get per-topic word distribution for model
beta = np.matrix(self.beta())
# Get per-document topic distribution for test corpus
theta = np.matrix(self.theta(stats))
lik = np.multiply(np.log(np.array(theta*beta)), corpus).sum(1)
return lik
def _gibbs_init(self, corpus):
'''Initialize Gibbs sampling by assigning a random topic to each word in
the corpus.
:param corpus: corpus[m][w] is the count for word w in document m
:param skip: skip initialization for first skip docs, default 0
:returns: statistics dict with the following keys:
nmk: document-topic count, nmk[m][k] is for document m, topic k
nm: document-topic sum, nm[m] is the number of words in document m
nkw: topic-term count, nkw[k][w] is for word w in topic k
nk: topic-term sum, nk[k] is the count of topic k in corpus
n: total number of words
topics: list of pairs (m, i) giving the topic for each word
'''
num_docs, num_words = corpus.shape
# Initialize stats
stats = {
'nmk': np.zeros((num_docs, self.num_topics))
, 'nm': np.zeros(num_docs)
, 'nkw': np.zeros((self.num_topics, num_words))
, 'nk': np.zeros(self.num_topics)
, 'topics': {}
}
for m in xrange(num_docs):
for i, w in enumerate(word_iter(corpus[m,:])):
# Sample topic from uniform distribution
k = nprand.randint(0, self.num_topics)
stats['nmk'][m][k] += 1
stats['nm'][m] += 1
stats['nkw'][k][w] += 1
stats['nk'][k] += 1
stats['topics'][(m, i)] = (w, k)
psi = spspecial.psi
stats['nlogtheta'] = psi(self.alpha + stats['nmk'])
stats['nlogtheta'] -= psi(self.alpha.sum() + stats['nm'])[:,np.newaxis]
stats['nlogbeta'] = psi(self.eta + stats['nkw'])
stats['nlogbeta'] -= psi(self.eta.sum() + stats['nk'])[:,np.newaxis]
return stats
def _gibbs_sample(self, stats):
'''Resample topics for each word using Gibbs sampling, with lag.
:param stats: statistics returned by _gibbs_init(), will be modified.
'''
self._gibbs_sample_n(stats, self.lag + 1)
def _gibbs_sample_n(self, stats, n):
'''Call _gibbs_sample_one() n times.'''
for i in range(n):
self._gibbs_sample_one(stats)
def _gibbs_sample_one(self, stats):
'''Resample topics for each word using Gibbs sampling, without lag.
:param stats: statistics returned by _gibbs_init(), will be modified.
'''
# Shuffle topic assignments
topics = stats['topics'].keys()
nprand.shuffle(topics)
# Resample each one
for m, i in topics:
# Remove doc m, word i from stats
w, k = stats['topics'][(m, i)]
stats['nmk'][m][k] -= 1
stats['nm'][m] -= 1
stats['nkw'][k][w] -= 1
stats['nk'][k] -= 1
# Sample from conditional
k = sample(self.topic_conditional(m, w, stats))
# Add new topic to stats
stats['nmk'][m][k] += 1
stats['nm'][m] += 1
stats['nkw'][k][w] += 1
stats['nk'][k] += 1
stats['topics'][(m, i)] = (w, k)
psi = spspecial.psi
stats['nlogtheta'] = psi(self.alpha + stats['nmk'])
stats['nlogtheta'] -= psi(self.alpha.sum() + stats['nm'])[:,np.newaxis]
stats['nlogbeta'] = psi(self.eta + stats['nkw'])
stats['nlogbeta'] -= psi(self.eta.sum() + stats['nk'])[:,np.newaxis]
def _m_alpha(self):
'''Find a new estimate for alpha that maximizes likelihood.
:param iter: The number of iterations to perform, defaults to 5
'''
nlogtheta = self.stats['nlogtheta']
self.alpha = estimate_dirichlet_newton(self.alpha, nlogtheta)
def _m_eta(self):
'''Find a new estimate for alpha that maximizes likelihood.
:param iter: The number of iterations to perform, defaults to 5
'''
nlogbeta = self.stats['nlogbeta']
self.eta = estimate_dirichlet_newton(self.eta, nlogbeta)
def expected_log_likelihood(self):
'''Expected (p(theta,beta|gibbs_z)) complete log likelihood.'''
stats = self.stats
psi = spspecial.psi
num_topics = stats['nkw'].shape[0]
num_docs = stats['nmk'].shape[0]
# Virtual word and topic counts
vmk = self.alpha + stats['nmk']
vkw = self.eta + stats['nkw']
# Calculate likelihood
lik = 0
lik += (stats['nlogtheta'] * (vmk - 1)).sum()
lik += (stats['nlogbeta'] * (vkw - 1)).sum()
lik -= num_docs * log_multinomial_beta(self.alpha)
lik -= num_topics * log_multinomial_beta(self.eta)
return lik
def log_likelihood_wz(self):
'''The log likelihood of the data and topic assignments.'''
# Heinrich2005 Eq. 73
num_docs = self.stats['nmk'].shape[0]
lik = 0
lik += log_multinomial_beta(self.stats['nkw'] + self.eta).sum()
lik -= self.num_topics * log_multinomial_beta(self.eta)
lik += log_multinomial_beta(self.stats['nmk'] + self.alpha).sum()
lik -= num_docs * log_multinomial_beta(self.alpha)
return lik
def expected_log_likelihood_components(self):
'''Expected (p(theta,beta|gibbs_z)) complete log likelihood.'''
stats = self.stats
psi = spspecial.psi
num_topics = stats['nkw'].shape[0]
num_docs = stats['nmk'].shape[0]
# Virtual word and topic counts
vmk = self.alpha + stats['nmk']
vkw = self.eta + stats['nkw']
# Calculate likelihood
lik = np.array([
(stats['nlogtheta'] * (vmk - 1)).sum()
, (stats['nlogbeta'] * (vkw - 1)).sum()
, num_docs * log_multinomial_beta(self.alpha)
, num_topics * log_multinomial_beta(self.eta)
])
return lik
def topic_conditional(self, m, w, stats):
'''Distribution of a single topic given others and words.
:param m: index of the document to sample for
:param w: word associated with the topic being sampled
:param stats: count statistics (with topic being sampled removed)
:returns: a (num_topics) length vector of topic probabilities
'''
pk = stats['nkw'][:,w] + self.eta[w]
pk = np.multiply(pk, stats['nmk'][m,:] + self.alpha)
pk = np.divide(pk, stats['nk'] + self.eta.sum())
# Normalize
pk /= pk.sum()
return pk | {
"content_hash": "abcdeac954f347de73b6014a4f237336",
"timestamp": "",
"source": "github",
"line_count": 387,
"max_line_length": 98,
"avg_line_length": 39.343669250645995,
"alnum_prop": 0.574412189675555,
"repo_name": "elplatt/lda-gibbs-em",
"id": "449bbcd7deb5d015d4c2a37e715c03821d688817",
"size": "15226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lda.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "32758"
}
],
"symlink_target": ""
} |
"""Component to interface with cameras."""
import asyncio
import base64
import collections
from contextlib import suppress
from datetime import timedelta
import logging
import hashlib
from random import SystemRandom
import attr
from aiohttp import web
import async_timeout
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, \
SERVICE_TURN_ON, CONF_FILENAME
from homeassistant.exceptions import HomeAssistantError
from homeassistant.loader import bind_hass
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.config_validation import ( # noqa
PLATFORM_SCHEMA, PLATFORM_SCHEMA_BASE)
from homeassistant.components.http import HomeAssistantView, KEY_AUTHENTICATED
from homeassistant.components.media_player.const import (
ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE,
SERVICE_PLAY_MEDIA, DOMAIN as DOMAIN_MP)
from homeassistant.components.stream import request_stream
from homeassistant.components.stream.const import (
OUTPUT_FORMATS, FORMAT_CONTENT_TYPE, CONF_STREAM_SOURCE, CONF_LOOKBACK,
CONF_DURATION, SERVICE_RECORD, DOMAIN as DOMAIN_STREAM)
from homeassistant.components import websocket_api
import homeassistant.helpers.config_validation as cv
from homeassistant.setup import async_when_setup
from .const import DOMAIN, DATA_CAMERA_PREFS
from .prefs import CameraPreferences
_LOGGER = logging.getLogger(__name__)
SERVICE_ENABLE_MOTION = 'enable_motion_detection'
SERVICE_DISABLE_MOTION = 'disable_motion_detection'
SERVICE_SNAPSHOT = 'snapshot'
SERVICE_PLAY_STREAM = 'play_stream'
SCAN_INTERVAL = timedelta(seconds=30)
ENTITY_ID_FORMAT = DOMAIN + '.{}'
ATTR_FILENAME = 'filename'
ATTR_MEDIA_PLAYER = 'media_player'
ATTR_FORMAT = 'format'
STATE_RECORDING = 'recording'
STATE_STREAMING = 'streaming'
STATE_IDLE = 'idle'
# Bitfield of features supported by the camera entity
SUPPORT_ON_OFF = 1
SUPPORT_STREAM = 2
DEFAULT_CONTENT_TYPE = 'image/jpeg'
ENTITY_IMAGE_URL = '/api/camera_proxy/{0}?token={1}'
TOKEN_CHANGE_INTERVAL = timedelta(minutes=5)
_RND = SystemRandom()
MIN_STREAM_INTERVAL = 0.5 # seconds
CAMERA_SERVICE_SCHEMA = vol.Schema({
vol.Optional(ATTR_ENTITY_ID): cv.comp_entity_ids,
})
CAMERA_SERVICE_SNAPSHOT = CAMERA_SERVICE_SCHEMA.extend({
vol.Required(ATTR_FILENAME): cv.template
})
CAMERA_SERVICE_PLAY_STREAM = CAMERA_SERVICE_SCHEMA.extend({
vol.Required(ATTR_MEDIA_PLAYER): cv.entities_domain(DOMAIN_MP),
vol.Optional(ATTR_FORMAT, default='hls'): vol.In(OUTPUT_FORMATS),
})
CAMERA_SERVICE_RECORD = CAMERA_SERVICE_SCHEMA.extend({
vol.Required(CONF_FILENAME): cv.template,
vol.Optional(CONF_DURATION, default=30): vol.Coerce(int),
vol.Optional(CONF_LOOKBACK, default=0): vol.Coerce(int),
})
WS_TYPE_CAMERA_THUMBNAIL = 'camera_thumbnail'
SCHEMA_WS_CAMERA_THUMBNAIL = websocket_api.BASE_COMMAND_MESSAGE_SCHEMA.extend({
vol.Required('type'): WS_TYPE_CAMERA_THUMBNAIL,
vol.Required('entity_id'): cv.entity_id
})
@attr.s
class Image:
"""Represent an image."""
content_type = attr.ib(type=str)
content = attr.ib(type=bytes)
@bind_hass
async def async_request_stream(hass, entity_id, fmt):
"""Request a stream for a camera entity."""
camera = _get_camera_from_entity_id(hass, entity_id)
camera_prefs = hass.data[DATA_CAMERA_PREFS].get(entity_id)
if not camera.stream_source:
raise HomeAssistantError("{} does not support play stream service"
.format(camera.entity_id))
return request_stream(hass, camera.stream_source, fmt=fmt,
keepalive=camera_prefs.preload_stream)
@bind_hass
async def async_get_image(hass, entity_id, timeout=10):
"""Fetch an image from a camera entity."""
camera = _get_camera_from_entity_id(hass, entity_id)
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
with async_timeout.timeout(timeout, loop=hass.loop):
image = await camera.async_camera_image()
if image:
return Image(camera.content_type, image)
raise HomeAssistantError('Unable to get image')
@bind_hass
async def async_get_mjpeg_stream(hass, request, entity_id):
"""Fetch an mjpeg stream from a camera entity."""
camera = _get_camera_from_entity_id(hass, entity_id)
return await camera.handle_async_mjpeg_stream(request)
async def async_get_still_stream(request, image_cb, content_type, interval):
"""Generate an HTTP MJPEG stream from camera images.
This method must be run in the event loop.
"""
response = web.StreamResponse()
response.content_type = ('multipart/x-mixed-replace; '
'boundary=--frameboundary')
await response.prepare(request)
async def write_to_mjpeg_stream(img_bytes):
"""Write image to stream."""
await response.write(bytes(
'--frameboundary\r\n'
'Content-Type: {}\r\n'
'Content-Length: {}\r\n\r\n'.format(
content_type, len(img_bytes)),
'utf-8') + img_bytes + b'\r\n')
last_image = None
while True:
img_bytes = await image_cb()
if not img_bytes:
break
if img_bytes != last_image:
await write_to_mjpeg_stream(img_bytes)
# Chrome seems to always ignore first picture,
# print it twice.
if last_image is None:
await write_to_mjpeg_stream(img_bytes)
last_image = img_bytes
await asyncio.sleep(interval)
return response
def _get_camera_from_entity_id(hass, entity_id):
"""Get camera component from entity_id."""
component = hass.data.get(DOMAIN)
if component is None:
raise HomeAssistantError('Camera component not set up')
camera = component.get_entity(entity_id)
if camera is None:
raise HomeAssistantError('Camera not found')
if not camera.is_on:
raise HomeAssistantError('Camera is off')
return camera
async def async_setup(hass, config):
"""Set up the camera component."""
component = hass.data[DOMAIN] = \
EntityComponent(_LOGGER, DOMAIN, hass, SCAN_INTERVAL)
prefs = CameraPreferences(hass)
await prefs.async_initialize()
hass.data[DATA_CAMERA_PREFS] = prefs
hass.http.register_view(CameraImageView(component))
hass.http.register_view(CameraMjpegStream(component))
hass.components.websocket_api.async_register_command(
WS_TYPE_CAMERA_THUMBNAIL, websocket_camera_thumbnail,
SCHEMA_WS_CAMERA_THUMBNAIL
)
hass.components.websocket_api.async_register_command(ws_camera_stream)
hass.components.websocket_api.async_register_command(websocket_get_prefs)
hass.components.websocket_api.async_register_command(
websocket_update_prefs)
await component.async_setup(config)
async def preload_stream(hass, _):
for camera in component.entities:
camera_prefs = prefs.get(camera.entity_id)
if camera.stream_source and camera_prefs.preload_stream:
request_stream(hass, camera.stream_source, keepalive=True)
async_when_setup(hass, DOMAIN_STREAM, preload_stream)
@callback
def update_tokens(time):
"""Update tokens of the entities."""
for entity in component.entities:
entity.async_update_token()
hass.async_create_task(entity.async_update_ha_state())
hass.helpers.event.async_track_time_interval(
update_tokens, TOKEN_CHANGE_INTERVAL)
component.async_register_entity_service(
SERVICE_ENABLE_MOTION, CAMERA_SERVICE_SCHEMA,
'async_enable_motion_detection'
)
component.async_register_entity_service(
SERVICE_DISABLE_MOTION, CAMERA_SERVICE_SCHEMA,
'async_disable_motion_detection'
)
component.async_register_entity_service(
SERVICE_TURN_OFF, CAMERA_SERVICE_SCHEMA,
'async_turn_off'
)
component.async_register_entity_service(
SERVICE_TURN_ON, CAMERA_SERVICE_SCHEMA,
'async_turn_on'
)
component.async_register_entity_service(
SERVICE_SNAPSHOT, CAMERA_SERVICE_SNAPSHOT,
async_handle_snapshot_service
)
component.async_register_entity_service(
SERVICE_PLAY_STREAM, CAMERA_SERVICE_PLAY_STREAM,
async_handle_play_stream_service
)
component.async_register_entity_service(
SERVICE_RECORD, CAMERA_SERVICE_RECORD,
async_handle_record_service
)
return True
async def async_setup_entry(hass, entry):
"""Set up a config entry."""
return await hass.data[DOMAIN].async_setup_entry(entry)
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
return await hass.data[DOMAIN].async_unload_entry(entry)
class Camera(Entity):
"""The base class for camera entities."""
def __init__(self):
"""Initialize a camera."""
self.is_streaming = False
self.content_type = DEFAULT_CONTENT_TYPE
self.access_tokens = collections.deque([], 2)
self.async_update_token()
@property
def should_poll(self):
"""No need to poll cameras."""
return False
@property
def entity_picture(self):
"""Return a link to the camera feed as entity picture."""
return ENTITY_IMAGE_URL.format(self.entity_id, self.access_tokens[-1])
@property
def supported_features(self):
"""Flag supported features."""
return 0
@property
def is_recording(self):
"""Return true if the device is recording."""
return False
@property
def brand(self):
"""Return the camera brand."""
return None
@property
def motion_detection_enabled(self):
"""Return the camera motion detection status."""
return None
@property
def model(self):
"""Return the camera model."""
return None
@property
def frame_interval(self):
"""Return the interval between frames of the mjpeg stream."""
return 0.5
@property
def stream_source(self):
"""Return the source of the stream."""
return None
def camera_image(self):
"""Return bytes of camera image."""
raise NotImplementedError()
@callback
def async_camera_image(self):
"""Return bytes of camera image.
This method must be run in the event loop and returns a coroutine.
"""
return self.hass.async_add_job(self.camera_image)
async def handle_async_still_stream(self, request, interval):
"""Generate an HTTP MJPEG stream from camera images.
This method must be run in the event loop.
"""
return await async_get_still_stream(request, self.async_camera_image,
self.content_type, interval)
async def handle_async_mjpeg_stream(self, request):
"""Serve an HTTP MJPEG stream from the camera.
This method can be overridden by camera plaforms to proxy
a direct stream from the camera.
This method must be run in the event loop.
"""
return await self.handle_async_still_stream(
request, self.frame_interval)
@property
def state(self):
"""Return the camera state."""
if self.is_recording:
return STATE_RECORDING
if self.is_streaming:
return STATE_STREAMING
return STATE_IDLE
@property
def is_on(self):
"""Return true if on."""
return True
def turn_off(self):
"""Turn off camera."""
raise NotImplementedError()
@callback
def async_turn_off(self):
"""Turn off camera."""
return self.hass.async_add_job(self.turn_off)
def turn_on(self):
"""Turn off camera."""
raise NotImplementedError()
@callback
def async_turn_on(self):
"""Turn off camera."""
return self.hass.async_add_job(self.turn_on)
def enable_motion_detection(self):
"""Enable motion detection in the camera."""
raise NotImplementedError()
@callback
def async_enable_motion_detection(self):
"""Call the job and enable motion detection."""
return self.hass.async_add_job(self.enable_motion_detection)
def disable_motion_detection(self):
"""Disable motion detection in camera."""
raise NotImplementedError()
@callback
def async_disable_motion_detection(self):
"""Call the job and disable motion detection."""
return self.hass.async_add_job(self.disable_motion_detection)
@property
def state_attributes(self):
"""Return the camera state attributes."""
attrs = {
'access_token': self.access_tokens[-1],
}
if self.model:
attrs['model_name'] = self.model
if self.brand:
attrs['brand'] = self.brand
if self.motion_detection_enabled:
attrs['motion_detection'] = self.motion_detection_enabled
return attrs
@callback
def async_update_token(self):
"""Update the used token."""
self.access_tokens.append(
hashlib.sha256(
_RND.getrandbits(256).to_bytes(32, 'little')).hexdigest())
class CameraView(HomeAssistantView):
"""Base CameraView."""
requires_auth = False
def __init__(self, component):
"""Initialize a basic camera view."""
self.component = component
async def get(self, request, entity_id):
"""Start a GET request."""
camera = self.component.get_entity(entity_id)
if camera is None:
raise web.HTTPNotFound()
authenticated = (request[KEY_AUTHENTICATED] or
request.query.get('token') in camera.access_tokens)
if not authenticated:
raise web.HTTPUnauthorized()
if not camera.is_on:
_LOGGER.debug('Camera is off.')
raise web.HTTPServiceUnavailable()
return await self.handle(request, camera)
async def handle(self, request, camera):
"""Handle the camera request."""
raise NotImplementedError()
class CameraImageView(CameraView):
"""Camera view to serve an image."""
url = '/api/camera_proxy/{entity_id}'
name = 'api:camera:image'
async def handle(self, request, camera):
"""Serve camera image."""
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
with async_timeout.timeout(10, loop=request.app['hass'].loop):
image = await camera.async_camera_image()
if image:
return web.Response(body=image,
content_type=camera.content_type)
raise web.HTTPInternalServerError()
class CameraMjpegStream(CameraView):
"""Camera View to serve an MJPEG stream."""
url = '/api/camera_proxy_stream/{entity_id}'
name = 'api:camera:stream'
async def handle(self, request, camera):
"""Serve camera stream, possibly with interval."""
interval = request.query.get('interval')
if interval is None:
return await camera.handle_async_mjpeg_stream(request)
try:
# Compose camera stream from stills
interval = float(request.query.get('interval'))
if interval < MIN_STREAM_INTERVAL:
raise ValueError("Stream interval must be be > {}"
.format(MIN_STREAM_INTERVAL))
return await camera.handle_async_still_stream(request, interval)
except ValueError:
raise web.HTTPBadRequest()
@websocket_api.async_response
async def websocket_camera_thumbnail(hass, connection, msg):
"""Handle get camera thumbnail websocket command.
Async friendly.
"""
try:
image = await async_get_image(hass, msg['entity_id'])
connection.send_message(websocket_api.result_message(
msg['id'], {
'content_type': image.content_type,
'content': base64.b64encode(image.content).decode('utf-8')
}
))
except HomeAssistantError:
connection.send_message(websocket_api.error_message(
msg['id'], 'image_fetch_failed', 'Unable to fetch image'))
@websocket_api.async_response
@websocket_api.websocket_command({
vol.Required('type'): 'camera/stream',
vol.Required('entity_id'): cv.entity_id,
vol.Optional('format', default='hls'): vol.In(OUTPUT_FORMATS),
})
async def ws_camera_stream(hass, connection, msg):
"""Handle get camera stream websocket command.
Async friendly.
"""
try:
entity_id = msg['entity_id']
camera = _get_camera_from_entity_id(hass, entity_id)
camera_prefs = hass.data[DATA_CAMERA_PREFS].get(entity_id)
if not camera.stream_source:
raise HomeAssistantError("{} does not support play stream service"
.format(camera.entity_id))
fmt = msg['format']
url = request_stream(hass, camera.stream_source, fmt=fmt,
keepalive=camera_prefs.preload_stream)
connection.send_result(msg['id'], {'url': url})
except HomeAssistantError as ex:
_LOGGER.error(ex)
connection.send_error(
msg['id'], 'start_stream_failed', str(ex))
@websocket_api.async_response
@websocket_api.websocket_command({
vol.Required('type'): 'camera/get_prefs',
vol.Required('entity_id'): cv.entity_id,
})
async def websocket_get_prefs(hass, connection, msg):
"""Handle request for account info."""
prefs = hass.data[DATA_CAMERA_PREFS].get(msg['entity_id'])
connection.send_result(msg['id'], prefs.as_dict())
@websocket_api.async_response
@websocket_api.websocket_command({
vol.Required('type'): 'camera/update_prefs',
vol.Required('entity_id'): cv.entity_id,
vol.Optional('preload_stream'): bool,
})
async def websocket_update_prefs(hass, connection, msg):
"""Handle request for account info."""
prefs = hass.data[DATA_CAMERA_PREFS]
changes = dict(msg)
changes.pop('id')
changes.pop('type')
entity_id = changes.pop('entity_id')
await prefs.async_update(entity_id, **changes)
connection.send_result(msg['id'], prefs.get(entity_id).as_dict())
async def async_handle_snapshot_service(camera, service):
"""Handle snapshot services calls."""
hass = camera.hass
filename = service.data[ATTR_FILENAME]
filename.hass = hass
snapshot_file = filename.async_render(
variables={ATTR_ENTITY_ID: camera})
# check if we allow to access to that file
if not hass.config.is_allowed_path(snapshot_file):
_LOGGER.error(
"Can't write %s, no access to path!", snapshot_file)
return
image = await camera.async_camera_image()
def _write_image(to_file, image_data):
"""Executor helper to write image."""
with open(to_file, 'wb') as img_file:
img_file.write(image_data)
try:
await hass.async_add_executor_job(
_write_image, snapshot_file, image)
except OSError as err:
_LOGGER.error("Can't write image to file: %s", err)
async def async_handle_play_stream_service(camera, service_call):
"""Handle play stream services calls."""
if not camera.stream_source:
raise HomeAssistantError("{} does not support play stream service"
.format(camera.entity_id))
hass = camera.hass
camera_prefs = hass.data[DATA_CAMERA_PREFS].get(camera.entity_id)
fmt = service_call.data[ATTR_FORMAT]
entity_ids = service_call.data[ATTR_MEDIA_PLAYER]
url = request_stream(hass, camera.stream_source, fmt=fmt,
keepalive=camera_prefs.preload_stream)
data = {
ATTR_ENTITY_ID: entity_ids,
ATTR_MEDIA_CONTENT_ID: "{}{}".format(hass.config.api.base_url, url),
ATTR_MEDIA_CONTENT_TYPE: FORMAT_CONTENT_TYPE[fmt]
}
await hass.services.async_call(
DOMAIN_MP, SERVICE_PLAY_MEDIA, data,
blocking=True, context=service_call.context)
async def async_handle_record_service(camera, call):
"""Handle stream recording service calls."""
if not camera.stream_source:
raise HomeAssistantError("{} does not support record service"
.format(camera.entity_id))
hass = camera.hass
filename = call.data[CONF_FILENAME]
filename.hass = hass
video_path = filename.async_render(
variables={ATTR_ENTITY_ID: camera})
data = {
CONF_STREAM_SOURCE: camera.stream_source,
CONF_FILENAME: video_path,
CONF_DURATION: call.data[CONF_DURATION],
CONF_LOOKBACK: call.data[CONF_LOOKBACK],
}
await hass.services.async_call(
DOMAIN_STREAM, SERVICE_RECORD, data,
blocking=True, context=call.context)
| {
"content_hash": "f6491b9b724b68b74c850cde92d407ed",
"timestamp": "",
"source": "github",
"line_count": 670,
"max_line_length": 79,
"avg_line_length": 31.426865671641792,
"alnum_prop": 0.6478438449848024,
"repo_name": "MartinHjelmare/home-assistant",
"id": "7a37dffe3b8263b1f705a3784f9ca64cb45ced4b",
"size": "21056",
"binary": false,
"copies": "5",
"ref": "refs/heads/dev",
"path": "homeassistant/components/camera/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1175"
},
{
"name": "Dockerfile",
"bytes": "1081"
},
{
"name": "Python",
"bytes": "15222591"
},
{
"name": "Ruby",
"bytes": "745"
},
{
"name": "Shell",
"bytes": "17609"
}
],
"symlink_target": ""
} |
import os
from tempfile import mkdtemp
from unittest import TestCase
from warnings import catch_warnings
from .mock import Mock
from testfixtures import (
TempDirectory, Replacer, ShouldRaise, compare, OutputCapture
)
from ..compat import Unicode, PY3
from ..rmtree import rmtree
if PY3:
some_bytes = '\xa3'.encode('utf-8')
some_text = '\xa3'
else:
some_bytes = '\xc2\xa3'
some_text = '\xc2\xa3'.decode('utf-8')
class TestTempDirectory(TestCase):
def test_cleanup(self):
d = TempDirectory()
p = d.path
assert os.path.exists(p) is True
p = d.write('something', b'stuff')
d.cleanup()
assert os.path.exists(p) is False
def test_cleanup_all(self):
d1 = TempDirectory()
d2 = TempDirectory()
assert os.path.exists(d1.path) is True
p1 = d1.path
assert os.path.exists(d2.path) is True
p2 = d2.path
TempDirectory.cleanup_all()
assert os.path.exists(p1) is False
assert os.path.exists(p2) is False
def test_with_statement(self):
with TempDirectory() as d:
p = d.path
assert os.path.exists(p) is True
d.write('something', b'stuff')
assert os.listdir(p) == ['something']
with open(os.path.join(p, 'something')) as f:
assert f.read() == 'stuff'
assert os.path.exists(p) is False
def test_listdir_sort(self): # pragma: no branch
with TempDirectory() as d:
d.write('ga', b'')
d.write('foo1', b'')
d.write('Foo2', b'')
d.write('g.o', b'')
with OutputCapture() as output:
d.listdir()
output.compare('Foo2\nfoo1\ng.o\nga')
class TempDirectoryTests(TestCase):
def test_write_with_slash_at_start(self):
with TempDirectory() as d:
with ShouldRaise(ValueError(
'Attempt to read or write outside the temporary Directory'
)):
d.write('/some/folder', 'stuff')
def test_makedir_with_slash_at_start(self):
with TempDirectory() as d:
with ShouldRaise(ValueError(
'Attempt to read or write outside the temporary Directory'
)):
d.makedir('/some/folder')
def test_read_with_slash_at_start(self):
with TempDirectory() as d:
with ShouldRaise(ValueError(
'Attempt to read or write outside the temporary Directory'
)):
d.read('/some/folder')
def test_listdir_with_slash_at_start(self):
with TempDirectory() as d:
with ShouldRaise(ValueError(
'Attempt to read or write outside the temporary Directory'
)):
d.listdir('/some/folder')
def test_compare_with_slash_at_start(self):
with TempDirectory() as d:
with ShouldRaise(ValueError(
'Attempt to read or write outside the temporary Directory'
)):
d.compare((), path='/some/folder')
def test_read_with_slash_at_start_ok(self):
with TempDirectory() as d:
path = d.write('foo', b'bar')
compare(d.read(path), b'bar')
def test_dont_cleanup_with_path(self):
d = mkdtemp()
fp = os.path.join(d, 'test')
with open(fp, 'w') as f:
f.write('foo')
try:
td = TempDirectory(path=d)
self.assertEqual(d, td.path)
td.cleanup()
# checks
self.assertEqual(os.listdir(d), ['test'])
with open(fp) as f:
self.assertEqual(f.read(), 'foo')
finally:
rmtree(d)
def test_dont_create_with_path(self):
d = mkdtemp()
rmtree(d)
td = TempDirectory(path=d)
self.assertEqual(d, td.path)
self.failIf(os.path.exists(d))
def test_deprecated_check(self):
with TempDirectory() as d:
d.write('x', b'')
d.check('x')
def test_deprecated_check_dir(self):
with TempDirectory() as d:
d.write('foo/x', b'')
d.check_dir('foo', 'x')
def test_deprecated_check_all(self):
with TempDirectory() as d:
d.write('a/b/c', b'')
d.check_all('', 'a/', 'a/b/', 'a/b/c')
d.check_all('a', 'b/', 'b/c')
def test_compare_sort_actual(self):
with TempDirectory() as d:
d.write('ga', b'')
d.write('foo1', b'')
d.write('Foo2', b'')
d.write('g.o', b'')
d.compare(['Foo2', 'foo1', 'g.o', 'ga'])
def test_compare_sort_expected(self):
with TempDirectory() as d:
d.write('ga', b'')
d.write('foo1', b'')
d.write('Foo2', b'')
d.write('g.o', b'')
d.compare(['Foo2', 'ga', 'foo1', 'g.o'])
def test_compare_path_tuple(self):
with TempDirectory() as d:
d.write('a/b/c', b'')
d.compare(path=('a', 'b'),
expected=['c'])
def test_recursive_ignore(self):
with TempDirectory(ignore=['.svn']) as d:
d.write('.svn/rubbish', b'')
d.write('a/.svn/rubbish', b'')
d.write('a/b/.svn', b'')
d.write('a/b/c', b'')
d.write('a/d/.svn/rubbish', b'')
d.compare([
'a/',
'a/b/',
'a/b/c',
'a/d/',
])
def test_files_only(self):
with TempDirectory() as d:
d.write('a/b/c', b'')
d.compare(['a/b/c'], files_only=True)
def test_path(self):
with TempDirectory() as d:
expected1 = d.makedir('foo')
expected2 = d.write('baz/bob', b'')
expected3 = d.getpath('a/b/c')
actual1 = d.getpath('foo')
actual2 = d.getpath('baz/bob')
actual3 = d.getpath(('a', 'b', 'c'))
self.assertEqual(expected1, actual1)
self.assertEqual(expected2, actual2)
self.assertEqual(expected3, actual3)
def test_atexit(self):
# http://bugs.python.org/issue25532
from .mock import call
m = Mock()
with Replacer() as r:
# make sure the marker is false, other tests will
# probably have set it
r.replace('testfixtures.TempDirectory.atexit_setup', False)
r.replace('atexit.register', m.register)
d = TempDirectory()
expected = [call.register(d.atexit)]
compare(expected, m.mock_calls)
with catch_warnings(record=True) as w:
d.atexit()
self.assertTrue(len(w), 1)
compare(str(w[0].message), ( # pragma: no branch
"TempDirectory instances not cleaned up by shutdown:\n" +
d.path
))
d.cleanup()
compare(set(), TempDirectory.instances)
# check re-running has no ill effects
d.atexit()
def test_read_decode(self):
with TempDirectory() as d:
with open(os.path.join(d.path, 'test.file'), 'wb') as f:
f.write(b'\xc2\xa3')
compare(d.read('test.file', 'utf8'), some_text)
def test_read_no_decode(self):
with TempDirectory() as d:
with open(os.path.join(d.path, 'test.file'), 'wb') as f:
f.write(b'\xc2\xa3')
compare(d.read('test.file'), b'\xc2\xa3')
def test_write_bytes(self):
with TempDirectory() as d:
d.write('test.file', b'\xc2\xa3')
with open(os.path.join(d.path, 'test.file'), 'rb') as f:
compare(f.read(), b'\xc2\xa3')
def test_write_unicode(self):
with TempDirectory() as d:
d.write('test.file', some_text, 'utf8')
with open(os.path.join(d.path, 'test.file'), 'rb') as f:
compare(f.read(), b'\xc2\xa3')
def test_write_unicode_bad(self):
if PY3:
expected = TypeError(
"a bytes-like object is required, not 'str'"
)
else:
expected = UnicodeDecodeError(
'ascii', '\xa3', 0, 1, 'ordinal not in range(128)'
)
with TempDirectory() as d:
with ShouldRaise(expected):
d.write('test.file', Unicode('\xa3'))
def test_just_empty_non_recursive(self):
with TempDirectory() as d:
d.makedir('foo/bar')
d.makedir('foo/baz')
d.compare(path='foo',
expected=['bar', 'baz'],
recursive=False)
def test_just_empty_dirs(self):
with TempDirectory() as d:
d.makedir('foo/bar')
d.makedir('foo/baz')
d.compare(['foo/', 'foo/bar/', 'foo/baz/'])
def test_symlink(self):
with TempDirectory() as d:
d.write('foo/bar.txt', b'x')
os.symlink(d.getpath('foo'), d.getpath('baz'))
d.compare(['baz/', 'foo/', 'foo/bar.txt'])
def test_follow_symlinks(self):
with TempDirectory() as d:
d.write('foo/bar.txt', b'x')
os.symlink(d.getpath('foo'), d.getpath('baz'))
d.compare(['baz/', 'baz/bar.txt', 'foo/', 'foo/bar.txt'],
followlinks=True)
def test_trailing_slash(self):
with TempDirectory() as d:
d.write('source/foo/bar.txt', b'x')
d.compare(path='source/', expected=['foo/', 'foo/bar.txt'])
def test_default_encoding(self):
encoded = b'\xc2\xa3'
decoded = encoded.decode('utf-8')
with TempDirectory(encoding='utf-8') as d:
d.write('test.txt', decoded)
compare(d.read('test.txt'), expected=decoded)
def test_override_default_encoding(self):
encoded = b'\xc2\xa3'
decoded = encoded.decode('utf-8')
with TempDirectory(encoding='ascii') as d:
d.write('test.txt', decoded, encoding='utf-8')
compare(d.read('test.txt', encoding='utf-8'), expected=decoded)
| {
"content_hash": "88933babafbff48c288156a75d4577f9",
"timestamp": "",
"source": "github",
"line_count": 316,
"max_line_length": 78,
"avg_line_length": 32.49683544303797,
"alnum_prop": 0.5127081507449606,
"repo_name": "nebulans/testfixtures",
"id": "38147f71ac9f88df6f4fe306c0ad4680aca28d4f",
"size": "10269",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "testfixtures/tests/test_tempdirectory.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "314546"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.