repo_name stringlengths 5 100 | ref stringlengths 12 67 | path stringlengths 4 244 | copies stringlengths 1 8 | content stringlengths 0 1.05M ⌀ |
|---|---|---|---|---|
ramcn/demo3 | refs/heads/master | venv/lib/python3.4/site-packages/django/contrib/messages/api.py | 512 | from django.contrib.messages import constants
from django.contrib.messages.storage import default_storage
from django.http import HttpRequest
__all__ = (
'add_message', 'get_messages',
'get_level', 'set_level',
'debug', 'info', 'success', 'warning', 'error',
'MessageFailure',
)
class MessageFailure(Exception):
pass
def add_message(request, level, message, extra_tags='', fail_silently=False):
"""
Attempts to add a message to the request using the 'messages' app.
"""
if not isinstance(request, HttpRequest):
raise TypeError("add_message() argument must be an HttpRequest object, "
"not '%s'." % request.__class__.__name__)
if hasattr(request, '_messages'):
return request._messages.add(level, message, extra_tags)
if not fail_silently:
raise MessageFailure('You cannot add messages without installing '
'django.contrib.messages.middleware.MessageMiddleware')
def get_messages(request):
"""
Returns the message storage on the request if it exists, otherwise returns
an empty list.
"""
if hasattr(request, '_messages'):
return request._messages
else:
return []
def get_level(request):
"""
Returns the minimum level of messages to be recorded.
The default level is the ``MESSAGE_LEVEL`` setting. If this is not found,
the ``INFO`` level is used.
"""
if hasattr(request, '_messages'):
storage = request._messages
else:
storage = default_storage(request)
return storage.level
def set_level(request, level):
"""
Sets the minimum level of messages to be recorded, returning ``True`` if
the level was recorded successfully.
If set to ``None``, the default level will be used (see the ``get_level``
method).
"""
if not hasattr(request, '_messages'):
return False
request._messages.level = level
return True
def debug(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``DEBUG`` level.
"""
add_message(request, constants.DEBUG, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def info(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``INFO`` level.
"""
add_message(request, constants.INFO, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def success(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``SUCCESS`` level.
"""
add_message(request, constants.SUCCESS, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def warning(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``WARNING`` level.
"""
add_message(request, constants.WARNING, message, extra_tags=extra_tags,
fail_silently=fail_silently)
def error(request, message, extra_tags='', fail_silently=False):
"""
Adds a message with the ``ERROR`` level.
"""
add_message(request, constants.ERROR, message, extra_tags=extra_tags,
fail_silently=fail_silently)
|
a25kk/eda | refs/heads/master | src/eda.sitecontent/eda/sitecontent/browser/__init__.py | 37 | # -*- coding: utf-8 -*-
"""Module providing browser views"""
|
endlessm/chromium-browser | refs/heads/master | third_party/catapult/third_party/WebOb/webob/dec.py | 24 | """
Decorators to wrap functions to make them WSGI applications.
The main decorator :class:`wsgify` turns a function into a WSGI
application (while also allowing normal calling of the method with an
instantiated request).
"""
from webob.compat import (
bytes_,
text_type,
)
from webob.request import Request
from webob.exc import HTTPException
__all__ = ['wsgify']
class wsgify(object):
"""Turns a request-taking, response-returning function into a WSGI
app
You can use this like::
@wsgify
def myfunc(req):
return webob.Response('hey there')
With that ``myfunc`` will be a WSGI application, callable like
``app_iter = myfunc(environ, start_response)``. You can also call
it like normal, e.g., ``resp = myfunc(req)``. (You can also wrap
methods, like ``def myfunc(self, req)``.)
If you raise exceptions from :mod:`webob.exc` they will be turned
into WSGI responses.
There are also several parameters you can use to customize the
decorator. Most notably, you can use a :class:`webob.Request`
subclass, like::
class MyRequest(webob.Request):
@property
def is_local(self):
return self.remote_addr == '127.0.0.1'
@wsgify(RequestClass=MyRequest)
def myfunc(req):
if req.is_local:
return Response('hi!')
else:
raise webob.exc.HTTPForbidden
Another customization you can add is to add `args` (positional
arguments) or `kwargs` (of course, keyword arguments). While
generally not that useful, you can use this to create multiple
WSGI apps from one function, like::
import simplejson
def serve_json(req, json_obj):
return Response(json.dumps(json_obj),
content_type='application/json')
serve_ob1 = wsgify(serve_json, args=(ob1,))
serve_ob2 = wsgify(serve_json, args=(ob2,))
You can return several things from a function:
* A :class:`webob.Response` object (or subclass)
* *Any* WSGI application
* None, and then ``req.response`` will be used (a pre-instantiated
Response object)
* A string, which will be written to ``req.response`` and then that
response will be used.
* Raise an exception from :mod:`webob.exc`
Also see :func:`wsgify.middleware` for a way to make middleware.
You can also subclass this decorator; the most useful things to do
in a subclass would be to change `RequestClass` or override
`call_func` (e.g., to add ``req.urlvars`` as keyword arguments to
the function).
"""
RequestClass = Request
def __init__(self, func=None, RequestClass=None,
args=(), kwargs=None, middleware_wraps=None):
self.func = func
if (RequestClass is not None
and RequestClass is not self.RequestClass):
self.RequestClass = RequestClass
self.args = tuple(args)
if kwargs is None:
kwargs = {}
self.kwargs = kwargs
self.middleware_wraps = middleware_wraps
def __repr__(self):
return '<%s at %s wrapping %r>' % (self.__class__.__name__,
id(self), self.func)
def __get__(self, obj, type=None):
# This handles wrapping methods
if hasattr(self.func, '__get__'):
return self.clone(self.func.__get__(obj, type))
else:
return self
def __call__(self, req, *args, **kw):
"""Call this as a WSGI application or with a request"""
func = self.func
if func is None:
if args or kw:
raise TypeError(
"Unbound %s can only be called with the function it "
"will wrap" % self.__class__.__name__)
func = req
return self.clone(func)
if isinstance(req, dict):
if len(args) != 1 or kw:
raise TypeError(
"Calling %r as a WSGI app with the wrong signature")
environ = req
start_response = args[0]
req = self.RequestClass(environ)
req.response = req.ResponseClass()
try:
args = self.args
if self.middleware_wraps:
args = (self.middleware_wraps,) + args
resp = self.call_func(req, *args, **self.kwargs)
except HTTPException as exc:
resp = exc
if resp is None:
## FIXME: I'm not sure what this should be?
resp = req.response
if isinstance(resp, text_type):
resp = bytes_(resp, req.charset)
if isinstance(resp, bytes):
body = resp
resp = req.response
resp.write(body)
if resp is not req.response:
resp = req.response.merge_cookies(resp)
return resp(environ, start_response)
else:
if self.middleware_wraps:
args = (self.middleware_wraps,) + args
return self.func(req, *args, **kw)
def get(self, url, **kw):
"""Run a GET request on this application, returning a Response.
This creates a request object using the given URL, and any
other keyword arguments are set on the request object (e.g.,
``last_modified=datetime.now()``).
::
resp = myapp.get('/article?id=10')
"""
kw.setdefault('method', 'GET')
req = self.RequestClass.blank(url, **kw)
return self(req)
def post(self, url, POST=None, **kw):
"""Run a POST request on this application, returning a Response.
The second argument (`POST`) can be the request body (a
string), or a dictionary or list of two-tuples, that give the
POST body.
::
resp = myapp.post('/article/new',
dict(title='My Day',
content='I ate a sandwich'))
"""
kw.setdefault('method', 'POST')
req = self.RequestClass.blank(url, POST=POST, **kw)
return self(req)
def request(self, url, **kw):
"""Run a request on this application, returning a Response.
This can be used for DELETE, PUT, etc requests. E.g.::
resp = myapp.request('/article/1', method='PUT', body='New article')
"""
req = self.RequestClass.blank(url, **kw)
return self(req)
def call_func(self, req, *args, **kwargs):
"""Call the wrapped function; override this in a subclass to
change how the function is called."""
return self.func(req, *args, **kwargs)
def clone(self, func=None, **kw):
"""Creates a copy/clone of this object, but with some
parameters rebound
"""
kwargs = {}
if func is not None:
kwargs['func'] = func
if self.RequestClass is not self.__class__.RequestClass:
kwargs['RequestClass'] = self.RequestClass
if self.args:
kwargs['args'] = self.args
if self.kwargs:
kwargs['kwargs'] = self.kwargs
kwargs.update(kw)
return self.__class__(**kwargs)
# To match @decorator:
@property
def undecorated(self):
return self.func
@classmethod
def middleware(cls, middle_func=None, app=None, **kw):
"""Creates middleware
Use this like::
@wsgify.middleware
def restrict_ip(req, app, ips):
if req.remote_addr not in ips:
raise webob.exc.HTTPForbidden('Bad IP: %s' % req.remote_addr)
return app
@wsgify
def app(req):
return 'hi'
wrapped = restrict_ip(app, ips=['127.0.0.1'])
Or if you want to write output-rewriting middleware::
@wsgify.middleware
def all_caps(req, app):
resp = req.get_response(app)
resp.body = resp.body.upper()
return resp
wrapped = all_caps(app)
Note that you must call ``req.get_response(app)`` to get a WebOb
response object. If you are not modifying the output, you can just
return the app.
As you can see, this method doesn't actually create an application, but
creates "middleware" that can be bound to an application, along with
"configuration" (that is, any other keyword arguments you pass when
binding the application).
"""
if middle_func is None:
return _UnboundMiddleware(cls, app, kw)
if app is None:
return _MiddlewareFactory(cls, middle_func, kw)
return cls(middle_func, middleware_wraps=app, kwargs=kw)
class _UnboundMiddleware(object):
"""A `wsgify.middleware` invocation that has not yet wrapped a
middleware function; the intermediate object when you do
something like ``@wsgify.middleware(RequestClass=Foo)``
"""
def __init__(self, wrapper_class, app, kw):
self.wrapper_class = wrapper_class
self.app = app
self.kw = kw
def __repr__(self):
return '<%s at %s wrapping %r>' % (self.__class__.__name__,
id(self), self.app)
def __call__(self, func, app=None):
if app is None:
app = self.app
return self.wrapper_class.middleware(func, app=app, **self.kw)
class _MiddlewareFactory(object):
"""A middleware that has not yet been bound to an application or
configured.
"""
def __init__(self, wrapper_class, middleware, kw):
self.wrapper_class = wrapper_class
self.middleware = middleware
self.kw = kw
def __repr__(self):
return '<%s at %s wrapping %r>' % (self.__class__.__name__, id(self),
self.middleware)
def __call__(self, app, **config):
kw = self.kw.copy()
kw.update(config)
return self.wrapper_class.middleware(self.middleware, app, **kw)
|
shanethehat/sd-agent-plugins | refs/heads/master | ZooKeeper/ZooKeeper.py | 4 | """
Server Density Plugin
ZooKeeper
https://www.serverdensity.com/plugins/ZooKeeper/
https://github.com/serverdensity/sd-agent-plugins/
Version: 1.0.0
"""
import socket
class ZooKeeper(object):
"""Plugin class to manage extracting the data from ZooKeeper
for the sd-agent.
"""
def __init__(self, agent_config, checks_logger, raw_config):
self.agent_config = agent_config
self.checks_logger = checks_logger
self.raw_config = raw_config
self.zookeeper_commands = [
'conf',
'ruok',
'srvr',
'mntr'
]
def run(self):
if 'ZooKeeper' not in self.raw_config:
host = 'localhost'
port = 2181
else:
host = self.raw_config['ZooKeeper'].get(
'host', 'localhost')
port = int(self.raw_config['ZooKeeper'].get(
'port', '2181'))
data = {}
data['imok'] = 1
self.checks_logger.debug('ZooKeeper_plugin: started gathering data')
for command in self.zookeeper_commands:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# set a timeout for socket operation
s.settimeout(4)
s.connect(
(host, port)
)
s.sendall(command)
reply = s.recv(1024)
if command == 'conf':
data = self.convert_conf(data, reply)
elif command == 'ruok':
data = self.convert_ruok(data, reply)
elif command == 'srvr':
data = self.convert_srvr(data, reply)
elif command == 'mntr':
data = self.convert_mntr(data, reply)
del s
except Exception as exception:
self.checks_logger.error(
'ZooKeeper_plugin: failed to read from socket. Error: {0}'
.format(exception.message))
self.checks_logger.debug('ZooKeeper_plugin: completed, returning')
return data
def convert_conf(self, data, reply):
"""
clientPort=2181
dataDir=/usr/local/var/run/zookeeper/data/version-2
dataLogDir=/usr/local/var/run/zookeeper/data/version-2
tickTime=2000
maxClientCnxns=10
minSessionTimeout=4000
maxSessionTimeout=40000
serverId=0
"""
for line in reply.split('\n'):
if not line:
continue
key, value = line.split('=')
if key in ['dataDir', 'dataLogDir']:
continue
data[key] = int(value)
return data
def convert_mntr(self, data, reply):
"""
zk_version 3.4.6-1569965, built on 02/20/2014 09:09 GMT
zk_avg_latency 0
zk_max_latency 751
zk_min_latency 0
zk_packets_received 101850
zk_packets_sent 101916
zk_num_alive_connections 1
zk_outstanding_requests 0
zk_server_state standalone
zk_znode_count 19
zk_watch_count 0
zk_ephemerals_count 0
zk_approximate_data_size 430
zk_open_file_descriptor_count 37
zk_max_file_descriptor_count 10240
"""
data['zk_server_state'] = -1
for line in reply.split('\n'):
if not line:
continue
split_line = line.split('\t')
key = split_line[0]
if key == 'zk_version':
continue
value = split_line[1].split('.')[0]
if key == 'zk_server_state':
if value == 'standalone':
value = 0
elif value == 'leader':
value = 1
elif value == 'follower':
value = 2
data[key] = int(value)
return data
def convert_ruok(self, data, reply):
if reply == 'imok':
data['imok'] = 0
else:
data['imok'] = 1
return data
def convert_srvr(self, data, reply):
"""
Latency min/avg/max: 0/0/0
Received: 52
Sent: 51
Outstanding: 0
Zxid: 0x0
Mode: standalone
Node count: 4
"""
for line in reply.split('\n'):
if not line or line.startswith('Zookeeper version'):
continue
key, value = line.split(':')
if key in ['Mode', 'Zxid']:
continue
if key.startswith('Latency min/avg/max'):
data['latency min'] = int(value.split('/')[0])
data['latency avg'] = int(value.split('/')[1])
data['latency max'] = int(value.split('/')[2])
else:
data[key] = int(value.strip())
return data
if __name__ == "__main__":
"""Standalone test
"""
import logging
import sys
import json
import time
host = '127.0.0.1'
port = 2181
raw_agent_config = {
'ZooKeeper': {
'host': host,
'port': port
}
}
main_checks_logger = logging.getLogger('ZooKeeperPlugin')
main_checks_logger.setLevel(logging.DEBUG)
main_checks_logger.addHandler(logging.StreamHandler(sys.stdout))
zookeeper_check = ZooKeeper({}, main_checks_logger, raw_agent_config)
while True:
try:
result = zookeeper_check.run()
print json.dumps(result, indent=4, sort_keys=True)
except:
main_checks_logger.exception("Unhandled exception")
finally:
time.sleep(60)
|
RealImpactAnalytics/airflow | refs/heads/master | airflow/lineage/backend/atlas/typedefs.py | 22 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
#
operator_typedef = {
"enumDefs": [],
"structDefs": [],
"classificationDefs": [],
"entityDefs": [
{
"superTypes": [
"Process"
],
"name": "airflow_operator",
"description": "Airflow Operator",
"createdBy": "airflow",
"updatedBy": "airflow",
"attributeDefs": [
# "name" will be set to Operator name
# "qualifiedName" will be set to dag_id_task_id@operator_name
{
"name": "dag_id",
"isOptional": False,
"isUnique": False,
"isIndexable": True,
"typeName": "string",
"valuesMaxCount": 1,
"cardinality": "SINGLE",
"valuesMinCount": 0
},
{
"name": "task_id",
"isOptional": False,
"isUnique": False,
"isIndexable": True,
"typeName": "string",
"valuesMaxCount": 1,
"cardinality": "SINGLE",
"valuesMinCount": 0
},
{
"name": "command",
"isOptional": True,
"isUnique": False,
"isIndexable": False,
"typeName": "string",
"valuesMaxCount": 1,
"cardinality": "SINGLE",
"valuesMinCount": 0
},
{
"name": "conn_id",
"isOptional": True,
"isUnique": False,
"isIndexable": False,
"typeName": "string",
"valuesMaxCount": 1,
"cardinality": "SINGLE",
"valuesMinCount": 0
},
{
"name": "execution_date",
"isOptional": False,
"isUnique": False,
"isIndexable": True,
"typeName": "date",
"valuesMaxCount": 1,
"cardinality": "SINGLE",
"valuesMinCount": 0
},
{
"name": "start_date",
"isOptional": True,
"isUnique": False,
"isIndexable": False,
"typeName": "date",
"valuesMaxCount": 1,
"cardinality": "SINGLE",
"valuesMinCount": 0
},
{
"name": "end_date",
"isOptional": True,
"isUnique": False,
"isIndexable": False,
"typeName": "date",
"valuesMaxCount": 1,
"cardinality": "SINGLE",
"valuesMinCount": 0
},
],
},
],
}
|
Ecotrust/F2S-MOI | refs/heads/master | moi/sectors/migrations/0002_auto_20151229_2316.py | 1 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-29 23:16
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.fields
class Migration(migrations.Migration):
dependencies = [
('wagtailimages', '0010_change_on_delete_behaviour'),
('sectors', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='sector',
name='displayTitle',
field=wagtail.wagtailcore.fields.RichTextField(blank=True),
),
migrations.AddField(
model_name='sector',
name='image',
field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='wagtailimages.Image'),
),
migrations.AddField(
model_name='sector',
name='main_content',
field=wagtail.wagtailcore.fields.RichTextField(blank=True, default=None, null=True),
),
migrations.AddField(
model_name='sector',
name='sub_title',
field=wagtail.wagtailcore.fields.RichTextField(blank=True, default=None, null=True),
),
]
|
Distrotech/intellij-community | refs/heads/master | python/testData/refactoring/move/oldStyleRelativeImport/before/src/pkg/a.py | 76 | import b as alias
from subpkg import c as alias2
from .subpkg import c
print(alias, alias2, c)
|
ray-zhong/github_trend_spider | refs/heads/master | ENV/Lib/site-packages/pip/_vendor/requests/packages/urllib3/contrib/appengine.py | 360 | from __future__ import absolute_import
import logging
import os
import warnings
from ..exceptions import (
HTTPError,
HTTPWarning,
MaxRetryError,
ProtocolError,
TimeoutError,
SSLError
)
from ..packages.six import BytesIO
from ..request import RequestMethods
from ..response import HTTPResponse
from ..util.timeout import Timeout
from ..util.retry import Retry
try:
from google.appengine.api import urlfetch
except ImportError:
urlfetch = None
log = logging.getLogger(__name__)
class AppEnginePlatformWarning(HTTPWarning):
pass
class AppEnginePlatformError(HTTPError):
pass
class AppEngineManager(RequestMethods):
"""
Connection manager for Google App Engine sandbox applications.
This manager uses the URLFetch service directly instead of using the
emulated httplib, and is subject to URLFetch limitations as described in
the App Engine documentation here:
https://cloud.google.com/appengine/docs/python/urlfetch
Notably it will raise an AppEnginePlatformError if:
* URLFetch is not available.
* If you attempt to use this on GAEv2 (Managed VMs), as full socket
support is available.
* If a request size is more than 10 megabytes.
* If a response size is more than 32 megabtyes.
* If you use an unsupported request method such as OPTIONS.
Beyond those cases, it will raise normal urllib3 errors.
"""
def __init__(self, headers=None, retries=None, validate_certificate=True):
if not urlfetch:
raise AppEnginePlatformError(
"URLFetch is not available in this environment.")
if is_prod_appengine_mvms():
raise AppEnginePlatformError(
"Use normal urllib3.PoolManager instead of AppEngineManager"
"on Managed VMs, as using URLFetch is not necessary in "
"this environment.")
warnings.warn(
"urllib3 is using URLFetch on Google App Engine sandbox instead "
"of sockets. To use sockets directly instead of URLFetch see "
"https://urllib3.readthedocs.io/en/latest/contrib.html.",
AppEnginePlatformWarning)
RequestMethods.__init__(self, headers)
self.validate_certificate = validate_certificate
self.retries = retries or Retry.DEFAULT
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# Return False to re-raise any potential exceptions
return False
def urlopen(self, method, url, body=None, headers=None,
retries=None, redirect=True, timeout=Timeout.DEFAULT_TIMEOUT,
**response_kw):
retries = self._get_retries(retries, redirect)
try:
response = urlfetch.fetch(
url,
payload=body,
method=method,
headers=headers or {},
allow_truncated=False,
follow_redirects=(
redirect and
retries.redirect != 0 and
retries.total),
deadline=self._get_absolute_timeout(timeout),
validate_certificate=self.validate_certificate,
)
except urlfetch.DeadlineExceededError as e:
raise TimeoutError(self, e)
except urlfetch.InvalidURLError as e:
if 'too large' in str(e):
raise AppEnginePlatformError(
"URLFetch request too large, URLFetch only "
"supports requests up to 10mb in size.", e)
raise ProtocolError(e)
except urlfetch.DownloadError as e:
if 'Too many redirects' in str(e):
raise MaxRetryError(self, url, reason=e)
raise ProtocolError(e)
except urlfetch.ResponseTooLargeError as e:
raise AppEnginePlatformError(
"URLFetch response too large, URLFetch only supports"
"responses up to 32mb in size.", e)
except urlfetch.SSLCertificateError as e:
raise SSLError(e)
except urlfetch.InvalidMethodError as e:
raise AppEnginePlatformError(
"URLFetch does not support method: %s" % method, e)
http_response = self._urlfetch_response_to_http_response(
response, **response_kw)
# Check for redirect response
if (http_response.get_redirect_location() and
retries.raise_on_redirect and redirect):
raise MaxRetryError(self, url, "too many redirects")
# Check if we should retry the HTTP response.
if retries.is_forced_retry(method, status_code=http_response.status):
retries = retries.increment(
method, url, response=http_response, _pool=self)
log.info("Forced retry: %s", url)
retries.sleep()
return self.urlopen(
method, url,
body=body, headers=headers,
retries=retries, redirect=redirect,
timeout=timeout, **response_kw)
return http_response
def _urlfetch_response_to_http_response(self, urlfetch_resp, **response_kw):
if is_prod_appengine():
# Production GAE handles deflate encoding automatically, but does
# not remove the encoding header.
content_encoding = urlfetch_resp.headers.get('content-encoding')
if content_encoding == 'deflate':
del urlfetch_resp.headers['content-encoding']
transfer_encoding = urlfetch_resp.headers.get('transfer-encoding')
# We have a full response's content,
# so let's make sure we don't report ourselves as chunked data.
if transfer_encoding == 'chunked':
encodings = transfer_encoding.split(",")
encodings.remove('chunked')
urlfetch_resp.headers['transfer-encoding'] = ','.join(encodings)
return HTTPResponse(
# In order for decoding to work, we must present the content as
# a file-like object.
body=BytesIO(urlfetch_resp.content),
headers=urlfetch_resp.headers,
status=urlfetch_resp.status_code,
**response_kw
)
def _get_absolute_timeout(self, timeout):
if timeout is Timeout.DEFAULT_TIMEOUT:
return 5 # 5s is the default timeout for URLFetch.
if isinstance(timeout, Timeout):
if timeout._read is not timeout._connect:
warnings.warn(
"URLFetch does not support granular timeout settings, "
"reverting to total timeout.", AppEnginePlatformWarning)
return timeout.total
return timeout
def _get_retries(self, retries, redirect):
if not isinstance(retries, Retry):
retries = Retry.from_int(
retries, redirect=redirect, default=self.retries)
if retries.connect or retries.read or retries.redirect:
warnings.warn(
"URLFetch only supports total retries and does not "
"recognize connect, read, or redirect retry parameters.",
AppEnginePlatformWarning)
return retries
def is_appengine():
return (is_local_appengine() or
is_prod_appengine() or
is_prod_appengine_mvms())
def is_appengine_sandbox():
return is_appengine() and not is_prod_appengine_mvms()
def is_local_appengine():
return ('APPENGINE_RUNTIME' in os.environ and
'Development/' in os.environ['SERVER_SOFTWARE'])
def is_prod_appengine():
return ('APPENGINE_RUNTIME' in os.environ and
'Google App Engine/' in os.environ['SERVER_SOFTWARE'] and
not is_prod_appengine_mvms())
def is_prod_appengine_mvms():
return os.environ.get('GAE_VM', False) == 'true'
|
charbeljc/OCB | refs/heads/8.0 | openerp/addons/base/res/res_partner.py | 4 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import datetime
from lxml import etree
import math
import pytz
import urlparse
import openerp
from openerp import tools, api
from openerp.osv import osv, fields
from openerp.osv.expression import get_unaccent_wrapper
from openerp.tools.translate import _
ADDRESS_FORMAT_LAYOUTS = {
'%(city)s %(state_code)s\n%(zip)s': """
<div class="address_format">
<field name="city" placeholder="%(city)s" style="width: 50%%"/>
<field name="state_id" class="oe_no_button" placeholder="%(state)s" style="width: 47%%" options='{"no_open": true}'/>
<br/>
<field name="zip" placeholder="%(zip)s"/>
</div>
""",
'%(zip)s %(city)s': """
<div class="address_format">
<field name="zip" placeholder="%(zip)s" style="width: 40%%"/>
<field name="city" placeholder="%(city)s" style="width: 57%%"/>
<br/>
<field name="state_id" class="oe_no_button" placeholder="%(state)s" options='{"no_open": true}'/>
</div>
""",
'%(city)s\n%(state_name)s\n%(zip)s': """
<div class="address_format">
<field name="city" placeholder="%(city)s"/>
<field name="state_id" class="oe_no_button" placeholder="%(state)s" options='{"no_open": true}'/>
<field name="zip" placeholder="%(zip)s"/>
</div>
"""
}
class format_address(object):
@api.model
def fields_view_get_address(self, arch):
fmt = self.env.user.company_id.country_id.address_format or ''
for k, v in ADDRESS_FORMAT_LAYOUTS.items():
if k in fmt:
doc = etree.fromstring(arch)
for node in doc.xpath("//div[@class='address_format']"):
tree = etree.fromstring(v % {'city': _('City'), 'zip': _('ZIP'), 'state': _('State')})
for child in node.xpath("//field"):
if child.attrib.get('modifiers'):
for field in tree.xpath("//field[@name='%s']" % child.attrib.get('name')):
field.attrib['modifiers'] = child.attrib.get('modifiers')
node.getparent().replace(node, tree)
arch = etree.tostring(doc)
break
return arch
@api.model
def _tz_get(self):
# put POSIX 'Etc/*' entries at the end to avoid confusing users - see bug 1086728
return [(tz,tz) for tz in sorted(pytz.all_timezones, key=lambda tz: tz if not tz.startswith('Etc/') else '_')]
class res_partner_category(osv.Model):
def name_get(self, cr, uid, ids, context=None):
""" Return the categories' display name, including their direct
parent by default.
If ``context['partner_category_display']`` is ``'short'``, the short
version of the category name (without the direct parent) is used.
The default is the long version.
"""
if not isinstance(ids, list):
ids = [ids]
if context is None:
context = {}
if context.get('partner_category_display') == 'short':
return super(res_partner_category, self).name_get(cr, uid, ids, context=context)
res = []
for category in self.browse(cr, uid, ids, context=context):
names = []
current = category
while current:
names.append(current.name)
current = current.parent_id
res.append((category.id, ' / '.join(reversed(names))))
return res
@api.model
def name_search(self, name, args=None, operator='ilike', limit=100):
args = args or []
if name:
# Be sure name_search is symetric to name_get
name = name.split(' / ')[-1]
args = [('name', operator, name)] + args
categories = self.search(args, limit=limit)
return categories.name_get()
@api.multi
def _name_get_fnc(self, field_name, arg):
return dict(self.name_get())
_description = 'Partner Tags'
_name = 'res.partner.category'
_columns = {
'name': fields.char('Category Name', required=True, translate=True),
'parent_id': fields.many2one('res.partner.category', 'Parent Category', select=True, ondelete='cascade'),
'complete_name': fields.function(_name_get_fnc, type="char", string='Full Name'),
'child_ids': fields.one2many('res.partner.category', 'parent_id', 'Child Categories'),
'active': fields.boolean('Active', help="The active field allows you to hide the category without removing it."),
'parent_left': fields.integer('Left parent', select=True),
'parent_right': fields.integer('Right parent', select=True),
'partner_ids': fields.many2many('res.partner', id1='category_id', id2='partner_id', string='Partners'),
}
_constraints = [
(osv.osv._check_recursion, 'Error ! You can not create recursive categories.', ['parent_id'])
]
_defaults = {
'active': 1,
}
_parent_store = True
_parent_order = 'name'
_order = 'parent_left'
class res_partner_title(osv.osv):
_name = 'res.partner.title'
_order = 'name'
_columns = {
'name': fields.char('Title', required=True, translate=True),
'shortcut': fields.char('Abbreviation', translate=True),
'domain': fields.selection([('partner', 'Partner'), ('contact', 'Contact')], 'Domain', required=True)
}
_defaults = {
'domain': 'contact',
}
@api.model
def _lang_get(self):
languages = self.env['res.lang'].search([])
return [(language.code, language.name) for language in languages]
# fields copy if 'use_parent_address' is checked
ADDRESS_FIELDS = ('street', 'street2', 'zip', 'city', 'state_id', 'country_id')
class res_partner(osv.Model, format_address):
_description = 'Partner'
_name = "res.partner"
def _address_display(self, cr, uid, ids, name, args, context=None):
res = {}
for partner in self.browse(cr, uid, ids, context=context):
res[partner.id] = self._display_address(cr, uid, partner, context=context)
return res
@api.multi
def _get_tz_offset(self, name, args):
return dict(
(p.id, datetime.datetime.now(pytz.timezone(p.tz or 'GMT')).strftime('%z'))
for p in self)
@api.multi
def _get_image(self, name, args):
return dict((p.id, tools.image_get_resized_images(p.image)) for p in self)
@api.one
def _set_image(self, name, value, args):
return self.write({'image': tools.image_resize_image_big(value)})
@api.multi
def _has_image(self, name, args):
return dict((p.id, bool(p.image)) for p in self)
def _commercial_partner_compute(self, cr, uid, ids, name, args, context=None):
""" Returns the partner that is considered the commercial
entity of this partner. The commercial entity holds the master data
for all commercial fields (see :py:meth:`~_commercial_fields`) """
result = dict.fromkeys(ids, False)
for partner in self.browse(cr, uid, ids, context=context):
current_partner = partner
while not current_partner.is_company and current_partner.parent_id:
current_partner = current_partner.parent_id
result[partner.id] = current_partner.id
return result
def _display_name_compute(self, cr, uid, ids, name, args, context=None):
context = dict(context or {})
context.pop('show_address', None)
context.pop('show_address_only', None)
context.pop('show_email', None)
return dict(self.name_get(cr, uid, ids, context=context))
# indirections to avoid passing a copy of the overridable method when declaring the function field
_commercial_partner_id = lambda self, *args, **kwargs: self._commercial_partner_compute(*args, **kwargs)
_display_name = lambda self, *args, **kwargs: self._display_name_compute(*args, **kwargs)
_commercial_partner_store_triggers = {
'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
['parent_id', 'is_company'], 10)
}
_display_name_store_triggers = {
'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),
['parent_id', 'is_company', 'name'], 10)
}
_order = "display_name"
_columns = {
'name': fields.char('Name', required=True, select=True),
'display_name': fields.function(_display_name, type='char', string='Name', store=_display_name_store_triggers, select=True),
'date': fields.date('Date', select=1),
'title': fields.many2one('res.partner.title', 'Title'),
'parent_id': fields.many2one('res.partner', 'Related Company', select=True),
'parent_name': fields.related('parent_id', 'name', type='char', readonly=True, string='Parent name'),
'child_ids': fields.one2many('res.partner', 'parent_id', 'Contacts', domain=[('active','=',True)]), # force "active_test" domain to bypass _search() override
'ref': fields.char('Contact Reference', select=1),
'lang': fields.selection(_lang_get, 'Language',
help="If the selected language is loaded in the system, all documents related to this contact will be printed in this language. If not, it will be English."),
'tz': fields.selection(_tz_get, 'Timezone', size=64,
help="The partner's timezone, used to output proper date and time values inside printed reports. "
"It is important to set a value for this field. You should use the same timezone "
"that is otherwise used to pick and render date and time values: your computer's timezone."),
'tz_offset': fields.function(_get_tz_offset, type='char', size=5, string='Timezone offset', invisible=True),
'user_id': fields.many2one('res.users', 'Salesperson', help='The internal user that is in charge of communicating with this contact if any.'),
'vat': fields.char('TIN', help="Tax Identification Number. Check the box if this contact is subjected to taxes. Used by the some of the legal statements."),
'bank_ids': fields.one2many('res.partner.bank', 'partner_id', 'Banks'),
'website': fields.char('Website', help="Website of Partner or Company"),
'comment': fields.text('Notes'),
'category_id': fields.many2many('res.partner.category', id1='partner_id', id2='category_id', string='Tags'),
'credit_limit': fields.float(string='Credit Limit'),
'ean13': fields.char('EAN13', size=13),
'active': fields.boolean('Active'),
'customer': fields.boolean('Customer', help="Check this box if this contact is a customer."),
'supplier': fields.boolean('Supplier', help="Check this box if this contact is a supplier. If it's not checked, purchase people will not see it when encoding a purchase order."),
'employee': fields.boolean('Employee', help="Check this box if this contact is an Employee."),
'function': fields.char('Job Position'),
'type': fields.selection([('default', 'Default'), ('invoice', 'Invoice'),
('delivery', 'Shipping'), ('contact', 'Contact'),
('other', 'Other')], 'Address Type',
help="Used to select automatically the right address according to the context in sales and purchases documents."),
'street': fields.char('Street'),
'street2': fields.char('Street2'),
'zip': fields.char('Zip', size=24, change_default=True),
'city': fields.char('City'),
'state_id': fields.many2one("res.country.state", 'State', ondelete='restrict'),
'country_id': fields.many2one('res.country', 'Country', ondelete='restrict'),
'email': fields.char('Email'),
'phone': fields.char('Phone'),
'fax': fields.char('Fax'),
'mobile': fields.char('Mobile'),
'birthdate': fields.char('Birthdate'),
'is_company': fields.boolean('Is a Company', help="Check if the contact is a company, otherwise it is a person"),
'use_parent_address': fields.boolean('Use Company Address', help="Select this if you want to set company's address information for this contact"),
# image: all image fields are base64 encoded and PIL-supported
'image': fields.binary("Image",
help="This field holds the image used as avatar for this contact, limited to 1024x1024px"),
'image_medium': fields.function(_get_image, fnct_inv=_set_image,
string="Medium-sized image", type="binary", multi="_get_image",
store={
'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
},
help="Medium-sized image of this contact. It is automatically "\
"resized as a 128x128px image, with aspect ratio preserved. "\
"Use this field in form views or some kanban views."),
'image_small': fields.function(_get_image, fnct_inv=_set_image,
string="Small-sized image", type="binary", multi="_get_image",
store={
'res.partner': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
},
help="Small-sized image of this contact. It is automatically "\
"resized as a 64x64px image, with aspect ratio preserved. "\
"Use this field anywhere a small image is required."),
'has_image': fields.function(_has_image, type="boolean"),
'company_id': fields.many2one('res.company', 'Company', select=1),
'color': fields.integer('Color Index'),
'user_ids': fields.one2many('res.users', 'partner_id', 'Users'),
'contact_address': fields.function(_address_display, type='char', string='Complete Address'),
# technical field used for managing commercial fields
'commercial_partner_id': fields.function(_commercial_partner_id, type='many2one', relation='res.partner', string='Commercial Entity', store=_commercial_partner_store_triggers)
}
@api.model
def _default_category(self):
category_id = self.env.context.get('category_id', False)
return [category_id] if category_id else False
@api.model
def _get_default_image(self, is_company, colorize=False):
img_path = openerp.modules.get_module_resource(
'base', 'static/src/img', 'company_image.png' if is_company else 'avatar.png')
with open(img_path, 'rb') as f:
image = f.read()
# colorize user avatars
if not is_company:
image = tools.image_colorize(image)
return tools.image_resize_image_big(image.encode('base64'))
def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
if (not view_id) and (view_type=='form') and context and context.get('force_email', False):
view_id = self.pool['ir.model.data'].get_object_reference(cr, user, 'base', 'view_partner_simple_form')[1]
res = super(res_partner,self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
if view_type == 'form':
res['arch'] = self.fields_view_get_address(cr, user, res['arch'], context=context)
return res
@api.model
def _default_company(self):
return self.env['res.company']._company_default_get('res.partner')
_defaults = {
'active': True,
'lang': api.model(lambda self: self.env.lang),
'tz': api.model(lambda self: self.env.context.get('tz', False)),
'customer': True,
'category_id': _default_category,
'company_id': _default_company,
'color': 0,
'is_company': False,
'type': 'contact', # type 'default' is wildcard and thus inappropriate
'use_parent_address': False,
'image': False,
}
_constraints = [
(osv.osv._check_recursion, 'You cannot create recursive Partner hierarchies.', ['parent_id']),
]
@api.one
def copy(self, default=None):
default = dict(default or {})
default['name'] = _('%s (copy)') % self.name
return super(res_partner, self).copy(default)
@api.multi
def onchange_type(self, is_company):
value = {'title': False}
if is_company:
value['use_parent_address'] = False
domain = {'title': [('domain', '=', 'partner')]}
else:
domain = {'title': [('domain', '=', 'contact')]}
return {'value': value, 'domain': domain}
def onchange_address(self, cr, uid, ids, use_parent_address, parent_id, context=None):
def value_or_id(val):
""" return val or val.id if val is a browse record """
return val if isinstance(val, (bool, int, long, float, basestring)) else val.id
result = {}
if parent_id:
if ids:
partner = self.browse(cr, uid, ids[0], context=context)
if partner.parent_id and partner.parent_id.id != parent_id:
result['warning'] = {'title': _('Warning'),
'message': _('Changing the company of a contact should only be done if it '
'was never correctly set. If an existing contact starts working for a new '
'company then a new contact should be created under that new '
'company. You can use the "Discard" button to abandon this change.')}
if use_parent_address:
parent = self.browse(cr, uid, parent_id, context=context)
address_fields = self._address_fields(cr, uid, context=context)
result['value'] = dict((key, value_or_id(parent[key])) for key in address_fields)
else:
result['value'] = {'use_parent_address': False}
return result
@api.multi
def onchange_state(self, state_id):
if state_id:
state = self.env['res.country.state'].browse(state_id)
return {'value': {'country_id': state.country_id.id}}
return {}
def _check_ean_key(self, cr, uid, ids, context=None):
for partner_o in self.pool['res.partner'].read(cr, uid, ids, ['ean13',]):
thisean=partner_o['ean13']
if thisean and thisean!='':
if len(thisean)!=13:
return False
sum=0
for i in range(12):
if not (i % 2):
sum+=int(thisean[i])
else:
sum+=3*int(thisean[i])
if math.ceil(sum/10.0)*10-sum!=int(thisean[12]):
return False
return True
# _constraints = [(_check_ean_key, 'Error: Invalid ean code', ['ean13'])]
def _update_fields_values(self, cr, uid, partner, fields, context=None):
""" Returns dict of write() values for synchronizing ``fields`` """
values = {}
for fname in fields:
field = self._fields[fname]
if field.type == 'one2many':
raise AssertionError('One2Many fields cannot be synchronized as part of `commercial_fields` or `address fields`')
if field.type == 'many2one':
values[fname] = partner[fname].id if partner[fname] else False
elif field.type == 'many2many':
values[fname] = [(6,0,[r.id for r in partner[fname] or []])]
else:
values[fname] = partner[fname]
return values
def _address_fields(self, cr, uid, context=None):
""" Returns the list of address fields that are synced from the parent
when the `use_parent_address` flag is set. """
return list(ADDRESS_FIELDS)
def update_address(self, cr, uid, ids, vals, context=None):
address_fields = self._address_fields(cr, uid, context=context)
addr_vals = dict((key, vals[key]) for key in address_fields if key in vals)
if addr_vals:
return super(res_partner, self).write(cr, uid, ids, addr_vals, context)
def _commercial_fields(self, cr, uid, context=None):
""" Returns the list of fields that are managed by the commercial entity
to which a partner belongs. These fields are meant to be hidden on
partners that aren't `commercial entities` themselves, and will be
delegated to the parent `commercial entity`. The list is meant to be
extended by inheriting classes. """
return ['vat', 'credit_limit']
def _commercial_sync_from_company(self, cr, uid, partner, context=None):
""" Handle sync of commercial fields when a new parent commercial entity is set,
as if they were related fields """
commercial_partner = partner.commercial_partner_id
if not commercial_partner:
# On child partner creation of a parent partner,
# the commercial_partner_id is not yet computed
commercial_partner_id = self._commercial_partner_compute(
cr, uid, [partner.id], 'commercial_partner_id', [], context=context)[partner.id]
commercial_partner = self.browse(cr, uid, commercial_partner_id, context=context)
if commercial_partner != partner:
commercial_fields = self._commercial_fields(cr, uid, context=context)
sync_vals = self._update_fields_values(cr, uid, commercial_partner,
commercial_fields, context=context)
partner.write(sync_vals)
def _commercial_sync_to_children(self, cr, uid, partner, context=None):
""" Handle sync of commercial fields to descendants """
commercial_fields = self._commercial_fields(cr, uid, context=context)
commercial_partner = partner.commercial_partner_id
if not commercial_partner:
# On child partner creation of a parent partner,
# the commercial_partner_id is not yet computed
commercial_partner_id = self._commercial_partner_compute(
cr, uid, [partner.id], 'commercial_partner_id', [], context=context)[partner.id]
commercial_partner = self.browse(cr, uid, commercial_partner_id, context=context)
sync_vals = self._update_fields_values(cr, uid, commercial_partner,
commercial_fields, context=context)
sync_children = [c for c in partner.child_ids if not c.is_company]
for child in sync_children:
self._commercial_sync_to_children(cr, uid, child, context=context)
return self.write(cr, uid, [c.id for c in sync_children], sync_vals, context=context)
def _fields_sync(self, cr, uid, partner, update_values, context=None):
""" Sync commercial fields and address fields from company and to children after create/update,
just as if those were all modeled as fields.related to the parent """
# 1. From UPSTREAM: sync from parent
if update_values.get('parent_id') or update_values.get('use_parent_address'):
# 1a. Commercial fields: sync if parent changed
if update_values.get('parent_id'):
self._commercial_sync_from_company(cr, uid, partner, context=context)
# 1b. Address fields: sync if parent or use_parent changed *and* both are now set
if partner.parent_id and partner.use_parent_address:
onchange_vals = self.onchange_address(cr, uid, [partner.id],
use_parent_address=partner.use_parent_address,
parent_id=partner.parent_id.id,
context=context).get('value', {})
partner.update_address(onchange_vals)
# 2. To DOWNSTREAM: sync children
if partner.child_ids:
# 2a. Commercial Fields: sync if commercial entity
if partner.commercial_partner_id == partner:
commercial_fields = self._commercial_fields(cr, uid,
context=context)
if any(field in update_values for field in commercial_fields):
self._commercial_sync_to_children(cr, uid, partner,
context=context)
# 2b. Address fields: sync if address changed
address_fields = self._address_fields(cr, uid, context=context)
if any(field in update_values for field in address_fields):
domain_children = [('parent_id', '=', partner.id), ('use_parent_address', '=', True)]
update_ids = self.search(cr, uid, domain_children, context=context)
self.update_address(cr, uid, update_ids, update_values, context=context)
def _handle_first_contact_creation(self, cr, uid, partner, context=None):
""" On creation of first contact for a company (or root) that has no address, assume contact address
was meant to be company address """
parent = partner.parent_id
address_fields = self._address_fields(cr, uid, context=context)
if parent and (parent.is_company or not parent.parent_id) and len(parent.child_ids) == 1 and \
any(partner[f] for f in address_fields) and not any(parent[f] for f in address_fields):
addr_vals = self._update_fields_values(cr, uid, partner, address_fields, context=context)
parent.update_address(addr_vals)
if not parent.is_company:
parent.write({'is_company': True})
def unlink(self, cr, uid, ids, context=None):
orphan_contact_ids = self.search(cr, uid,
[('parent_id', 'in', ids), ('id', 'not in', ids), ('use_parent_address', '=', True)], context=context)
if orphan_contact_ids:
# no longer have a parent address
self.write(cr, uid, orphan_contact_ids, {'use_parent_address': False}, context=context)
return super(res_partner, self).unlink(cr, uid, ids, context=context)
def _clean_website(self, website):
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(website)
if not scheme:
if not netloc:
netloc, path = path, ''
website = urlparse.urlunparse(('http', netloc, path, params, query, fragment))
return website
@api.multi
def write(self, vals):
# res.partner must only allow to set the company_id of a partner if it
# is the same as the company of all users that inherit from this partner
# (this is to allow the code from res_users to write to the partner!) or
# if setting the company_id to False (this is compatible with any user
# company)
if vals.get('website'):
vals['website'] = self._clean_website(vals['website'])
if vals.get('company_id'):
company = self.env['res.company'].browse(vals['company_id'])
for partner in self:
if partner.user_ids:
companies = set(user.company_id for user in partner.user_ids)
if len(companies) > 1 or company not in companies:
raise osv.except_osv(_("Warning"),_("You can not change the company as the partner/user has multiple user linked with different companies."))
result = super(res_partner, self).write(vals)
for partner in self:
self._fields_sync(partner, vals)
return result
@api.model
def create(self, vals):
if vals.get('website'):
vals['website'] = self._clean_website(vals['website'])
partner = super(res_partner, self).create(vals)
self._fields_sync(partner, vals)
self._handle_first_contact_creation(partner)
return partner
def open_commercial_entity(self, cr, uid, ids, context=None):
""" Utility method used to add an "Open Company" button in partner views """
partner = self.browse(cr, uid, ids[0], context=context)
return {'type': 'ir.actions.act_window',
'res_model': 'res.partner',
'view_mode': 'form',
'res_id': partner.commercial_partner_id.id,
'target': 'new',
'flags': {'form': {'action_buttons': True}}}
def open_parent(self, cr, uid, ids, context=None):
""" Utility method used to add an "Open Parent" button in partner views """
partner = self.browse(cr, uid, ids[0], context=context)
return {'type': 'ir.actions.act_window',
'res_model': 'res.partner',
'view_mode': 'form',
'res_id': partner.parent_id.id,
'target': 'new',
'flags': {'form': {'action_buttons': True}}}
def name_get(self, cr, uid, ids, context=None):
if context is None:
context = {}
if isinstance(ids, (int, long)):
ids = [ids]
res = []
for record in self.browse(cr, uid, ids, context=context):
name = record.name
if record.parent_id and not record.is_company:
name = "%s, %s" % (record.parent_name, name)
if context.get('show_address_only'):
name = self._display_address(cr, uid, record, without_company=True, context=context)
if context.get('show_address'):
name = name + "\n" + self._display_address(cr, uid, record, without_company=True, context=context)
name = name.replace('\n\n','\n')
name = name.replace('\n\n','\n')
if context.get('show_email') and record.email:
name = "%s <%s>" % (name, record.email)
res.append((record.id, name))
return res
def _parse_partner_name(self, text, context=None):
""" Supported syntax:
- 'Raoul <raoul@grosbedon.fr>': will find name and email address
- otherwise: default, everything is set as the name """
emails = tools.email_split(text.replace(' ',','))
if emails:
email = emails[0]
name = text[:text.index(email)].replace('"', '').replace('<', '').strip()
else:
name, email = text, ''
return name, email
def name_create(self, cr, uid, name, context=None):
""" Override of orm's name_create method for partners. The purpose is
to handle some basic formats to create partners using the
name_create.
If only an email address is received and that the regex cannot find
a name, the name will have the email value.
If 'force_email' key in context: must find the email address. """
if context is None:
context = {}
name, email = self._parse_partner_name(name, context=context)
if context.get('force_email') and not email:
raise osv.except_osv(_('Warning'), _("Couldn't create contact without email address!"))
if not name and email:
name = email
rec_id = self.create(cr, uid, {self._rec_name: name or email, 'email': email or False}, context=context)
return self.name_get(cr, uid, [rec_id], context)[0]
def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
""" Override search() to always show inactive children when searching via ``child_of`` operator. The ORM will
always call search() with a simple domain of the form [('parent_id', 'in', [ids])]. """
# a special ``domain`` is set on the ``child_ids`` o2m to bypass this logic, as it uses similar domain expressions
if len(args) == 1 and len(args[0]) == 3 and args[0][:2] == ('parent_id','in') \
and args[0][2] != [False]:
context = dict(context or {}, active_test=False)
return super(res_partner, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context,
count=count, access_rights_uid=access_rights_uid)
def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
if not args:
args = []
if name and operator in ('=', 'ilike', '=ilike', 'like', '=like'):
self.check_access_rights(cr, uid, 'read')
where_query = self._where_calc(cr, uid, args, context=context)
self._apply_ir_rules(cr, uid, where_query, 'read', context=context)
from_clause, where_clause, where_clause_params = where_query.get_sql()
where_str = where_clause and (" WHERE %s AND " % where_clause) or ' WHERE '
# search on the name of the contacts and of its company
search_name = name
if operator in ('ilike', 'like'):
search_name = '%%%s%%' % name
if operator in ('=ilike', '=like'):
operator = operator[1:]
unaccent = get_unaccent_wrapper(cr)
query = """SELECT id
FROM res_partner
{where} ({email} {operator} {percent}
OR {display_name} {operator} {percent})
ORDER BY {display_name}
""".format(where=where_str, operator=operator,
email=unaccent('email'),
display_name=unaccent('display_name'),
percent=unaccent('%s'))
where_clause_params += [search_name, search_name]
if limit:
query += ' limit %s'
where_clause_params.append(limit)
cr.execute(query, where_clause_params)
ids = map(lambda x: x[0], cr.fetchall())
if ids:
return self.name_get(cr, uid, ids, context)
else:
return []
return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)
def find_or_create(self, cr, uid, email, context=None):
""" Find a partner with the given ``email`` or use :py:method:`~.name_create`
to create one
:param str email: email-like string, which should contain at least one email,
e.g. ``"Raoul Grosbedon <r.g@grosbedon.fr>"``"""
assert email, 'an email is required for find_or_create to work'
emails = tools.email_split(email)
if emails:
email = emails[0]
ids = self.search(cr, uid, [('email','ilike',email)], context=context)
if not ids:
return self.name_create(cr, uid, email, context=context)[0]
return ids[0]
def _email_send(self, cr, uid, ids, email_from, subject, body, on_error=None):
partners = self.browse(cr, uid, ids)
for partner in partners:
if partner.email:
tools.email_send(email_from, [partner.email], subject, body, on_error)
return True
def email_send(self, cr, uid, ids, email_from, subject, body, on_error=''):
while len(ids):
self.pool['ir.cron'].create(cr, uid, {
'name': 'Send Partner Emails',
'user_id': uid,
'model': 'res.partner',
'function': '_email_send',
'args': repr([ids[:16], email_from, subject, body, on_error])
})
ids = ids[16:]
return True
def address_get(self, cr, uid, ids, adr_pref=None, context=None):
""" Find contacts/addresses of the right type(s) by doing a depth-first-search
through descendants within company boundaries (stop at entities flagged ``is_company``)
then continuing the search at the ancestors that are within the same company boundaries.
Defaults to partners of type ``'default'`` when the exact type is not found, or to the
provided partner itself if no type ``'default'`` is found either. """
adr_pref = set(adr_pref or [])
if 'default' not in adr_pref:
adr_pref.add('default')
result = {}
visited = set()
if isinstance(ids, (int, long)):
ids = [ids]
for partner in self.browse(cr, uid, filter(None, ids), context=context):
current_partner = partner
while current_partner:
to_scan = [current_partner]
# Scan descendants, DFS
while to_scan:
record = to_scan.pop(0)
visited.add(record)
if record.type in adr_pref and not result.get(record.type):
result[record.type] = record.id
if len(result) == len(adr_pref):
return result
to_scan = [c for c in record.child_ids
if c not in visited
if not c.is_company] + to_scan
# Continue scanning at ancestor if current_partner is not a commercial entity
if current_partner.is_company or not current_partner.parent_id:
break
current_partner = current_partner.parent_id
# default to type 'default' or the partner itself
default = result.get('default', ids and ids[0] or False)
for adr_type in adr_pref:
result[adr_type] = result.get(adr_type) or default
return result
def view_header_get(self, cr, uid, view_id, view_type, context):
res = super(res_partner, self).view_header_get(cr, uid, view_id, view_type, context)
if res: return res
if not context.get('category_id', False):
return False
return _('Partners: ')+self.pool['res.partner.category'].browse(cr, uid, context['category_id'], context).name
@api.model
@api.returns('self')
def main_partner(self):
''' Return the main partner '''
return self.env.ref('base.main_partner')
def _display_address(self, cr, uid, address, without_company=False, context=None):
'''
The purpose of this function is to build and return an address formatted accordingly to the
standards of the country where it belongs.
:param address: browse record of the res.partner to format
:returns: the address formatted in a display that fit its country habits (or the default ones
if not country is specified)
:rtype: string
'''
# get the information that will be injected into the display format
# get the address format
address_format = address.country_id.address_format or \
"%(street)s\n%(street2)s\n%(city)s %(state_code)s %(zip)s\n%(country_name)s"
args = {
'state_code': address.state_id.code or '',
'state_name': address.state_id.name or '',
'country_code': address.country_id.code or '',
'country_name': address.country_id.name or '',
'company_name': address.parent_name or '',
}
for field in self._address_fields(cr, uid, context=context):
args[field] = getattr(address, field) or ''
if without_company:
args['company_name'] = ''
elif address.parent_id:
address_format = '%(company_name)s\n' + address_format
return address_format % args
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
olivierdalang/QGIS | refs/heads/master | tests/src/python/test_qgslayoutscalebar.py | 45 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsLayoutItemScaleBar.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = '(C) 2017 by Nyall Dawson'
__date__ = '23/10/2017'
__copyright__ = 'Copyright 2017, The QGIS Project'
import qgis # NOQA
from qgis.testing import start_app, unittest
from qgis.core import QgsLayoutItemScaleBar
from test_qgslayoutitem import LayoutItemTestCase
start_app()
class TestQgsLayoutScaleBar(unittest.TestCase, LayoutItemTestCase):
@classmethod
def setUpClass(cls):
cls.item_class = QgsLayoutItemScaleBar
if __name__ == '__main__':
unittest.main()
|
JimCircadian/ansible | refs/heads/devel | lib/ansible/plugins/lookup/dig.py | 87 | # (c) 2015, Jan-Piet Mens <jpmens(at)gmail.com>
# (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = """
lookup: dig
author: Jan-Piet Mens (@jpmens) <jpmens(at)gmail.com>
version_added: "1.9"
short_description: query DNS using the dnspython library
requirements:
- dnspython (python library, http://www.dnspython.org/)
description:
- The dig lookup runs queries against DNS servers to retrieve DNS records for a specific name (FQDN - fully qualified domain name).
It is possible to lookup any DNS record in this manner.
- There is a couple of different syntaxes that can be used to specify what record should be retrieved, and for which name.
It is also possible to explicitly specify the DNS server(s) to use for lookups.
- In its simplest form, the dig lookup plugin can be used to retrieve an IPv4 address (DNS A record) associated with FQDN
- In addition to (default) A record, it is also possible to specify a different record type that should be queried.
This can be done by either passing-in additional parameter of format qtype=TYPE to the dig lookup, or by appending /TYPE to the FQDN being queried.
- If multiple values are associated with the requested record, the results will be returned as a comma-separated list.
In such cases you may want to pass option wantlist=True to the plugin, which will result in the record values being returned as a list
over which you can iterate later on.
- By default, the lookup will rely on system-wide configured DNS servers for performing the query.
It is also possible to explicitly specify DNS servers to query using the @DNS_SERVER_1,DNS_SERVER_2,...,DNS_SERVER_N notation.
This needs to be passed-in as an additional parameter to the lookup
options:
_terms:
description: domain(s) to query
qtype:
description: record type to query
default: 'A'
choices: [A, ALL, AAAA, CNAME, DNAME, DLV, DNSKEY, DS, HINFO, LOC, MX, NAPTR, NS, NSEC3PARAM, PTR, RP, RRSIG, SOA, SPF, SRV, SSHFP, TLSA, TXT]
flat:
description: If 0 each record is returned as a dictionary, otherwise a string
default: 1
notes:
- ALL is not a record per-se, merely the listed fields are available for any record results you retrieve in the form of a dictionary.
- While the 'dig' lookup plugin supports anything which dnspython supports out of the box, only a subset can be converted into a dictionary.
- If you need to obtain the AAAA record (IPv6 address), you must specify the record type explicitly.
Syntax for specifying the record type is shown in the examples below.
- The trailing dot in most of the examples listed is purely optional, but is specified for completeness/correctness sake.
"""
EXAMPLES = """
- name: Simple A record (IPV4 address) lookup for example.com
debug: msg="{{ lookup('dig', 'example.com.')}}"
- name: "The TXT record for example.org."
debug: msg="{{ lookup('dig', 'example.org.', 'qtype=TXT') }}"
- name: "The TXT record for example.org, alternative syntax."
debug: msg="{{ lookup('dig', 'example.org./TXT') }}"
- name: use in a loop
debug: msg="MX record for gmail.com {{ item }}"
with_items: "{{ lookup('dig', 'gmail.com./MX', wantlist=True) }}"
- debug: msg="Reverse DNS for 192.0.2.5 is {{ lookup('dig', '192.0.2.5/PTR') }}"
- debug: msg="Reverse DNS for 192.0.2.5 is {{ lookup('dig', '5.2.0.192.in-addr.arpa./PTR') }}"
- debug: msg="Reverse DNS for 192.0.2.5 is {{ lookup('dig', '5.2.0.192.in-addr.arpa.', 'qtype=PTR') }}"
- debug: msg="Querying 198.51.100.23 for IPv4 address for example.com. produces {{ lookup('dig', 'example.com', '@198.51.100.23') }}"
- debug: msg="XMPP service for gmail.com. is available at {{ item.target }} on port {{ item.port }}"
with_items: "{{ lookup('dig', '_xmpp-server._tcp.gmail.com./SRV', 'flat=0', wantlist=True) }}"
"""
RETURN = """
_list:
description:
- list of composed strings or dictonaries with key and value
If a dictionary, fields shows the keys returned depending on query type
fields:
ALL: owner, ttl, type
A: address
AAAA: address
CNAME: target
DNAME: target
DLV: algorithm, digest_type, key_tag, digest
DNSKEY: flags, algorithm, protocol, key
DS: algorithm, digest_type, key_tag, digest
HINFO: cpu, os
LOC: latitude, longitude, altitude, size, horizontal_precision, vertical_precision
MX: preference, exchange
NAPTR: order, preference, flags, service, regexp, replacement
NS: target
NSEC3PARAM: algorithm, flags, iterations, salt
PTR: target
RP: mbox, txt
SOA: mname, rname, serial, refresh, retry, expire, minimum
SPF: strings
SRV: priority, weight, port, target
SSHFP: algorithm, fp_type, fingerprint
TLSA: usage, selector, mtype, cert
TXT: strings
"""
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils._text import to_native
import socket
try:
import dns.exception
import dns.name
import dns.resolver
import dns.reversename
import dns.rdataclass
from dns.rdatatype import (A, AAAA, CNAME, DLV, DNAME, DNSKEY, DS, HINFO, LOC,
MX, NAPTR, NS, NSEC3PARAM, PTR, RP, SOA, SPF, SRV, SSHFP, TLSA, TXT)
HAVE_DNS = True
except ImportError:
HAVE_DNS = False
def make_rdata_dict(rdata):
''' While the 'dig' lookup plugin supports anything which dnspython supports
out of the box, the following supported_types list describes which
DNS query types we can convert to a dict.
Note: adding support for RRSIG is hard work. :)
'''
supported_types = {
A: ['address'],
AAAA: ['address'],
CNAME: ['target'],
DNAME: ['target'],
DLV: ['algorithm', 'digest_type', 'key_tag', 'digest'],
DNSKEY: ['flags', 'algorithm', 'protocol', 'key'],
DS: ['algorithm', 'digest_type', 'key_tag', 'digest'],
HINFO: ['cpu', 'os'],
LOC: ['latitude', 'longitude', 'altitude', 'size', 'horizontal_precision', 'vertical_precision'],
MX: ['preference', 'exchange'],
NAPTR: ['order', 'preference', 'flags', 'service', 'regexp', 'replacement'],
NS: ['target'],
NSEC3PARAM: ['algorithm', 'flags', 'iterations', 'salt'],
PTR: ['target'],
RP: ['mbox', 'txt'],
# RRSIG: ['algorithm', 'labels', 'original_ttl', 'expiration', 'inception', 'signature'],
SOA: ['mname', 'rname', 'serial', 'refresh', 'retry', 'expire', 'minimum'],
SPF: ['strings'],
SRV: ['priority', 'weight', 'port', 'target'],
SSHFP: ['algorithm', 'fp_type', 'fingerprint'],
TLSA: ['usage', 'selector', 'mtype', 'cert'],
TXT: ['strings'],
}
rd = {}
if rdata.rdtype in supported_types:
fields = supported_types[rdata.rdtype]
for f in fields:
val = rdata.__getattribute__(f)
if isinstance(val, dns.name.Name):
val = dns.name.Name.to_text(val)
if rdata.rdtype == DLV and f == 'digest':
val = dns.rdata._hexify(rdata.digest).replace(' ', '')
if rdata.rdtype == DS and f == 'digest':
val = dns.rdata._hexify(rdata.digest).replace(' ', '')
if rdata.rdtype == DNSKEY and f == 'key':
val = dns.rdata._base64ify(rdata.key).replace(' ', '')
if rdata.rdtype == NSEC3PARAM and f == 'salt':
val = dns.rdata._hexify(rdata.salt).replace(' ', '')
if rdata.rdtype == SSHFP and f == 'fingerprint':
val = dns.rdata._hexify(rdata.fingerprint).replace(' ', '')
if rdata.rdtype == TLSA and f == 'cert':
val = dns.rdata._hexify(rdata.cert).replace(' ', '')
rd[f] = val
return rd
# ==============================================================
# dig: Lookup DNS records
#
# --------------------------------------------------------------
class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
'''
terms contains a string with things to `dig' for. We support the
following formats:
example.com # A record
example.com qtype=A # same
example.com/TXT # specific qtype
example.com qtype=txt # same
192.0.2.23/PTR # reverse PTR
^^ shortcut for 23.2.0.192.in-addr.arpa/PTR
example.net/AAAA @nameserver # query specified server
^^^ can be comma-sep list of names/addresses
... flat=0 # returns a dict; default is 1 == string
'''
if HAVE_DNS is False:
raise AnsibleError("The dig lookup requires the python 'dnspython' library and it is not installed")
# Create Resolver object so that we can set NS if necessary
myres = dns.resolver.Resolver(configure=True)
edns_size = 4096
myres.use_edns(0, ednsflags=dns.flags.DO, payload=edns_size)
domain = None
qtype = 'A'
flat = True
rdclass = dns.rdataclass.from_text('IN')
for t in terms:
if t.startswith('@'): # e.g. "@10.0.1.2,192.0.2.1" is ok.
nsset = t[1:].split(',')
for ns in nsset:
nameservers = []
# Check if we have a valid IP address. If so, use that, otherwise
# try to resolve name to address using system's resolver. If that
# fails we bail out.
try:
socket.inet_aton(ns)
nameservers.append(ns)
except:
try:
nsaddr = dns.resolver.query(ns)[0].address
nameservers.append(nsaddr)
except Exception as e:
raise AnsibleError("dns lookup NS: %s" % to_native(e))
myres.nameservers = nameservers
continue
if '=' in t:
try:
opt, arg = t.split('=')
except:
pass
if opt == 'qtype':
qtype = arg.upper()
elif opt == 'flat':
flat = int(arg)
elif opt == 'class':
try:
rdclass = dns.rdataclass.from_text(arg)
except Exception as e:
raise AnsibleError("dns lookup illegal CLASS: %s" % to_native(e))
continue
if '/' in t:
try:
domain, qtype = t.split('/')
except:
domain = t
else:
domain = t
# print "--- domain = {0} qtype={1} rdclass={2}".format(domain, qtype, rdclass)
ret = []
if qtype.upper() == 'PTR':
try:
n = dns.reversename.from_address(domain)
domain = n.to_text()
except dns.exception.SyntaxError:
pass
except Exception as e:
raise AnsibleError("dns.reversename unhandled exception %s" % to_native(e))
try:
answers = myres.query(domain, qtype, rdclass=rdclass)
for rdata in answers:
s = rdata.to_text()
if qtype.upper() == 'TXT':
s = s[1:-1] # Strip outside quotes on TXT rdata
if flat:
ret.append(s)
else:
try:
rd = make_rdata_dict(rdata)
rd['owner'] = answers.canonical_name.to_text()
rd['type'] = dns.rdatatype.to_text(rdata.rdtype)
rd['ttl'] = answers.rrset.ttl
rd['class'] = dns.rdataclass.to_text(rdata.rdclass)
ret.append(rd)
except Exception as e:
ret.append(str(e))
except dns.resolver.NXDOMAIN:
ret.append('NXDOMAIN')
except dns.resolver.NoAnswer:
ret.append("")
except dns.resolver.Timeout:
ret.append('')
except dns.exception.DNSException as e:
raise AnsibleError("dns.resolver unhandled exception %s" % to_native(e))
return ret
|
kencochrane/docker-django-demo | refs/heads/master | dockerdemo/voting/models.py | 1 | from __future__ import unicode_literals
import datetime
from django.db import models
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', auto_now_add=True)
last_update = models.DateTimeField('last updated', auto_now=True)
def __str__(self):
return self.question_text
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
@property
def votes(self):
"""How many votes does this choice have."""
return self.vote_set.count()
def __str__(self):
return self.choice_text
class Vote(models.Model):
vote_date = models.DateTimeField('date voted', auto_now=True)
selection = models.ForeignKey(Choice, on_delete=models.CASCADE)
ip_address = models.GenericIPAddressField()
def old_vote(self):
"""Votes older then 2 days are old"""
return self.vote_date <= timezone.now() - datetime.timedelta(days=2)
def __str__(self):
return "{}:{}".format(self.ip_address, self.selection)
|
nishad89/newfies-dialer | refs/heads/master | addons/samples/namegen/__init__.py | 23 | import pkg_resources
pkg_resources.declare_namespace(__name__)
from .namegen import NameGenerator
namegen = NameGenerator()
|
dsm054/pandas | refs/heads/master | pandas/io/sas/sas7bdat.py | 1 | """
Read SAS7BDAT files
Based on code written by Jared Hobbs:
https://bitbucket.org/jaredhobbs/sas7bdat
See also:
https://github.com/BioStatMatt/sas7bdat
Partial documentation of the file format:
https://cran.r-project.org/web/packages/sas7bdat/vignettes/sas7bdat.pdf
Reference for binary data compression:
http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/CUJ/1992/9210/ross/ross.htm
"""
from datetime import datetime
import struct
import numpy as np
from pandas.errors import EmptyDataError
import pandas as pd
from pandas import compat
from pandas.io.common import BaseIterator, get_filepath_or_buffer
from pandas.io.sas._sas import Parser
import pandas.io.sas.sas_constants as const
class _subheader_pointer(object):
pass
class _column(object):
pass
# SAS7BDAT represents a SAS data file in SAS7BDAT format.
class SAS7BDATReader(BaseIterator):
"""
Read SAS files in SAS7BDAT format.
Parameters
----------
path_or_buf : path name or buffer
Name of SAS file or file-like object pointing to SAS file
contents.
index : column identifier, defaults to None
Column to use as index.
convert_dates : boolean, defaults to True
Attempt to convert dates to Pandas datetime values. Note that
some rarely used SAS date formats may be unsupported.
blank_missing : boolean, defaults to True
Convert empty strings to missing values (SAS uses blanks to
indicate missing character variables).
chunksize : int, defaults to None
Return SAS7BDATReader object for iterations, returns chunks
with given number of lines.
encoding : string, defaults to None
String encoding.
convert_text : bool, defaults to True
If False, text variables are left as raw bytes.
convert_header_text : bool, defaults to True
If False, header text, including column names, are left as raw
bytes.
"""
def __init__(self, path_or_buf, index=None, convert_dates=True,
blank_missing=True, chunksize=None, encoding=None,
convert_text=True, convert_header_text=True):
self.index = index
self.convert_dates = convert_dates
self.blank_missing = blank_missing
self.chunksize = chunksize
self.encoding = encoding
self.convert_text = convert_text
self.convert_header_text = convert_header_text
self.default_encoding = "latin-1"
self.compression = ""
self.column_names_strings = []
self.column_names = []
self.column_formats = []
self.columns = []
self._current_page_data_subheader_pointers = []
self._cached_page = None
self._column_data_lengths = []
self._column_data_offsets = []
self._column_types = []
self._current_row_in_file_index = 0
self._current_row_on_page_index = 0
self._current_row_in_file_index = 0
self._path_or_buf, _, _, _ = get_filepath_or_buffer(path_or_buf)
if isinstance(self._path_or_buf, compat.string_types):
self._path_or_buf = open(self._path_or_buf, 'rb')
self.handle = self._path_or_buf
self._get_properties()
self._parse_metadata()
def column_data_lengths(self):
"""Return a numpy int64 array of the column data lengths"""
return np.asarray(self._column_data_lengths, dtype=np.int64)
def column_data_offsets(self):
"""Return a numpy int64 array of the column offsets"""
return np.asarray(self._column_data_offsets, dtype=np.int64)
def column_types(self):
"""Returns a numpy character array of the column types:
s (string) or d (double)"""
return np.asarray(self._column_types, dtype=np.dtype('S1'))
def close(self):
try:
self.handle.close()
except AttributeError:
pass
def _get_properties(self):
# Check magic number
self._path_or_buf.seek(0)
self._cached_page = self._path_or_buf.read(288)
if self._cached_page[0:len(const.magic)] != const.magic:
self.close()
raise ValueError("magic number mismatch (not a SAS file?)")
# Get alignment information
align1, align2 = 0, 0
buf = self._read_bytes(const.align_1_offset, const.align_1_length)
if buf == const.u64_byte_checker_value:
align2 = const.align_2_value
self.U64 = True
self._int_length = 8
self._page_bit_offset = const.page_bit_offset_x64
self._subheader_pointer_length = const.subheader_pointer_length_x64
else:
self.U64 = False
self._page_bit_offset = const.page_bit_offset_x86
self._subheader_pointer_length = const.subheader_pointer_length_x86
self._int_length = 4
buf = self._read_bytes(const.align_2_offset, const.align_2_length)
if buf == const.align_1_checker_value:
align1 = const.align_2_value
total_align = align1 + align2
# Get endianness information
buf = self._read_bytes(const.endianness_offset,
const.endianness_length)
if buf == b'\x01':
self.byte_order = "<"
else:
self.byte_order = ">"
# Get encoding information
buf = self._read_bytes(const.encoding_offset, const.encoding_length)[0]
if buf in const.encoding_names:
self.file_encoding = const.encoding_names[buf]
else:
self.file_encoding = "unknown (code=%s)" % str(buf)
# Get platform information
buf = self._read_bytes(const.platform_offset, const.platform_length)
if buf == b'1':
self.platform = "unix"
elif buf == b'2':
self.platform = "windows"
else:
self.platform = "unknown"
buf = self._read_bytes(const.dataset_offset, const.dataset_length)
self.name = buf.rstrip(b'\x00 ')
if self.convert_header_text:
self.name = self.name.decode(
self.encoding or self.default_encoding)
buf = self._read_bytes(const.file_type_offset, const.file_type_length)
self.file_type = buf.rstrip(b'\x00 ')
if self.convert_header_text:
self.file_type = self.file_type.decode(
self.encoding or self.default_encoding)
# Timestamp is epoch 01/01/1960
epoch = datetime(1960, 1, 1)
x = self._read_float(const.date_created_offset + align1,
const.date_created_length)
self.date_created = epoch + pd.to_timedelta(x, unit='s')
x = self._read_float(const.date_modified_offset + align1,
const.date_modified_length)
self.date_modified = epoch + pd.to_timedelta(x, unit='s')
self.header_length = self._read_int(const.header_size_offset + align1,
const.header_size_length)
# Read the rest of the header into cached_page.
buf = self._path_or_buf.read(self.header_length - 288)
self._cached_page += buf
if len(self._cached_page) != self.header_length:
self.close()
raise ValueError("The SAS7BDAT file appears to be truncated.")
self._page_length = self._read_int(const.page_size_offset + align1,
const.page_size_length)
self._page_count = self._read_int(const.page_count_offset + align1,
const.page_count_length)
buf = self._read_bytes(const.sas_release_offset + total_align,
const.sas_release_length)
self.sas_release = buf.rstrip(b'\x00 ')
if self.convert_header_text:
self.sas_release = self.sas_release.decode(
self.encoding or self.default_encoding)
buf = self._read_bytes(const.sas_server_type_offset + total_align,
const.sas_server_type_length)
self.server_type = buf.rstrip(b'\x00 ')
if self.convert_header_text:
self.server_type = self.server_type.decode(
self.encoding or self.default_encoding)
buf = self._read_bytes(const.os_version_number_offset + total_align,
const.os_version_number_length)
self.os_version = buf.rstrip(b'\x00 ')
if self.convert_header_text:
self.os_version = self.os_version.decode(
self.encoding or self.default_encoding)
buf = self._read_bytes(const.os_name_offset + total_align,
const.os_name_length)
buf = buf.rstrip(b'\x00 ')
if len(buf) > 0:
self.os_name = buf.decode(self.encoding or self.default_encoding)
else:
buf = self._read_bytes(const.os_maker_offset + total_align,
const.os_maker_length)
self.os_name = buf.rstrip(b'\x00 ')
if self.convert_header_text:
self.os_name = self.os_name.decode(
self.encoding or self.default_encoding)
def __next__(self):
da = self.read(nrows=self.chunksize or 1)
if da is None:
raise StopIteration
return da
# Read a single float of the given width (4 or 8).
def _read_float(self, offset, width):
if width not in (4, 8):
self.close()
raise ValueError("invalid float width")
buf = self._read_bytes(offset, width)
fd = "f" if width == 4 else "d"
return struct.unpack(self.byte_order + fd, buf)[0]
# Read a single signed integer of the given width (1, 2, 4 or 8).
def _read_int(self, offset, width):
if width not in (1, 2, 4, 8):
self.close()
raise ValueError("invalid int width")
buf = self._read_bytes(offset, width)
it = {1: "b", 2: "h", 4: "l", 8: "q"}[width]
iv = struct.unpack(self.byte_order + it, buf)[0]
return iv
def _read_bytes(self, offset, length):
if self._cached_page is None:
self._path_or_buf.seek(offset)
buf = self._path_or_buf.read(length)
if len(buf) < length:
self.close()
msg = "Unable to read {:d} bytes from file position {:d}."
raise ValueError(msg.format(length, offset))
return buf
else:
if offset + length > len(self._cached_page):
self.close()
raise ValueError("The cached page is too small.")
return self._cached_page[offset:offset + length]
def _parse_metadata(self):
done = False
while not done:
self._cached_page = self._path_or_buf.read(self._page_length)
if len(self._cached_page) <= 0:
break
if len(self._cached_page) != self._page_length:
self.close()
raise ValueError(
"Failed to read a meta data page from the SAS file.")
done = self._process_page_meta()
def _process_page_meta(self):
self._read_page_header()
pt = [const.page_meta_type, const.page_amd_type] + const.page_mix_types
if self._current_page_type in pt:
self._process_page_metadata()
is_data_page = self._current_page_type & const.page_data_type
is_mix_page = self._current_page_type in const.page_mix_types
return (is_data_page or is_mix_page
or self._current_page_data_subheader_pointers != [])
def _read_page_header(self):
bit_offset = self._page_bit_offset
tx = const.page_type_offset + bit_offset
self._current_page_type = self._read_int(tx, const.page_type_length)
tx = const.block_count_offset + bit_offset
self._current_page_block_count = self._read_int(
tx, const.block_count_length)
tx = const.subheader_count_offset + bit_offset
self._current_page_subheaders_count = (
self._read_int(tx, const.subheader_count_length))
def _process_page_metadata(self):
bit_offset = self._page_bit_offset
for i in range(self._current_page_subheaders_count):
pointer = self._process_subheader_pointers(
const.subheader_pointers_offset + bit_offset, i)
if pointer.length == 0:
continue
if pointer.compression == const.truncated_subheader_id:
continue
subheader_signature = self._read_subheader_signature(
pointer.offset)
subheader_index = (
self._get_subheader_index(subheader_signature,
pointer.compression, pointer.ptype))
self._process_subheader(subheader_index, pointer)
def _get_subheader_index(self, signature, compression, ptype):
index = const.subheader_signature_to_index.get(signature)
if index is None:
f1 = ((compression == const.compressed_subheader_id) or
(compression == 0))
f2 = (ptype == const.compressed_subheader_type)
if (self.compression != "") and f1 and f2:
index = const.SASIndex.data_subheader_index
else:
self.close()
raise ValueError("Unknown subheader signature")
return index
def _process_subheader_pointers(self, offset, subheader_pointer_index):
subheader_pointer_length = self._subheader_pointer_length
total_offset = (offset +
subheader_pointer_length * subheader_pointer_index)
subheader_offset = self._read_int(total_offset, self._int_length)
total_offset += self._int_length
subheader_length = self._read_int(total_offset, self._int_length)
total_offset += self._int_length
subheader_compression = self._read_int(total_offset, 1)
total_offset += 1
subheader_type = self._read_int(total_offset, 1)
x = _subheader_pointer()
x.offset = subheader_offset
x.length = subheader_length
x.compression = subheader_compression
x.ptype = subheader_type
return x
def _read_subheader_signature(self, offset):
subheader_signature = self._read_bytes(offset, self._int_length)
return subheader_signature
def _process_subheader(self, subheader_index, pointer):
offset = pointer.offset
length = pointer.length
if subheader_index == const.SASIndex.row_size_index:
processor = self._process_rowsize_subheader
elif subheader_index == const.SASIndex.column_size_index:
processor = self._process_columnsize_subheader
elif subheader_index == const.SASIndex.column_text_index:
processor = self._process_columntext_subheader
elif subheader_index == const.SASIndex.column_name_index:
processor = self._process_columnname_subheader
elif subheader_index == const.SASIndex.column_attributes_index:
processor = self._process_columnattributes_subheader
elif subheader_index == const.SASIndex.format_and_label_index:
processor = self._process_format_subheader
elif subheader_index == const.SASIndex.column_list_index:
processor = self._process_columnlist_subheader
elif subheader_index == const.SASIndex.subheader_counts_index:
processor = self._process_subheader_counts
elif subheader_index == const.SASIndex.data_subheader_index:
self._current_page_data_subheader_pointers.append(pointer)
return
else:
raise ValueError("unknown subheader index")
processor(offset, length)
def _process_rowsize_subheader(self, offset, length):
int_len = self._int_length
lcs_offset = offset
lcp_offset = offset
if self.U64:
lcs_offset += 682
lcp_offset += 706
else:
lcs_offset += 354
lcp_offset += 378
self.row_length = self._read_int(
offset + const.row_length_offset_multiplier * int_len, int_len)
self.row_count = self._read_int(
offset + const.row_count_offset_multiplier * int_len, int_len)
self.col_count_p1 = self._read_int(
offset + const.col_count_p1_multiplier * int_len, int_len)
self.col_count_p2 = self._read_int(
offset + const.col_count_p2_multiplier * int_len, int_len)
mx = const.row_count_on_mix_page_offset_multiplier * int_len
self._mix_page_row_count = self._read_int(offset + mx, int_len)
self._lcs = self._read_int(lcs_offset, 2)
self._lcp = self._read_int(lcp_offset, 2)
def _process_columnsize_subheader(self, offset, length):
int_len = self._int_length
offset += int_len
self.column_count = self._read_int(offset, int_len)
if (self.col_count_p1 + self.col_count_p2 !=
self.column_count):
print("Warning: column count mismatch (%d + %d != %d)\n",
self.col_count_p1, self.col_count_p2, self.column_count)
# Unknown purpose
def _process_subheader_counts(self, offset, length):
pass
def _process_columntext_subheader(self, offset, length):
offset += self._int_length
text_block_size = self._read_int(offset, const.text_block_size_length)
buf = self._read_bytes(offset, text_block_size)
cname_raw = buf[0:text_block_size].rstrip(b"\x00 ")
cname = cname_raw
if self.convert_header_text:
cname = cname.decode(self.encoding or self.default_encoding)
self.column_names_strings.append(cname)
if len(self.column_names_strings) == 1:
compression_literal = ""
for cl in const.compression_literals:
if cl in cname_raw:
compression_literal = cl
self.compression = compression_literal
offset -= self._int_length
offset1 = offset + 16
if self.U64:
offset1 += 4
buf = self._read_bytes(offset1, self._lcp)
compression_literal = buf.rstrip(b"\x00")
if compression_literal == "":
self._lcs = 0
offset1 = offset + 32
if self.U64:
offset1 += 4
buf = self._read_bytes(offset1, self._lcp)
self.creator_proc = buf[0:self._lcp]
elif compression_literal == const.rle_compression:
offset1 = offset + 40
if self.U64:
offset1 += 4
buf = self._read_bytes(offset1, self._lcp)
self.creator_proc = buf[0:self._lcp]
elif self._lcs > 0:
self._lcp = 0
offset1 = offset + 16
if self.U64:
offset1 += 4
buf = self._read_bytes(offset1, self._lcs)
self.creator_proc = buf[0:self._lcp]
if self.convert_header_text:
if hasattr(self, "creator_proc"):
self.creator_proc = self.creator_proc.decode(
self.encoding or self.default_encoding)
def _process_columnname_subheader(self, offset, length):
int_len = self._int_length
offset += int_len
column_name_pointers_count = (length - 2 * int_len - 12) // 8
for i in range(column_name_pointers_count):
text_subheader = offset + const.column_name_pointer_length * \
(i + 1) + const.column_name_text_subheader_offset
col_name_offset = offset + const.column_name_pointer_length * \
(i + 1) + const.column_name_offset_offset
col_name_length = offset + const.column_name_pointer_length * \
(i + 1) + const.column_name_length_offset
idx = self._read_int(
text_subheader, const.column_name_text_subheader_length)
col_offset = self._read_int(
col_name_offset, const.column_name_offset_length)
col_len = self._read_int(
col_name_length, const.column_name_length_length)
name_str = self.column_names_strings[idx]
self.column_names.append(name_str[col_offset:col_offset + col_len])
def _process_columnattributes_subheader(self, offset, length):
int_len = self._int_length
column_attributes_vectors_count = (
length - 2 * int_len - 12) // (int_len + 8)
for i in range(column_attributes_vectors_count):
col_data_offset = (offset + int_len +
const.column_data_offset_offset +
i * (int_len + 8))
col_data_len = (offset + 2 * int_len +
const.column_data_length_offset +
i * (int_len + 8))
col_types = (offset + 2 * int_len +
const.column_type_offset + i * (int_len + 8))
x = self._read_int(col_data_offset, int_len)
self._column_data_offsets.append(x)
x = self._read_int(col_data_len, const.column_data_length_length)
self._column_data_lengths.append(x)
x = self._read_int(col_types, const.column_type_length)
self._column_types.append(b'd' if x == 1 else b's')
def _process_columnlist_subheader(self, offset, length):
# unknown purpose
pass
def _process_format_subheader(self, offset, length):
int_len = self._int_length
text_subheader_format = (
offset +
const.column_format_text_subheader_index_offset +
3 * int_len)
col_format_offset = (offset +
const.column_format_offset_offset +
3 * int_len)
col_format_len = (offset +
const.column_format_length_offset +
3 * int_len)
text_subheader_label = (
offset +
const.column_label_text_subheader_index_offset +
3 * int_len)
col_label_offset = (offset +
const.column_label_offset_offset +
3 * int_len)
col_label_len = offset + const.column_label_length_offset + 3 * int_len
x = self._read_int(text_subheader_format,
const.column_format_text_subheader_index_length)
format_idx = min(x, len(self.column_names_strings) - 1)
format_start = self._read_int(
col_format_offset, const.column_format_offset_length)
format_len = self._read_int(
col_format_len, const.column_format_length_length)
label_idx = self._read_int(
text_subheader_label,
const.column_label_text_subheader_index_length)
label_idx = min(label_idx, len(self.column_names_strings) - 1)
label_start = self._read_int(
col_label_offset, const.column_label_offset_length)
label_len = self._read_int(col_label_len,
const.column_label_length_length)
label_names = self.column_names_strings[label_idx]
column_label = label_names[label_start: label_start + label_len]
format_names = self.column_names_strings[format_idx]
column_format = format_names[format_start: format_start + format_len]
current_column_number = len(self.columns)
col = _column()
col.col_id = current_column_number
col.name = self.column_names[current_column_number]
col.label = column_label
col.format = column_format
col.ctype = self._column_types[current_column_number]
col.length = self._column_data_lengths[current_column_number]
self.column_formats.append(column_format)
self.columns.append(col)
def read(self, nrows=None):
if (nrows is None) and (self.chunksize is not None):
nrows = self.chunksize
elif nrows is None:
nrows = self.row_count
if len(self._column_types) == 0:
self.close()
raise EmptyDataError("No columns to parse from file")
if self._current_row_in_file_index >= self.row_count:
return None
m = self.row_count - self._current_row_in_file_index
if nrows > m:
nrows = m
nd = self._column_types.count(b'd')
ns = self._column_types.count(b's')
self._string_chunk = np.empty((ns, nrows), dtype=np.object)
self._byte_chunk = np.zeros((nd, 8 * nrows), dtype=np.uint8)
self._current_row_in_chunk_index = 0
p = Parser(self)
p.read(nrows)
rslt = self._chunk_to_dataframe()
if self.index is not None:
rslt = rslt.set_index(self.index)
return rslt
def _read_next_page(self):
self._current_page_data_subheader_pointers = []
self._cached_page = self._path_or_buf.read(self._page_length)
if len(self._cached_page) <= 0:
return True
elif len(self._cached_page) != self._page_length:
self.close()
msg = ("failed to read complete page from file "
"(read {:d} of {:d} bytes)")
raise ValueError(msg.format(len(self._cached_page),
self._page_length))
self._read_page_header()
page_type = self._current_page_type
if page_type == const.page_meta_type:
self._process_page_metadata()
is_data_page = page_type & const.page_data_type
pt = [const.page_meta_type] + const.page_mix_types
if not is_data_page and self._current_page_type not in pt:
return self._read_next_page()
return False
def _chunk_to_dataframe(self):
n = self._current_row_in_chunk_index
m = self._current_row_in_file_index
ix = range(m - n, m)
rslt = pd.DataFrame(index=ix)
js, jb = 0, 0
for j in range(self.column_count):
name = self.column_names[j]
if self._column_types[j] == b'd':
rslt[name] = self._byte_chunk[jb, :].view(
dtype=self.byte_order + 'd')
rslt[name] = np.asarray(rslt[name], dtype=np.float64)
if self.convert_dates:
unit = None
if self.column_formats[j] in const.sas_date_formats:
unit = 'd'
elif self.column_formats[j] in const.sas_datetime_formats:
unit = 's'
if unit:
rslt[name] = pd.to_datetime(rslt[name], unit=unit,
origin="1960-01-01")
jb += 1
elif self._column_types[j] == b's':
rslt[name] = self._string_chunk[js, :]
if self.convert_text and (self.encoding is not None):
rslt[name] = rslt[name].str.decode(
self.encoding or self.default_encoding)
if self.blank_missing:
ii = rslt[name].str.len() == 0
rslt.loc[ii, name] = np.nan
js += 1
else:
self.close()
raise ValueError("unknown column type %s" %
self._column_types[j])
return rslt
|
mSenyor/sl4a | refs/heads/master | python/gdata/tests/gdata_tests/calendar/service_test.py | 87 | #!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# 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.
__author__ = 'api.rboyd@google.com (Ryan Boyd)'
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import atom.mock_http
import gdata.calendar
import gdata.calendar.service
import random
import getpass
# Commented out as dateutil is not in this repository
#from dateutil.parser import parse
username = ''
password = ''
class CalendarServiceUnitTest(unittest.TestCase):
def setUp(self):
self.cal_client = gdata.calendar.service.CalendarService()
self.cal_client.email = username
self.cal_client.password = password
self.cal_client.source = 'GCalendarClient "Unit" Tests'
def tearDown(self):
# No teardown needed
pass
def testPostUpdateAndDeleteSubscription(self):
"""Test posting a new subscription, updating it, deleting it"""
self.cal_client.ProgrammaticLogin()
subscription_id = 'c4o4i7m2lbamc4k26sc2vokh5g%40group.calendar.google.com'
subscription_url = '%s%s' % (
'http://www.google.com/calendar/feeds/default/allcalendars/full/',
subscription_id)
# Subscribe to Google Doodles calendar
calendar = gdata.calendar.CalendarListEntry()
calendar.id = atom.Id(text=subscription_id)
returned_calendar = self.cal_client.InsertCalendarSubscription(calendar)
self.assertEquals(subscription_url, returned_calendar.id.text)
self.assertEquals('Google Doodles', returned_calendar.title.text)
# Update subscription
calendar_to_update = self.cal_client.GetCalendarListEntry(subscription_url)
self.assertEquals('Google Doodles', calendar_to_update.title.text)
self.assertEquals('true', calendar_to_update.selected.value)
calendar_to_update.selected.value = 'false'
self.assertEquals('false', calendar_to_update.selected.value)
updated_calendar = self.cal_client.UpdateCalendar(calendar_to_update)
self.assertEquals('false', updated_calendar.selected.value)
# Delete subscription
response = self.cal_client.DeleteCalendarEntry(
returned_calendar.GetEditLink().href)
self.assertEquals(True, response)
def testPostUpdateAndDeleteCalendar(self):
"""Test posting a new calendar, updating it, deleting it"""
self.cal_client.ProgrammaticLogin()
# New calendar to create
title='Little League Schedule'
description='This calendar contains practice and game times'
time_zone='America/Los_Angeles'
hidden=False
location='Oakland'
color='#2952A3'
# Calendar object
calendar = gdata.calendar.CalendarListEntry()
calendar.title = atom.Title(text=title)
calendar.summary = atom.Summary(text=description)
calendar.where = gdata.calendar.Where(value_string=location)
calendar.color = gdata.calendar.Color(value=color)
calendar.timezone = gdata.calendar.Timezone(value=time_zone)
if hidden:
calendar.hidden = gdata.calendar.Hidden(value='true')
else:
calendar.hidden = gdata.calendar.Hidden(value='false')
# Create calendar
new_calendar = self.cal_client.InsertCalendar(new_calendar=calendar)
self.assertEquals(title, new_calendar.title.text)
self.assertEquals(description, new_calendar.summary.text)
self.assertEquals(location, new_calendar.where.value_string)
self.assertEquals(color, new_calendar.color.value)
self.assertEquals(time_zone, new_calendar.timezone.value)
if hidden:
self.assertEquals('true', new_calendar.hidden.value)
else:
self.assertEquals('false', new_calendar.hidden.value)
# Update calendar
calendar_to_update = self.cal_client.GetCalendarListEntry(
new_calendar.id.text)
updated_title = 'This is the updated title'
calendar_to_update.title.text = updated_title
updated_calendar = self.cal_client.UpdateCalendar(calendar_to_update)
self.assertEquals(updated_title, updated_calendar.title.text)
# Delete calendar
calendar_to_delete = self.cal_client.GetCalendarListEntry(
new_calendar.id.text)
self.cal_client.Delete(calendar_to_delete.GetEditLink().href)
return new_calendar
def testPostAndDeleteExtendedPropertyEvent(self):
"""Test posting a new entry with an extended property, deleting it"""
# Get random data for creating event
r = random.Random()
r.seed()
random_event_number = str(r.randint(100000,1000000))
random_event_title = 'My Random Extended Property Test Event %s' % (
random_event_number)
# Set event data
event = gdata.calendar.CalendarEventEntry()
event.author.append(atom.Author(name=atom.Name(text='GData Test user')))
event.title = atom.Title(text=random_event_title)
event.content = atom.Content(text='Picnic with some lunch')
event.extended_property.append(gdata.calendar.ExtendedProperty(
name='prop test name', value='prop test value'))
# Insert event
self.cal_client.ProgrammaticLogin()
new_event = self.cal_client.InsertEvent(event,
'/calendar/feeds/default/private/full')
self.assertEquals(event.extended_property[0].value,
new_event.extended_property[0].value)
# Delete the event
self.cal_client.DeleteEvent(new_event.GetEditLink().href)
# WARNING: Due to server-side issues, this test takes a while (~60seconds)
def testPostEntryWithCommentAndDelete(self):
"""Test posting a new entry with an extended property, deleting it"""
# Get random data for creating event
r = random.Random()
r.seed()
random_event_number = str(r.randint(100000,1000000))
random_event_title = 'My Random Comments Test Event %s' % (
random_event_number)
# Set event data
event = gdata.calendar.CalendarEventEntry()
event.author.append(atom.Author(name=atom.Name(text='GData Test user')))
event.title = atom.Title(text=random_event_title)
event.content = atom.Content(text='Picnic with some lunch')
# Insert event
self.cal_client.ProgrammaticLogin()
new_event = self.cal_client.InsertEvent(event,
'/calendar/feeds/default/private/full')
# Get comments feed
comments_url = new_event.comments.feed_link.href
comments_query = gdata.calendar.service.CalendarEventCommentQuery(comments_url)
comments_feed = self.cal_client.CalendarQuery(comments_query)
# Add comment
comments_entry = gdata.calendar.CalendarEventCommentEntry()
comments_entry.content = atom.Content(text='Comments content')
comments_entry.author.append(
atom.Author(name=atom.Name(text='GData Test user'),
email=atom.Email(text='gdata.ops.demo@gmail.com')))
new_comments_entry = self.cal_client.InsertEventComment(comments_entry,
comments_feed.GetPostLink().href)
# Delete the event
event_to_delete = self.cal_client.GetCalendarEventEntry(new_event.id.text)
self.cal_client.DeleteEvent(event_to_delete.GetEditLink().href)
def testPostQueryUpdateAndDeleteEvents(self):
"""Test posting a new entry, updating it, deleting it, querying for it"""
# Get random data for creating event
r = random.Random()
r.seed()
random_event_number = str(r.randint(100000,1000000))
random_event_title = 'My Random Test Event %s' % random_event_number
random_start_hour = (r.randint(1,1000000) % 23)
random_end_hour = random_start_hour + 1
non_random_start_minute = 0
non_random_end_minute = 0
random_month = (r.randint(1,1000000) % 12 + 1)
random_day_of_month = (r.randint(1,1000000) % 28 + 1)
non_random_year = 2008
start_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % (
non_random_year, random_month, random_day_of_month,
random_start_hour, non_random_start_minute,)
end_time = '%04d-%02d-%02dT%02d:%02d:00.000-05:00' % (
non_random_year, random_month, random_day_of_month,
random_end_hour, non_random_end_minute,)
# Set event data
event = gdata.calendar.CalendarEventEntry()
event.author.append(atom.Author(name=atom.Name(text='GData Test user')))
event.title = atom.Title(text=random_event_title)
event.content = atom.Content(text='Picnic with some lunch')
event.where.append(gdata.calendar.Where(value_string='Down by the river'))
event.when.append(gdata.calendar.When(start_time=start_time,end_time=end_time))
# Insert event
self.cal_client.ProgrammaticLogin()
new_event = self.cal_client.InsertEvent(event,
'/calendar/feeds/default/private/full')
# Ensure that atom data returned from calendar server equals atom data sent
self.assertEquals(event.title.text, new_event.title.text)
self.assertEquals(event.content.text, new_event.content.text)
# Ensure that gd:where data returned from calendar equals value sent
self.assertEquals(event.where[0].value_string,
new_event.where[0].value_string)
# Commented out as dateutil is not in this repository
# Ensure that dates returned from calendar server equals dates sent
#start_time_py = parse(event.when[0].start_time)
#start_time_py_new = parse(new_event.when[0].start_time)
#self.assertEquals(start_time_py, start_time_py_new)
#end_time_py = parse(event.when[0].end_time)
#end_time_py_new = parse(new_event.when[0].end_time)
#self.assertEquals(end_time_py, end_time_py_new)
# Update event
event_to_update = new_event
updated_title_text = event_to_update.title.text + ' - UPDATED'
event_to_update.title = atom.Title(text=updated_title_text)
updated_event = self.cal_client.UpdateEvent(
event_to_update.GetEditLink().href, event_to_update)
# Ensure that updated title was set in the updated event
self.assertEquals(event_to_update.title.text, updated_event.title.text)
# Delete the event
self.cal_client.DeleteEvent(updated_event.GetEditLink().href)
# Ensure deleted event is marked as canceled in the feed
after_delete_query = gdata.calendar.service.CalendarEventQuery()
after_delete_query.updated_min = '2007-01-01'
after_delete_query.text_query = str(random_event_number)
after_delete_query.max_results = '1'
after_delete_query_result = self.cal_client.CalendarQuery(
after_delete_query)
# Ensure feed returned at max after_delete_query.max_results events
self.assert_(
len(after_delete_query_result.entry) <= after_delete_query.max_results)
# Ensure status of returned event is canceled
self.assertEquals(after_delete_query_result.entry[0].event_status.value,
'CANCELED')
def testCreateAndDeleteEventUsingBatch(self):
# Get random data for creating event
r = random.Random()
r.seed()
random_event_number = str(r.randint(100000,1000000))
random_event_title = 'My Random Comments Test Event %s' % (
random_event_number)
# Set event data
event = gdata.calendar.CalendarEventEntry()
event.author.append(atom.Author(name=atom.Name(text='GData Test user')))
event.title = atom.Title(text=random_event_title)
event.content = atom.Content(text='Picnic with some lunch')
# Form a batch request
batch_request = gdata.calendar.CalendarEventFeed()
batch_request.AddInsert(entry=event)
# Execute the batch request to insert the event.
self.cal_client.ProgrammaticLogin()
batch_result = self.cal_client.ExecuteBatch(batch_request,
gdata.calendar.service.DEFAULT_BATCH_URL)
self.assertEquals(len(batch_result.entry), 1)
self.assertEquals(batch_result.entry[0].title.text, random_event_title)
self.assertEquals(batch_result.entry[0].batch_operation.type,
gdata.BATCH_INSERT)
self.assertEquals(batch_result.GetBatchLink().href,
gdata.calendar.service.DEFAULT_BATCH_URL)
# Create a batch request to delete the newly created entry.
batch_delete_request = gdata.calendar.CalendarEventFeed()
batch_delete_request.AddDelete(entry=batch_result.entry[0])
batch_delete_result = self.cal_client.ExecuteBatch(batch_delete_request,
batch_result.GetBatchLink().href)
self.assertEquals(len(batch_delete_result.entry), 1)
self.assertEquals(batch_delete_result.entry[0].batch_operation.type,
gdata.BATCH_DELETE)
def testCorrectReturnTypesForGetMethods(self):
self.cal_client.ProgrammaticLogin()
result = self.cal_client.GetCalendarEventFeed()
self.assertEquals(isinstance(result, gdata.calendar.CalendarEventFeed),
True)
def testValidHostName(self):
mock_http = atom.mock_http.MockHttpClient()
response = atom.mock_http.MockResponse(body='<entry/>', status=200,
reason='OK')
mock_http.add_response(response, 'GET',
'https://www.google.com/calendar/feeds/default/allcalendars/full')
self.cal_client.ssl = True
self.cal_client.http_client = mock_http
self.cal_client.SetAuthSubToken('foo')
self.assertEquals(str(self.cal_client.token_store.find_token(
'https://www.google.com/calendar/feeds/default/allcalendars/full')),
'AuthSub token=foo')
resp = self.cal_client.Get('/calendar/feeds/default/allcalendars/full')
self.assert_(resp is not None)
class CalendarEventQueryUnitTest(unittest.TestCase):
def setUp(self):
self.query = gdata.calendar.service.CalendarEventQuery()
def testOrderByValidatesValues(self):
self.query.orderby = 'lastmodified'
self.assertEquals(self.query.orderby, 'lastmodified')
try:
self.query.orderby = 'illegal input'
self.fail()
except gdata.calendar.service.Error:
self.assertEquals(self.query.orderby, 'lastmodified')
def testSortOrderValidatesValues(self):
self.query.sortorder = 'a'
self.assertEquals(self.query.sortorder, 'a')
try:
self.query.sortorder = 'illegal input'
self.fail()
except gdata.calendar.service.Error:
self.assertEquals(self.query.sortorder, 'a')
def testTimezoneParameter(self):
self.query.ctz = 'America/Los_Angeles'
self.assertEquals(self.query['ctz'], 'America/Los_Angeles')
self.assert_(self.query.ToUri().find('America%2FLos_Angeles') > -1)
if __name__ == '__main__':
print ('Google Calendar Test\nNOTE: Please run these tests only with a '
'test account. The tests may delete or update your data.')
username = raw_input('Please enter your username: ')
password = getpass.getpass()
unittest.main()
|
ga4gh/ga4gh-schemas | refs/heads/master | python/ga4gh/schemas/protocol.py | 4 | """
Definitions of the GA4GH protocol types.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import json
import inspect
import sys
import array
from _protocol_version import version # noqa
from ga4gh.common_pb2 import * # noqa
from ga4gh.metadata_pb2 import * # noqa
from ga4gh.metadata_service_pb2 import * # noqa
from ga4gh.read_service_pb2 import * # noqa
from ga4gh.reads_pb2 import * # noqa
from ga4gh.reference_service_pb2 import * # noqa
from ga4gh.references_pb2 import * # noqa
from ga4gh.variant_service_pb2 import * # noqa
from ga4gh.variants_pb2 import * # noqa
from ga4gh.allele_annotations_pb2 import * # noqa
from ga4gh.allele_annotation_service_pb2 import * # noqa
from ga4gh.sequence_annotations_pb2 import * # noqa
from ga4gh.sequence_annotation_service_pb2 import * # noqa
from ga4gh.bio_metadata_pb2 import * # noqa
from ga4gh.bio_metadata_service_pb2 import * # noqa
from ga4gh.genotype_phenotype_pb2 import * # noqa
from ga4gh.genotype_phenotype_service_pb2 import * # noqa
from ga4gh.rna_quantification_pb2 import * # noqa
from ga4gh.rna_quantification_service_pb2 import * # noqa
from ga4gh.peer_service_pb2 import * # noqa
import ga4gh.common_pb2 as common
import hacks.googhack as googhack
# This is necessary because we have a package in the same directory as this
# file named 'google', so an 'import google' attempts to import that package
# instead of the top-level google package.
json_format = googhack.getJsonFormat()
message = googhack.getMessage()
struct_pb2 = googhack.getStructPb2()
def setAttribute(values, value):
"""
Takes the values of an attribute value list and attempts to append
attributes of the proper type, inferred from their Python type.
"""
if isinstance(value, int):
values.add().int32_value = value
elif isinstance(value, float):
values.add().double_value = value
elif isinstance(value, long):
values.add().int64_value = value
elif isinstance(value, str):
values.add().string_value = value
elif isinstance(value, bool):
values.add().bool_value = value
elif isinstance(value, (list, tuple, array.array)):
for v in value:
setAttribute(values, v)
elif isinstance(value, dict):
for key in value:
setAttribute(
values.add().attributes.attr[key].values, value[key])
else:
values.add().string_value = str(value)
def deepGetAttr(obj, path):
"""
Resolves a dot-delimited path on an object. If path is not found
an `AttributeError` will be raised.
"""
return reduce(getattr, path.split('.'), obj)
def deepSetAttr(obj, path, val):
"""
Sets a deep attribute on an object by resolving a dot-delimited
path. If path does not exist an `AttributeError` will be raised`.
"""
first, _, rest = path.rpartition('.')
return setattr(deepGetAttr(obj, first) if first else obj, rest, val)
def encodeValue(value):
"""
TODO
"""
if isinstance(value, (list, tuple)):
return [common.AttributeValue(string_value=str(v)) for v in value]
else:
return [common.AttributeValue(string_value=str(value))]
def getValueListName(protocolResponseClass):
"""
Returns the name of the attribute in the specified protocol class
that is used to hold the values in a search response.
"""
return protocolResponseClass.DESCRIPTOR.fields_by_number[1].name
def convertDatetime(t):
"""
Converts the specified datetime object into its appropriate protocol
value. This is the number of milliseconds from the epoch.
"""
epoch = datetime.datetime.utcfromtimestamp(0)
delta = t - epoch
millis = delta.total_seconds() * 1000
return int(millis)
def getValueFromValue(value):
"""
Extract the currently set field from a Value structure
"""
if type(value) != common.AttributeValue:
raise TypeError(
"Expected an AttributeValue, but got {}".format(type(value)))
if value.WhichOneof("value") is None:
raise AttributeError("Nothing set for {}".format(value))
return getattr(value, value.WhichOneof("value"))
def toJson(protoObject, indent=None):
"""
Serialises a protobuf object as json
"""
# Using the internal method because this way we can reformat the JSON
js = json_format.MessageToDict(protoObject, False)
return json.dumps(js, indent=indent)
def toJsonDict(protoObject):
"""
Converts a protobuf object to the raw attributes
i.e. a key/value dictionary
"""
return json.loads(toJson(protoObject))
def fromJson(json, protoClass):
"""
Deserialise json into an instance of protobuf class
"""
return json_format.Parse(json, protoClass())
def validate(json, protoClass):
"""
Check that json represents data that could be used to make
a given protobuf class
"""
try:
fromJson(json, protoClass)
# The json conversion automatically validates
return True
except Exception:
return False
def getProtocolClasses(superclass=message.Message):
"""
Returns all the protocol classes that are subclasses of the
specified superclass. Only 'leaf' classes are returned,
corresponding directly to the classes defined in the protocol.
"""
# We keep a manual list of the superclasses that we define here
# so we can filter them out when we're getting the protocol
# classes.
superclasses = set([message.Message])
thisModule = sys.modules[__name__]
subclasses = []
for name, class_ in inspect.getmembers(thisModule):
if ((inspect.isclass(class_) and
issubclass(class_, superclass) and
class_ not in superclasses)):
subclasses.append(class_)
return subclasses
postMethods = \
[('/callsets/search',
SearchCallSetsRequest, # noqa
SearchCallSetsResponse), # noqa
('/datasets/search',
SearchDatasetsRequest, # noqa
SearchDatasetsResponse), # noqa
('/readgroupsets/search',
SearchReadGroupSetsRequest, # noqa
SearchReadGroupSetsResponse), # noqa
('/reads/search',
SearchReadsRequest, # noqa
SearchReadsResponse), # noqa
('/references/search',
SearchReferencesRequest, # noqa
SearchReferencesResponse), # noqa
('/referencesets/search',
SearchReferenceSetsRequest, # noqa
SearchReferenceSetsResponse), # noqa
('/variants/search',
SearchVariantsRequest, # noqa
SearchVariantsResponse), # noqa
('/datasets/search',
SearchDatasetsRequest, # noqa
SearchDatasetsResponse), # noqa
('/callsets/search',
SearchCallSetsRequest, # noqa
SearchCallSetsResponse), # noqa
('/featuresets/search',
SearchFeatureSetsRequest, # noqa
SearchFeatureSetsResponse), # noqa
('/features/search',
SearchFeaturesRequest, # noqa
SearchFeaturesResponse), # noqa
('/continuoussets/search',
SearchContinuousSetsRequest, # noqa
SearchContinuousSetsResponse), # noqa
('/continuous/search',
SearchContinuousRequest, # noqa
SearchContinuousResponse), # noqa
('/variantsets/search',
SearchVariantSetsRequest, # noqa
SearchVariantSetsResponse), # noqa
('/variantannotations/search',
SearchVariantAnnotationsRequest, # noqa
SearchVariantAnnotationSetsResponse), # noqa
('/variantannotationsets/search',
SearchVariantAnnotationSetsRequest, # noqa
SearchVariantAnnotationSetsResponse), # noqa
('/rnaquantificationsets/search',
SearchRnaQuantificationSetsRequest, # noqa
SearchRnaQuantificationSetsResponse), # noqa
('/rnaquantifications/search',
SearchRnaQuantificationsRequest, # noqa
SearchRnaQuantificationsResponse), # noqa
('/expressionlevels/search',
SearchExpressionLevelsRequest, # noqa
SearchExpressionLevelsResponse)] # noqa
|
rolandovillca/python_introduction_basic | refs/heads/master | threads_and_multiprocess/threads/example02.py | 4 | import threading
import time
class ThreadingExample(object):
'''
Threading example class.
The run() method will be started and
it will run in the background until the application exits.
'''
def __init__(self, interval=1):
'''
Constructor
:type interval: int
:param interval: Check interval, in seconds.
'''
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
'''
Method tha runs forver.
Once a thread object is created, its activity must be started by calling
the thread's start() method. This invokes the run() method in a separate
thread of control.
'''
while True:
# Do something
print 'Doing something imporant in the background'
time.sleep(20)
example = ThreadingExample()
time.sleep(30)
print 'Checkpoint'
time.sleep(30)
print 'Bye' |
hpfem/cython | refs/heads/master | docs/sphinxext/ipython_console_highlighting.py | 13 | from pygments.lexer import Lexer, do_insertions
from pygments.lexers.agile import PythonConsoleLexer, PythonLexer, \
PythonTracebackLexer
from pygments.token import Comment, Generic
from sphinx import highlighting
import re
line_re = re.compile('.*?\n')
class IPythonConsoleLexer(Lexer):
"""
For IPython console output or doctests, such as:
Tracebacks are not currently supported.
.. sourcecode:: ipython
In [1]: a = 'foo'
In [2]: a
Out[2]: 'foo'
In [3]: print a
foo
In [4]: 1 / 0
"""
name = 'IPython console session'
aliases = ['ipython']
mimetypes = ['text/x-ipython-console']
input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)")
output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)")
continue_prompt = re.compile(" \.\.\.+:")
tb_start = re.compile("\-+")
def get_tokens_unprocessed(self, text):
pylexer = PythonLexer(**self.options)
tblexer = PythonTracebackLexer(**self.options)
curcode = ''
insertions = []
for match in line_re.finditer(text):
line = match.group()
input_prompt = self.input_prompt.match(line)
continue_prompt = self.continue_prompt.match(line.rstrip())
output_prompt = self.output_prompt.match(line)
if line.startswith("#"):
insertions.append((len(curcode),
[(0, Comment, line)]))
elif input_prompt is not None:
insertions.append((len(curcode),
[(0, Generic.Prompt, input_prompt.group())]))
curcode += line[input_prompt.end():]
elif continue_prompt is not None:
insertions.append((len(curcode),
[(0, Generic.Prompt, continue_prompt.group())]))
curcode += line[continue_prompt.end():]
elif output_prompt is not None:
insertions.append((len(curcode),
[(0, Generic.Output, output_prompt.group())]))
curcode += line[output_prompt.end():]
else:
if curcode:
for item in do_insertions(insertions,
pylexer.get_tokens_unprocessed(curcode)):
yield item
curcode = ''
insertions = []
yield match.start(), Generic.Output, line
if curcode:
for item in do_insertions(insertions,
pylexer.get_tokens_unprocessed(curcode)):
yield item
highlighting.lexers['ipython'] = IPythonConsoleLexer()
|
manveru0/FeaCore_Phoenix_S3 | refs/heads/master | arch/ia64/scripts/unwcheck.py | 13143 | #!/usr/bin/python
#
# Usage: unwcheck.py FILE
#
# This script checks the unwind info of each function in file FILE
# and verifies that the sum of the region-lengths matches the total
# length of the function.
#
# Based on a shell/awk script originally written by Harish Patil,
# which was converted to Perl by Matthew Chapman, which was converted
# to Python by David Mosberger.
#
import os
import re
import sys
if len(sys.argv) != 2:
print "Usage: %s FILE" % sys.argv[0]
sys.exit(2)
readelf = os.getenv("READELF", "readelf")
start_pattern = re.compile("<([^>]*)>: \[0x([0-9a-f]+)-0x([0-9a-f]+)\]")
rlen_pattern = re.compile(".*rlen=([0-9]+)")
def check_func (func, slots, rlen_sum):
if slots != rlen_sum:
global num_errors
num_errors += 1
if not func: func = "[%#x-%#x]" % (start, end)
print "ERROR: %s: %lu slots, total region length = %lu" % (func, slots, rlen_sum)
return
num_funcs = 0
num_errors = 0
func = False
slots = 0
rlen_sum = 0
for line in os.popen("%s -u %s" % (readelf, sys.argv[1])):
m = start_pattern.match(line)
if m:
check_func(func, slots, rlen_sum)
func = m.group(1)
start = long(m.group(2), 16)
end = long(m.group(3), 16)
slots = 3 * (end - start) / 16
rlen_sum = 0L
num_funcs += 1
else:
m = rlen_pattern.match(line)
if m:
rlen_sum += long(m.group(1))
check_func(func, slots, rlen_sum)
if num_errors == 0:
print "No errors detected in %u functions." % num_funcs
else:
if num_errors > 1:
err="errors"
else:
err="error"
print "%u %s detected in %u functions." % (num_errors, err, num_funcs)
sys.exit(1)
|
jrversteegh/softsailor | refs/heads/master | softsailor/sol/sol_boat.py | 1 | """
Sol boat module
Contains a boat with sol performance
"""
__author__ = "J.R. Versteegh"
__copyright__ = "Copyright 2011, J.R. Versteegh"
__contact__ = "j.r.versteegh@gmail.com"
__version__ = "0.1"
__license__ = "GPLv3, No Warranty. See 'LICENSE'"
from softsailor.boat import SailBoat
from sol_performance import Performance
from sol_settings import *
from sol_functions import get_settings
class Boat(SailBoat):
def __init__(self, *args, **kwargs):
super(Boat, self).__init__(*args, **kwargs)
self.performance = Performance(get_settings().polar_data)
self.efficiency = 1
|
sublime1809/django | refs/heads/master | tests/view_tests/models.py | 160 | """
Regression tests for Django built-in views.
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
def get_absolute_url(self):
return '/authors/%s/' % self.id
@python_2_unicode_compatible
class BaseArticle(models.Model):
"""
An abstract article Model so that we can create article models with and
without a get_absolute_url method (for create_update generic views tests).
"""
title = models.CharField(max_length=100)
slug = models.SlugField()
author = models.ForeignKey(Author)
class Meta:
abstract = True
def __str__(self):
return self.title
class Article(BaseArticle):
date_created = models.DateTimeField()
class UrlArticle(BaseArticle):
"""
An Article class with a get_absolute_url defined.
"""
date_created = models.DateTimeField()
def get_absolute_url(self):
return '/urlarticles/%s/' % self.slug
get_absolute_url.purge = True
class DateArticle(BaseArticle):
"""
An article Model with a DateField instead of DateTimeField,
for testing #7602
"""
date_created = models.DateField()
|
ashutrix03/inteygrate_flaskapp-master | refs/heads/master | build/lib/yowsup/common/__init__.py | 70 | from .constants import YowConstants |
oskar456/youtube-dl | refs/heads/master | youtube_dl/extractor/everyonesmixtape.py | 88 | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
sanitized_Request,
)
class EveryonesMixtapeIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?everyonesmixtape\.com/#/mix/(?P<id>[0-9a-zA-Z]+)(?:/(?P<songnr>[0-9]))?$'
_TESTS = [{
'url': 'http://everyonesmixtape.com/#/mix/m7m0jJAbMQi/5',
'info_dict': {
'id': '5bfseWNmlds',
'ext': 'mp4',
'title': "Passion Pit - \"Sleepyhead\" (Official Music Video)",
'uploader': 'FKR.TV',
'uploader_id': 'frenchkissrecords',
'description': "Music video for \"Sleepyhead\" from Passion Pit's debut EP Chunk Of Change.\nBuy on iTunes: https://itunes.apple.com/us/album/chunk-of-change-ep/id300087641\n\nDirected by The Wilderness.\n\nhttp://www.passionpitmusic.com\nhttp://www.frenchkissrecords.com",
'upload_date': '20081015'
},
'params': {
'skip_download': True, # This is simply YouTube
}
}, {
'url': 'http://everyonesmixtape.com/#/mix/m7m0jJAbMQi',
'info_dict': {
'id': 'm7m0jJAbMQi',
'title': 'Driving',
},
'playlist_count': 24
}]
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
playlist_id = mobj.group('id')
pllist_url = 'http://everyonesmixtape.com/mixtape.php?a=getMixes&u=-1&linked=%s&explore=' % playlist_id
pllist_req = sanitized_Request(pllist_url)
pllist_req.add_header('X-Requested-With', 'XMLHttpRequest')
playlist_list = self._download_json(
pllist_req, playlist_id, note='Downloading playlist metadata')
try:
playlist_no = next(playlist['id']
for playlist in playlist_list
if playlist['code'] == playlist_id)
except StopIteration:
raise ExtractorError('Playlist id not found')
pl_url = 'http://everyonesmixtape.com/mixtape.php?a=getMix&id=%s&userId=null&code=' % playlist_no
pl_req = sanitized_Request(pl_url)
pl_req.add_header('X-Requested-With', 'XMLHttpRequest')
playlist = self._download_json(
pl_req, playlist_id, note='Downloading playlist info')
entries = [{
'_type': 'url',
'url': t['url'],
'title': t['title'],
} for t in playlist['tracks']]
if mobj.group('songnr'):
songnr = int(mobj.group('songnr')) - 1
return entries[songnr]
playlist_title = playlist['mixData']['name']
return {
'_type': 'playlist',
'id': playlist_id,
'title': playlist_title,
'entries': entries,
}
|
trhongbinwang/data_science_journey | refs/heads/master | deep_learning/tensorflow/tutorials/tutorial1/02_logistic_regression.py | 1 | #!/usr/bin/env python
import tensorflow as tf
import numpy as np
import input_data
def init_weights(shape):
return tf.Variable(tf.random_normal(shape, stddev=0.01))
def load_data():
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
trX, trY, teX, teY = mnist.train.images, mnist.train.labels, mnist.test.images, mnist.test.labels
return [trX, trY, teX, teY]
def inputs_placeholder():
X = tf.placeholder("float", [None, 784]) # create symbolic variables
Y = tf.placeholder("float", [None, 10])
return [X, Y]
def model(X, Y):
w = init_weights([784, 10]) # like in linear regression, we need a shared variable weight matrix for logistic regression
py_x = tf.matmul(X, w)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=py_x, labels=Y)) # compute mean cross entropy (softmax is applied internally)
train_op = tf.train.GradientDescentOptimizer(0.05).minimize(cost) # construct optimizer
predict_op = tf.argmax(py_x, 1) # at predict time, evaluate the argmax of the logistic regression
return [train_op, predict_op]
def train(sess, trX, trY, teX, teY, X, Y, train_op, predict_op):
''' train the model '''
for i in range(100):
for start, end in zip(range(0, len(trX), 128), range(128, len(trX)+1, 128)):
sess.run(train_op, feed_dict={X: trX[start:end], Y: trY[start:end]})
print(i, np.mean(np.argmax(teY, axis=1) ==
sess.run(predict_op, feed_dict={X: teX})))
if __name__ == '__main__':
''' '''
# load data
[trX, trY, teX, teY] = load_data()
# define inputs
[X, Y] = inputs_placeholder()
# define model
[train_op, predict_op] = model(X, Y)
# Launch the graph in a session
with tf.Session() as sess:
# you need to initialize all variables
tf.global_variables_initializer().run()
# train
train(sess, trX, trY, teX, teY, X, Y, train_op, predict_op)
|
knewbie/crashshow | refs/heads/master | test.py | 1 | #!/usr/bin/env python
from hashlib import sha1
#from app.data_collect import Extract
from app.models import db_handler
#ext = Extract('2016-01-25', '/Users/kevin/study/python/flask/myproj')
#ext.run_extract()
user_dict = {
'admin':'admin',
'kevin':'kevinlee',
'lwn':'lwn1234',
'ff':'ff1234',
'mxc':'mxc1234'}
for k, v in user_dict.items():
db_handler.save_user(k, sha1(v).hexdigest())
print db_handler.get_user_passwd('admin')
|
arenadata/ambari | refs/heads/branch-adh-1.6 | ambari-server/src/main/resources/stacks/BigInsights/4.0/services/HDFS/package/scripts/hdfs_client.py | 1 | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.
"""
from resource_management import *
from resource_management.libraries.functions import stack_select
from resource_management.libraries.functions.security_commons import build_expectations, \
cached_kinit_executor, get_params_from_filesystem, validate_security_config_properties, \
FILE_TYPE_XML
from hdfs import hdfs
from utils import service
class HdfsClient(Script):
def install(self, env):
import params
self.install_packages(env)
env.set_params(params)
self.config(env)
def pre_upgrade_restart(self, env, upgrade_type=None):
import params
env.set_params(params)
if params.version and compare_versions(format_stack_version(params.version), '4.0.0.0') >= 0:
stack_select.select_packages(params.version)
def start(self, env, upgrade_type=False):
import params
env.set_params(params)
def stop(self, env, upgrade_type=False):
import params
env.set_params(params)
def status(self, env):
raise ClientComponentHasNoStatus()
def config(self, env):
import params
hdfs()
def security_status(self, env):
import status_params
env.set_params(status_params)
props_value_check = {"hadoop.security.authentication": "kerberos",
"hadoop.security.authorization": "true"}
props_empty_check = ["hadoop.security.auth_to_local"]
props_read_check = None
core_site_expectations = build_expectations('core-site', props_value_check, props_empty_check,
props_read_check)
hdfs_expectations ={}
hdfs_expectations.update(core_site_expectations)
security_params = get_params_from_filesystem(status_params.hadoop_conf_dir,
{'core-site.xml': FILE_TYPE_XML})
if 'core-site' in security_params and 'hadoop.security.authentication' in security_params['core-site'] and \
security_params['core-site']['hadoop.security.authentication'].lower() == 'kerberos':
result_issues = validate_security_config_properties(security_params, hdfs_expectations)
if not result_issues: # If all validations passed successfully
if status_params.hdfs_user_principal or status_params.hdfs_user_keytab:
try:
cached_kinit_executor(status_params.kinit_path_local,
status_params.hdfs_user,
status_params.hdfs_user_keytab,
status_params.hdfs_user_principal,
status_params.hostname,
status_params.tmp_dir)
self.put_structured_out({"securityState": "SECURED_KERBEROS"})
except Exception as e:
self.put_structured_out({"securityState": "ERROR"})
self.put_structured_out({"securityStateErrorInfo": str(e)})
else:
self.put_structured_out({"securityIssuesFound": "hdfs principal and/or keytab file is not specified"})
self.put_structured_out({"securityState": "UNSECURED"})
else:
issues = []
for cf in result_issues:
issues.append("Configuration file %s did not pass the validation. Reason: %s" % (cf, result_issues[cf]))
self.put_structured_out({"securityIssuesFound": ". ".join(issues)})
self.put_structured_out({"securityState": "UNSECURED"})
else:
self.put_structured_out({"securityState": "UNSECURED"})
if __name__ == "__main__":
HdfsClient().execute()
|
elba7r/lite-system | refs/heads/master | erpnext/patches/v7_1/update_missing_salary_component_type.py | 35 | from __future__ import unicode_literals
import frappe
from frappe.utils import cstr
'''
Some components do not have type set, try and guess whether they turn up in
earnings or deductions in existing salary slips
'''
def execute():
frappe.reload_doc("accounts", "doctype", "salary_component_account")
for s in frappe.db.sql('''select name, type, salary_component_abbr from `tabSalary Component`
where ifnull(type, "")="" or ifnull(salary_component_abbr, "") = ""''', as_dict=1):
component = frappe.get_doc('Salary Component', s.name)
# guess
if not s.type:
guess = frappe.db.sql('''select
parentfield from `tabSalary Detail`
where salary_component=%s limit 1''', s.name)
if guess:
component.type = 'Earning' if guess[0][0]=='earnings' else 'Deduction'
else:
component.type = 'Deduction'
if not s.salary_component_abbr:
abbr = ''.join([c[0] for c in component.salary_component.split()]).upper()
abbr_count = frappe.db.sql("""
select
count(name)
from
`tabSalary Component`
where
salary_component_abbr = %s or salary_component_abbr like %s
""", (abbr, abbr + "-%%"))
if abbr_count and abbr_count[0][0] > 0:
abbr = abbr + "-" + cstr(abbr_count[0][0])
component.salary_component_abbr = abbr
component.save()
|
KohlsTechnology/ansible | refs/heads/devel | lib/ansible/modules/network/dellos10/dellos10_command.py | 45 | #!/usr/bin/python
#
# (c) 2015 Peter Sprygada, <psprygada@ansible.com>
# Copyright (c) 2017 Dell Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: dellos10_command
version_added: "2.2"
author: "Senthil Kumar Ganesan (@skg-net)"
short_description: Run commands on remote devices running Dell OS10
description:
- Sends arbitrary commands to a Dell OS10 node and returns the results
read from the device. This module includes an
argument that will cause the module to wait for a specific condition
before returning or timing out if the condition is not met.
- This module does not support running commands in configuration mode.
Please use M(dellos10_config) to configure Dell OS10 devices.
extends_documentation_fragment: dellos10
options:
commands:
description:
- List of commands to send to the remote dellos10 device over the
configured provider. The resulting output from the command
is returned. If the I(wait_for) argument is provided, the
module is not returned until the condition is satisfied or
the number of retries has expired.
required: true
wait_for:
description:
- List of conditions to evaluate against the output of the
command. The task will wait for each condition to be true
before moving forward. If the conditional is not true
within the configured number of I(retries), the task fails.
See examples.
version_added: "2.2"
match:
description:
- The I(match) argument is used in conjunction with the
I(wait_for) argument to specify the match policy. Valid
values are C(all) or C(any). If the value is set to C(all)
then all conditionals in the wait_for must be satisfied. If
the value is set to C(any) then only one of the values must be
satisfied.
default: all
choices: ['any', 'all']
version_added: "2.5"
retries:
description:
- Specifies the number of retries a command should be tried
before it is considered failed. The command is run on the
target device every retry and evaluated against the
I(wait_for) conditions.
default: 10
interval:
description:
- Configures the interval in seconds to wait between retries
of the command. If the command does not pass the specified
conditions, the interval indicates how long to wait before
trying the command again.
default: 1
"""
EXAMPLES = """
tasks:
- name: run show version on remote devices
dellos10_command:
commands: show version
- name: run show version and check to see if output contains OS10
dellos10_command:
commands: show version
wait_for: result[0] contains OS10
- name: run multiple commands on remote nodes
dellos10_command:
commands:
- show version
- show interface
- name: run multiple commands and evaluate the output
dellos10_command:
commands:
- show version
- show interface
wait_for:
- result[0] contains OS10
- result[1] contains Ethernet
"""
RETURN = """
stdout:
description: The set of responses from the commands
returned: always apart from low level errors (such as action plugin)
type: list
sample: ['...', '...']
stdout_lines:
description: The value of stdout split into a list
returned: always apart from low level errors (such as action plugin)
type: list
sample: [['...', '...'], ['...'], ['...']]
failed_conditions:
description: The list of conditionals that have failed
returned: failed
type: list
sample: ['...', '...']
warnings:
description: The list of warnings (if any) generated by module based on arguments
returned: always
type: list
sample: ['...', '...']
"""
import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.dellos10.dellos10 import run_commands
from ansible.module_utils.network.dellos10.dellos10 import dellos10_argument_spec, check_args
from ansible.module_utils.network.common.utils import ComplexList
from ansible.module_utils.network.common.parsing import Conditional
from ansible.module_utils.six import string_types
def to_lines(stdout):
for item in stdout:
if isinstance(item, string_types):
item = str(item).split('\n')
yield item
def parse_commands(module, warnings):
command = ComplexList(dict(
command=dict(key=True),
prompt=dict(),
answer=dict()
), module)
commands = command(module.params['commands'])
for index, item in enumerate(commands):
if module.check_mode and not item['command'].startswith('show'):
warnings.append(
'only show commands are supported when using check mode, not '
'executing `%s`' % item['command']
)
elif item['command'].startswith('conf'):
module.fail_json(
msg='dellos10_command does not support running config mode '
'commands. Please use dellos10_config instead'
)
return commands
def main():
"""main entry point for module execution
"""
argument_spec = dict(
# { command: <str>, prompt: <str>, response: <str> }
commands=dict(type='list', required=True),
wait_for=dict(type='list'),
match=dict(default='all', choices=['all', 'any']),
retries=dict(default=10, type='int'),
interval=dict(default=1, type='int')
)
argument_spec.update(dellos10_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
result = {'changed': False}
warnings = list()
check_args(module, warnings)
commands = parse_commands(module, warnings)
result['warnings'] = warnings
wait_for = module.params['wait_for'] or list()
conditionals = [Conditional(c) for c in wait_for]
retries = module.params['retries']
interval = module.params['interval']
match = module.params['match']
while retries > 0:
responses = run_commands(module, commands)
for item in list(conditionals):
if item(responses):
if match == 'any':
conditionals = list()
break
conditionals.remove(item)
if not conditionals:
break
time.sleep(interval)
retries -= 1
if conditionals:
failed_conditions = [item.raw for item in conditionals]
msg = 'One or more conditional statements have not been satisfied'
module.fail_json(msg=msg, failed_conditions=failed_conditions)
result.update({
'changed': False,
'stdout': responses,
'stdout_lines': list(to_lines(responses))
})
module.exit_json(**result)
if __name__ == '__main__':
main()
|
havard024/prego | refs/heads/master | venv/lib/python2.7/site-packages/django/core/mail/backends/dummy.py | 634 | """
Dummy email backend that does nothing.
"""
from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
return len(email_messages)
|
kaedroho/django | refs/heads/master | tests/foreign_object/models/person.py | 79 | import datetime
from django.db import models
class Country(models.Model):
# Table Column Fields
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Person(models.Model):
# Table Column Fields
name = models.CharField(max_length=128)
person_country_id = models.IntegerField()
# Relation Fields
person_country = models.ForeignObject(
Country,
from_fields=['person_country_id'],
to_fields=['id'],
on_delete=models.CASCADE,
)
friends = models.ManyToManyField('self', through='Friendship', symmetrical=False)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class Group(models.Model):
# Table Column Fields
name = models.CharField(max_length=128)
group_country = models.ForeignKey(Country, models.CASCADE)
members = models.ManyToManyField(Person, related_name='groups', through='Membership')
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class Membership(models.Model):
# Table Column Fields
membership_country = models.ForeignKey(Country, models.CASCADE)
date_joined = models.DateTimeField(default=datetime.datetime.now)
invite_reason = models.CharField(max_length=64, null=True)
person_id = models.IntegerField()
group_id = models.IntegerField(blank=True, null=True)
# Relation Fields
person = models.ForeignObject(
Person,
from_fields=['person_id', 'membership_country'],
to_fields=['id', 'person_country_id'],
on_delete=models.CASCADE,
)
group = models.ForeignObject(
Group,
from_fields=['group_id', 'membership_country'],
to_fields=['id', 'group_country'],
on_delete=models.CASCADE,
)
class Meta:
ordering = ('date_joined', 'invite_reason')
def __str__(self):
group_name = self.group.name if self.group_id else 'NULL'
return "%s is a member of %s" % (self.person.name, group_name)
class Friendship(models.Model):
# Table Column Fields
from_friend_country = models.ForeignKey(Country, models.CASCADE, related_name="from_friend_country")
from_friend_id = models.IntegerField()
to_friend_country_id = models.IntegerField()
to_friend_id = models.IntegerField()
# Relation Fields
from_friend = models.ForeignObject(
Person,
on_delete=models.CASCADE,
from_fields=['from_friend_country', 'from_friend_id'],
to_fields=['person_country_id', 'id'],
related_name='from_friend',
)
to_friend_country = models.ForeignObject(
Country,
from_fields=['to_friend_country_id'],
to_fields=['id'],
related_name='to_friend_country',
on_delete=models.CASCADE,
)
to_friend = models.ForeignObject(
Person,
from_fields=['to_friend_country_id', 'to_friend_id'],
to_fields=['person_country_id', 'id'],
related_name='to_friend',
on_delete=models.CASCADE,
)
|
mcanthony/cython | refs/heads/master | Cython/Debugger/DebugWriter.py | 13 | from __future__ import with_statement
import os
import sys
import errno
try:
from lxml import etree
have_lxml = True
except ImportError:
have_lxml = False
try:
# Python 2.5
from xml.etree import cElementTree as etree
except ImportError:
try:
# Python 2.5
from xml.etree import ElementTree as etree
except ImportError:
try:
# normal cElementTree install
import cElementTree as etree
except ImportError:
try:
# normal ElementTree install
import elementtree.ElementTree as etree
except ImportError:
etree = None
from Cython.Compiler import Errors
class CythonDebugWriter(object):
"""
Class to output debugging information for cygdb
It writes debug information to cython_debug/cython_debug_info_<modulename>
in the build directory.
"""
def __init__(self, output_dir):
if etree is None:
raise Errors.NoElementTreeInstalledException()
self.output_dir = os.path.join(output_dir or os.curdir, 'cython_debug')
self.tb = etree.TreeBuilder()
# set by Cython.Compiler.ParseTreeTransforms.DebugTransform
self.module_name = None
self.start('cython_debug', attrs=dict(version='1.0'))
def start(self, name, attrs=None):
self.tb.start(name, attrs or {})
def end(self, name):
self.tb.end(name)
def serialize(self):
self.tb.end('Module')
self.tb.end('cython_debug')
xml_root_element = self.tb.close()
try:
os.makedirs(self.output_dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise
et = etree.ElementTree(xml_root_element)
kw = {}
if have_lxml:
kw['pretty_print'] = True
fn = "cython_debug_info_" + self.module_name
et.write(os.path.join(self.output_dir, fn), encoding="UTF-8", **kw)
interpreter_path = os.path.join(self.output_dir, 'interpreter')
with open(interpreter_path, 'w') as f:
f.write(sys.executable)
|
jamesblunt/sympy | refs/heads/master | sympy/physics/optics/waves.py | 14 | """
This module has all the classes and functions related to waves in optics.
**Contains**
* TWave
"""
from __future__ import print_function, division
__all__ = ['TWave']
from sympy import (sympify, pi, sin, cos, sqrt, simplify, Symbol, S, C, I,
symbols, Derivative, atan2)
from sympy.core.expr import Expr
from sympy.physics.units import c
class TWave(Expr):
r"""
This is a simple transverse sine wave travelling in a one dimensional space.
Basic properties are required at the time of creation of the object but
they can be changed later with respective methods provided.
It has been represented as :math:`A \times cos(k*x - \omega \times t + \phi )`
where :math:`A` is amplitude, :math:`\omega` is angular velocity, :math:`k`is
wavenumber, :math:`x` is a spatial variable to represent the position on the
dimension on which the wave propagates and :math:`\phi` is phase angle of the wave.
Arguments
=========
amplitude : Sympifyable
Amplitude of the wave.
frequency : Sympifyable
Frequency of the wave.
phase : Sympifyable
Phase angle of the wave.
time_period : Sympifyable
Time period of the wave.
n : Sympifyable
Refractive index of the medium.
Raises
=======
ValueError : When neither frequency nor time period is provided
or they are not consistent.
TypeError : When anyting other than TWave objects is added.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
>>> w1 = TWave(A1, f, phi1)
>>> w2 = TWave(A2, f, phi2)
>>> w3 = w1 + w2 # Superposition of two waves
>>> w3
TWave(sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2), f,
atan2(A1*cos(phi1) + A2*cos(phi2), A1*sin(phi1) + A2*sin(phi2)))
>>> w3.amplitude
sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
>>> w3.phase
atan2(A1*cos(phi1) + A2*cos(phi2), A1*sin(phi1) + A2*sin(phi2))
>>> w3.speed
299792458*m/(n*s)
>>> w3.angular_velocity
2*pi*f
"""
def __init__(
self,
amplitude,
frequency=None,
phase=S.Zero,
time_period=None,
n=Symbol('n')):
frequency = sympify(frequency)
amplitude = sympify(amplitude)
phase = sympify(phase)
time_period = sympify(time_period)
n = sympify(n)
self._frequency = frequency
self._amplitude = amplitude
self._phase = phase
self._time_period = time_period
self._n = n
if time_period is not None:
self._frequency = 1/self._time_period
if frequency is not None:
self._time_period = 1/self._frequency
if time_period is not None:
if frequency != 1/time_period:
raise ValueError("frequency and time_period should be consistent.")
if frequency is None and time_period is None:
raise ValueError("Either frequency or time period is needed.")
@property
def frequency(self):
"""
Returns the frequency of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.frequency
f
"""
return self._frequency
@property
def time_period(self):
"""
Returns the time period of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.time_period
1/f
"""
return self._time_period
@property
def wavelength(self):
"""
Returns wavelength of the wave.
It depends on the medium of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavelength
299792458*m/(f*n*s)
"""
return c/(self._frequency*self._n)
@property
def amplitude(self):
"""
Returns the amplitude of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.amplitude
A
"""
return self._amplitude
@property
def phase(self):
"""
Returns the phase angle of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.phase
phi
"""
return self._phase
@property
def speed(self):
"""
Returns the speed of travelling wave.
It is medium dependent.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.speed
299792458*m/(n*s)
"""
return self.wavelength*self._frequency
@property
def angular_velocity(self):
"""
Returns angular velocity of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.angular_velocity
2*pi*f
"""
return 2*pi*self._frequency
@property
def wavenumber(self):
"""
Returns wavenumber of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavenumber
pi*f*n*s/(149896229*m)
"""
return 2*pi/self.wavelength
def __str__(self):
"""String representation of a TWave."""
from sympy.printing import sstr
return type(self).__name__ + sstr(self.args)
__repr__ = __str__
def __add__(self, other):
"""
Addition of two waves will result in their superposition.
The type of interference will depend on their phase angles.
"""
if isinstance(other, TWave):
if self._frequency == other._frequency and self.wavelength == other.wavelength:
return TWave(sqrt(self._amplitude**2 + other._amplitude**2 + 2 *
self.amplitude*other.amplitude*cos(
self._phase - other.phase)),
self.frequency,
atan2(self._amplitude*cos(self._phase)
+other._amplitude*cos(other._phase),
self._amplitude*sin(self._phase)
+other._amplitude*sin(other._phase))
)
else:
raise NotImplementedError("Interference of waves with different frequencies"
" has not been implemented.")
else:
raise TypeError(type(other).__name__ + " and TWave objects can't be added.")
def _eval_rewrite_as_sin(self, *args):
return self._amplitude*sin(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self._phase + pi/2, evaluate=False)
def _eval_rewrite_as_cos(self, *args):
return self._amplitude*cos(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self._phase)
def _eval_rewrite_as_pde(self, *args):
from sympy import Function
mu, epsilon, x, t = symbols('mu, epsilon, x, t')
E = Function('E')
return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2)
def _eval_rewrite_as_exp(self, *args):
from sympy import C, I
exp = C.exp
return self._amplitude*exp(I*(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self._phase))
|
taaviteska/django | refs/heads/master | django/db/migrations/__init__.py | 826 | from .migration import Migration, swappable_dependency # NOQA
from .operations import * # NOQA
|
sandymanu/manufooty_yu_lp | refs/heads/master | tools/perf/scripts/python/netdev-times.py | 11271 | # Display a process of packets and processed time.
# It helps us to investigate networking or network device.
#
# options
# tx: show only tx chart
# rx: show only rx chart
# dev=: show only thing related to specified device
# debug: work with debug mode. It shows buffer status.
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
all_event_list = []; # insert all tracepoint event related with this script
irq_dic = {}; # key is cpu and value is a list which stacks irqs
# which raise NET_RX softirq
net_rx_dic = {}; # key is cpu and value include time of NET_RX softirq-entry
# and a list which stacks receive
receive_hunk_list = []; # a list which include a sequence of receive events
rx_skb_list = []; # received packet list for matching
# skb_copy_datagram_iovec
buffer_budget = 65536; # the budget of rx_skb_list, tx_queue_list and
# tx_xmit_list
of_count_rx_skb_list = 0; # overflow count
tx_queue_list = []; # list of packets which pass through dev_queue_xmit
of_count_tx_queue_list = 0; # overflow count
tx_xmit_list = []; # list of packets which pass through dev_hard_start_xmit
of_count_tx_xmit_list = 0; # overflow count
tx_free_list = []; # list of packets which is freed
# options
show_tx = 0;
show_rx = 0;
dev = 0; # store a name of device specified by option "dev="
debug = 0;
# indices of event_info tuple
EINFO_IDX_NAME= 0
EINFO_IDX_CONTEXT=1
EINFO_IDX_CPU= 2
EINFO_IDX_TIME= 3
EINFO_IDX_PID= 4
EINFO_IDX_COMM= 5
# Calculate a time interval(msec) from src(nsec) to dst(nsec)
def diff_msec(src, dst):
return (dst - src) / 1000000.0
# Display a process of transmitting a packet
def print_transmit(hunk):
if dev != 0 and hunk['dev'].find(dev) < 0:
return
print "%7s %5d %6d.%06dsec %12.3fmsec %12.3fmsec" % \
(hunk['dev'], hunk['len'],
nsecs_secs(hunk['queue_t']),
nsecs_nsecs(hunk['queue_t'])/1000,
diff_msec(hunk['queue_t'], hunk['xmit_t']),
diff_msec(hunk['xmit_t'], hunk['free_t']))
# Format for displaying rx packet processing
PF_IRQ_ENTRY= " irq_entry(+%.3fmsec irq=%d:%s)"
PF_SOFT_ENTRY=" softirq_entry(+%.3fmsec)"
PF_NAPI_POLL= " napi_poll_exit(+%.3fmsec %s)"
PF_JOINT= " |"
PF_WJOINT= " | |"
PF_NET_RECV= " |---netif_receive_skb(+%.3fmsec skb=%x len=%d)"
PF_NET_RX= " |---netif_rx(+%.3fmsec skb=%x)"
PF_CPY_DGRAM= " | skb_copy_datagram_iovec(+%.3fmsec %d:%s)"
PF_KFREE_SKB= " | kfree_skb(+%.3fmsec location=%x)"
PF_CONS_SKB= " | consume_skb(+%.3fmsec)"
# Display a process of received packets and interrputs associated with
# a NET_RX softirq
def print_receive(hunk):
show_hunk = 0
irq_list = hunk['irq_list']
cpu = irq_list[0]['cpu']
base_t = irq_list[0]['irq_ent_t']
# check if this hunk should be showed
if dev != 0:
for i in range(len(irq_list)):
if irq_list[i]['name'].find(dev) >= 0:
show_hunk = 1
break
else:
show_hunk = 1
if show_hunk == 0:
return
print "%d.%06dsec cpu=%d" % \
(nsecs_secs(base_t), nsecs_nsecs(base_t)/1000, cpu)
for i in range(len(irq_list)):
print PF_IRQ_ENTRY % \
(diff_msec(base_t, irq_list[i]['irq_ent_t']),
irq_list[i]['irq'], irq_list[i]['name'])
print PF_JOINT
irq_event_list = irq_list[i]['event_list']
for j in range(len(irq_event_list)):
irq_event = irq_event_list[j]
if irq_event['event'] == 'netif_rx':
print PF_NET_RX % \
(diff_msec(base_t, irq_event['time']),
irq_event['skbaddr'])
print PF_JOINT
print PF_SOFT_ENTRY % \
diff_msec(base_t, hunk['sirq_ent_t'])
print PF_JOINT
event_list = hunk['event_list']
for i in range(len(event_list)):
event = event_list[i]
if event['event_name'] == 'napi_poll':
print PF_NAPI_POLL % \
(diff_msec(base_t, event['event_t']), event['dev'])
if i == len(event_list) - 1:
print ""
else:
print PF_JOINT
else:
print PF_NET_RECV % \
(diff_msec(base_t, event['event_t']), event['skbaddr'],
event['len'])
if 'comm' in event.keys():
print PF_WJOINT
print PF_CPY_DGRAM % \
(diff_msec(base_t, event['comm_t']),
event['pid'], event['comm'])
elif 'handle' in event.keys():
print PF_WJOINT
if event['handle'] == "kfree_skb":
print PF_KFREE_SKB % \
(diff_msec(base_t,
event['comm_t']),
event['location'])
elif event['handle'] == "consume_skb":
print PF_CONS_SKB % \
diff_msec(base_t,
event['comm_t'])
print PF_JOINT
def trace_begin():
global show_tx
global show_rx
global dev
global debug
for i in range(len(sys.argv)):
if i == 0:
continue
arg = sys.argv[i]
if arg == 'tx':
show_tx = 1
elif arg =='rx':
show_rx = 1
elif arg.find('dev=',0, 4) >= 0:
dev = arg[4:]
elif arg == 'debug':
debug = 1
if show_tx == 0 and show_rx == 0:
show_tx = 1
show_rx = 1
def trace_end():
# order all events in time
all_event_list.sort(lambda a,b :cmp(a[EINFO_IDX_TIME],
b[EINFO_IDX_TIME]))
# process all events
for i in range(len(all_event_list)):
event_info = all_event_list[i]
name = event_info[EINFO_IDX_NAME]
if name == 'irq__softirq_exit':
handle_irq_softirq_exit(event_info)
elif name == 'irq__softirq_entry':
handle_irq_softirq_entry(event_info)
elif name == 'irq__softirq_raise':
handle_irq_softirq_raise(event_info)
elif name == 'irq__irq_handler_entry':
handle_irq_handler_entry(event_info)
elif name == 'irq__irq_handler_exit':
handle_irq_handler_exit(event_info)
elif name == 'napi__napi_poll':
handle_napi_poll(event_info)
elif name == 'net__netif_receive_skb':
handle_netif_receive_skb(event_info)
elif name == 'net__netif_rx':
handle_netif_rx(event_info)
elif name == 'skb__skb_copy_datagram_iovec':
handle_skb_copy_datagram_iovec(event_info)
elif name == 'net__net_dev_queue':
handle_net_dev_queue(event_info)
elif name == 'net__net_dev_xmit':
handle_net_dev_xmit(event_info)
elif name == 'skb__kfree_skb':
handle_kfree_skb(event_info)
elif name == 'skb__consume_skb':
handle_consume_skb(event_info)
# display receive hunks
if show_rx:
for i in range(len(receive_hunk_list)):
print_receive(receive_hunk_list[i])
# display transmit hunks
if show_tx:
print " dev len Qdisc " \
" netdevice free"
for i in range(len(tx_free_list)):
print_transmit(tx_free_list[i])
if debug:
print "debug buffer status"
print "----------------------------"
print "xmit Qdisc:remain:%d overflow:%d" % \
(len(tx_queue_list), of_count_tx_queue_list)
print "xmit netdevice:remain:%d overflow:%d" % \
(len(tx_xmit_list), of_count_tx_xmit_list)
print "receive:remain:%d overflow:%d" % \
(len(rx_skb_list), of_count_rx_skb_list)
# called from perf, when it finds a correspoinding event
def irq__softirq_entry(name, context, cpu, sec, nsec, pid, comm, vec):
if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX":
return
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec)
all_event_list.append(event_info)
def irq__softirq_exit(name, context, cpu, sec, nsec, pid, comm, vec):
if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX":
return
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec)
all_event_list.append(event_info)
def irq__softirq_raise(name, context, cpu, sec, nsec, pid, comm, vec):
if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX":
return
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec)
all_event_list.append(event_info)
def irq__irq_handler_entry(name, context, cpu, sec, nsec, pid, comm,
irq, irq_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
irq, irq_name)
all_event_list.append(event_info)
def irq__irq_handler_exit(name, context, cpu, sec, nsec, pid, comm, irq, ret):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, ret)
all_event_list.append(event_info)
def napi__napi_poll(name, context, cpu, sec, nsec, pid, comm, napi, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
napi, dev_name)
all_event_list.append(event_info)
def net__netif_receive_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr,
skblen, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, dev_name)
all_event_list.append(event_info)
def net__netif_rx(name, context, cpu, sec, nsec, pid, comm, skbaddr,
skblen, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, dev_name)
all_event_list.append(event_info)
def net__net_dev_queue(name, context, cpu, sec, nsec, pid, comm,
skbaddr, skblen, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, dev_name)
all_event_list.append(event_info)
def net__net_dev_xmit(name, context, cpu, sec, nsec, pid, comm,
skbaddr, skblen, rc, dev_name):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen, rc ,dev_name)
all_event_list.append(event_info)
def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm,
skbaddr, protocol, location):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, protocol, location)
all_event_list.append(event_info)
def skb__consume_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr)
all_event_list.append(event_info)
def skb__skb_copy_datagram_iovec(name, context, cpu, sec, nsec, pid, comm,
skbaddr, skblen):
event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm,
skbaddr, skblen)
all_event_list.append(event_info)
def handle_irq_handler_entry(event_info):
(name, context, cpu, time, pid, comm, irq, irq_name) = event_info
if cpu not in irq_dic.keys():
irq_dic[cpu] = []
irq_record = {'irq':irq, 'name':irq_name, 'cpu':cpu, 'irq_ent_t':time}
irq_dic[cpu].append(irq_record)
def handle_irq_handler_exit(event_info):
(name, context, cpu, time, pid, comm, irq, ret) = event_info
if cpu not in irq_dic.keys():
return
irq_record = irq_dic[cpu].pop()
if irq != irq_record['irq']:
return
irq_record.update({'irq_ext_t':time})
# if an irq doesn't include NET_RX softirq, drop.
if 'event_list' in irq_record.keys():
irq_dic[cpu].append(irq_record)
def handle_irq_softirq_raise(event_info):
(name, context, cpu, time, pid, comm, vec) = event_info
if cpu not in irq_dic.keys() \
or len(irq_dic[cpu]) == 0:
return
irq_record = irq_dic[cpu].pop()
if 'event_list' in irq_record.keys():
irq_event_list = irq_record['event_list']
else:
irq_event_list = []
irq_event_list.append({'time':time, 'event':'sirq_raise'})
irq_record.update({'event_list':irq_event_list})
irq_dic[cpu].append(irq_record)
def handle_irq_softirq_entry(event_info):
(name, context, cpu, time, pid, comm, vec) = event_info
net_rx_dic[cpu] = {'sirq_ent_t':time, 'event_list':[]}
def handle_irq_softirq_exit(event_info):
(name, context, cpu, time, pid, comm, vec) = event_info
irq_list = []
event_list = 0
if cpu in irq_dic.keys():
irq_list = irq_dic[cpu]
del irq_dic[cpu]
if cpu in net_rx_dic.keys():
sirq_ent_t = net_rx_dic[cpu]['sirq_ent_t']
event_list = net_rx_dic[cpu]['event_list']
del net_rx_dic[cpu]
if irq_list == [] or event_list == 0:
return
rec_data = {'sirq_ent_t':sirq_ent_t, 'sirq_ext_t':time,
'irq_list':irq_list, 'event_list':event_list}
# merge information realted to a NET_RX softirq
receive_hunk_list.append(rec_data)
def handle_napi_poll(event_info):
(name, context, cpu, time, pid, comm, napi, dev_name) = event_info
if cpu in net_rx_dic.keys():
event_list = net_rx_dic[cpu]['event_list']
rec_data = {'event_name':'napi_poll',
'dev':dev_name, 'event_t':time}
event_list.append(rec_data)
def handle_netif_rx(event_info):
(name, context, cpu, time, pid, comm,
skbaddr, skblen, dev_name) = event_info
if cpu not in irq_dic.keys() \
or len(irq_dic[cpu]) == 0:
return
irq_record = irq_dic[cpu].pop()
if 'event_list' in irq_record.keys():
irq_event_list = irq_record['event_list']
else:
irq_event_list = []
irq_event_list.append({'time':time, 'event':'netif_rx',
'skbaddr':skbaddr, 'skblen':skblen, 'dev_name':dev_name})
irq_record.update({'event_list':irq_event_list})
irq_dic[cpu].append(irq_record)
def handle_netif_receive_skb(event_info):
global of_count_rx_skb_list
(name, context, cpu, time, pid, comm,
skbaddr, skblen, dev_name) = event_info
if cpu in net_rx_dic.keys():
rec_data = {'event_name':'netif_receive_skb',
'event_t':time, 'skbaddr':skbaddr, 'len':skblen}
event_list = net_rx_dic[cpu]['event_list']
event_list.append(rec_data)
rx_skb_list.insert(0, rec_data)
if len(rx_skb_list) > buffer_budget:
rx_skb_list.pop()
of_count_rx_skb_list += 1
def handle_net_dev_queue(event_info):
global of_count_tx_queue_list
(name, context, cpu, time, pid, comm,
skbaddr, skblen, dev_name) = event_info
skb = {'dev':dev_name, 'skbaddr':skbaddr, 'len':skblen, 'queue_t':time}
tx_queue_list.insert(0, skb)
if len(tx_queue_list) > buffer_budget:
tx_queue_list.pop()
of_count_tx_queue_list += 1
def handle_net_dev_xmit(event_info):
global of_count_tx_xmit_list
(name, context, cpu, time, pid, comm,
skbaddr, skblen, rc, dev_name) = event_info
if rc == 0: # NETDEV_TX_OK
for i in range(len(tx_queue_list)):
skb = tx_queue_list[i]
if skb['skbaddr'] == skbaddr:
skb['xmit_t'] = time
tx_xmit_list.insert(0, skb)
del tx_queue_list[i]
if len(tx_xmit_list) > buffer_budget:
tx_xmit_list.pop()
of_count_tx_xmit_list += 1
return
def handle_kfree_skb(event_info):
(name, context, cpu, time, pid, comm,
skbaddr, protocol, location) = event_info
for i in range(len(tx_queue_list)):
skb = tx_queue_list[i]
if skb['skbaddr'] == skbaddr:
del tx_queue_list[i]
return
for i in range(len(tx_xmit_list)):
skb = tx_xmit_list[i]
if skb['skbaddr'] == skbaddr:
skb['free_t'] = time
tx_free_list.append(skb)
del tx_xmit_list[i]
return
for i in range(len(rx_skb_list)):
rec_data = rx_skb_list[i]
if rec_data['skbaddr'] == skbaddr:
rec_data.update({'handle':"kfree_skb",
'comm':comm, 'pid':pid, 'comm_t':time})
del rx_skb_list[i]
return
def handle_consume_skb(event_info):
(name, context, cpu, time, pid, comm, skbaddr) = event_info
for i in range(len(tx_xmit_list)):
skb = tx_xmit_list[i]
if skb['skbaddr'] == skbaddr:
skb['free_t'] = time
tx_free_list.append(skb)
del tx_xmit_list[i]
return
def handle_skb_copy_datagram_iovec(event_info):
(name, context, cpu, time, pid, comm, skbaddr, skblen) = event_info
for i in range(len(rx_skb_list)):
rec_data = rx_skb_list[i]
if skbaddr == rec_data['skbaddr']:
rec_data.update({'handle':"skb_copy_datagram_iovec",
'comm':comm, 'pid':pid, 'comm_t':time})
del rx_skb_list[i]
return
|
zangree/ryu | refs/heads/master | ryu/tests/integrated/test_vrrp_multi.py | 49 | # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013 Isaku Yamahata <yamahata at valinux co jp>
#
# 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.
"""
Usage:
PYTHONPATH=. ./bin/ryu-manager --verbose \
ryu.topology.switches \
ryu.tests.integrated.test_vrrp_multi \
ryu.services.protocols.vrrp.dumper
ryu.services.protocols.vrrp.dumper is optional.
+---+ ----------------
/--|OVS|<--veth-->| |
Ryu +---+ | linux bridge |<--veth--> command to generate packets
\--|OVS|<--veth-->| |
+---+ ----------------
configure OVSs to connect ryu
example
# brctl addbr b0
# ip link add veth0-ovs type veth peer name veth0-br
# ip link add veth1-ovs type veth peer name veth1-br
# brctl addif b0 veth0-br
# brctl addif b0 veth1-br
# brctl show
bridge name bridge id STP enabled interfaces
b0 8000.6642e5822497 no veth0-br
veth1-br
ovs-system 0000.122038293b55 no
# ovs-vsctl add-br s0
# ovs-vsctl add-port s0 veth0-ovs
# ovs-vsctl add-br s1
# ovs-vsctl add-port s1 veth1-ovs
# ovs-vsctl set-controller s0 tcp:127.0.0.1:6633
# ovs-vsctl set bridge s0 protocols='[OpenFlow12]'
# ovs-vsctl set-controller s1 tcp:127.0.0.1:6633
# ovs-vsctl set bridge s1 protocols='[OpenFlow12]'
# ovs-vsctl show
20c2a046-ae7e-4453-a576-11034db24985
Manager "ptcp:6634"
Bridge "s0"
Controller "tcp:127.0.0.1:6633"
is_connected: true
Port "veth0-ovs"
Interface "veth0-ovs"
Port "s0"
Interface "s0"
type: internal
Bridge "s1"
Controller "tcp:127.0.0.1:6633"
is_connected: true
Port "veth1-ovs"
Interface "veth1-ovs"
Port "s1"
Interface "s1"
type: internal
ovs_version: "1.9.90"
# ip link veth0-br set up
# ip link veth0-ovs set up
# ip link veth1-br set up
# ip link veth1-ovs set up
# ip link b0 set up
"""
from ryu.base import app_manager
from ryu.controller import handler
from ryu.lib import dpid as lib_dpid
from ryu.lib import hub
from ryu.lib.packet import vrrp
from ryu.services.protocols.vrrp import api as vrrp_api
from ryu.services.protocols.vrrp import event as vrrp_event
from ryu.services.protocols.vrrp import monitor_openflow
from ryu.topology import event as topo_event
from ryu.topology import api as topo_api
from . import vrrp_common
class VRRPConfigApp(vrrp_common.VRRPCommon):
_IFNAME0 = 0
_IFNAME1 = 1
def __init__(self, *args, **kwargs):
super(VRRPConfigApp, self).__init__(*args, **kwargs)
self.start_main = False
@handler.set_ev_cls(topo_event.EventSwitchEnter)
def _switch_enter_handler(self, ev):
if self.start_main:
return
switches = topo_api.get_switch(self)
if len(switches) < 2:
return
self.start_main = True
app_mgr = app_manager.AppManager.get_instance()
self.logger.debug('%s', app_mgr.applications)
self.switches = app_mgr.applications['switches']
hub.spawn(self._main)
def _configure_vrrp_router(self, vrrp_version, priority,
ip_addr, switch_index, vrid):
switches = self.switches
self.logger.debug('%s', switches.dps)
dpid = sorted(switches.dps.keys())[switch_index]
self.logger.debug('%s', lib_dpid.dpid_to_str(dpid))
self.logger.debug('%s', switches.port_state)
# hack: use the smallest port no to avoid picking OVS local port
port_no = sorted(switches.port_state[dpid].keys())[0]
self.logger.debug('%d', port_no)
port = switches.port_state[dpid][port_no]
self.logger.debug('%s', port)
mac = port.hw_addr
self.logger.debug('%s', mac)
interface = vrrp_event.VRRPInterfaceOpenFlow(
mac, ip_addr, None, dpid, port_no)
self.logger.debug('%s', interface)
config = vrrp_event.VRRPConfig(
version=vrrp_version, vrid=vrid, priority=priority,
ip_addresses=[ip_addr])
self.logger.debug('%s', config)
rep = vrrp_api.vrrp_config(self, interface, config)
self.logger.debug('%s', rep)
return rep
|
Slezhuk/ansible | refs/heads/devel | lib/ansible/modules/network/panos/panos_security_policy.py | 32 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Ansible module to manage PaloAltoNetworks Firewall
# (c) 2016, techbizdev <techbizdev@paloaltonetworks.com>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: panos_security_policy
short_description: Create security rule policy on PanOS devices.
description: >
Security policies allow you to enforce rules and take action, and can be as general or specific as needed.
The policy rules are compared against the incoming traffic in sequence, and because the first rule that matches
the traffic is applied, the more specific rules must precede the more general ones.
author: "Ivan Bojer (@ivanbojer)"
version_added: "2.3"
requirements:
- pan-python can be obtained from PyPi U(https://pypi.python.org/pypi/pan-python)
- pandevice can be obtained from PyPi U(https://pypi.python.org/pypi/pandevice)
notes:
- Checkmode is not supported.
- Panorama is supported
options:
ip_address:
description:
- IP address (or hostname) of PAN-OS device being configured.
required: true
username:
description:
- Username credentials to use for auth unless I(api_key) is set.
default: "admin"
password:
description:
- Password credentials to use for auth unless I(api_key) is set.
required: true
api_key:
description:
- API key that can be used instead of I(username)/I(password) credentials.
rule_name:
description:
- Name of the security rule.
required: true
rule_type:
description:
- Type of security rule (version 6.1 of PanOS and above).
default: "universal"
description:
description:
- Description for the security rule.
default: "None"
tag:
description:
- Administrative tags that can be added to the rule. Note, tags must be already defined.
default: "None"
from_zone:
description:
- List of source zones.
default: "any"
to_zone:
description:
- List of destination zones.
default: "any"
source:
description:
- List of source addresses.
default: "any"
source_user:
description:
- Use users to enforce policy for individual users or a group of users.
default: "any"
hip_profiles:
description: >
If you are using GlobalProtect with host information profile (HIP) enabled, you can also base the policy
on information collected by GlobalProtect. For example, the user access level can be determined HIP that
notifies the firewall about the user's local configuration.
default: "any"
destination:
description:
- List of destination addresses.
default: "any"
application:
description:
- List of applications.
default: "any"
service:
description:
- List of services.
default: "application-default"
log_start:
description:
- Whether to log at session start.
default: false
log_end:
description:
- Whether to log at session end.
default: true
action:
description:
- Action to apply once rules maches.
default: "allow"
group_profile:
description: >
Security profile group that is already defined in the system. This property supersedes antivirus,
vulnerability, spyware, url_filtering, file_blocking, data_filtering, and wildfire_analysis properties.
default: None
antivirus:
description:
- Name of the already defined antivirus profile.
default: None
vulnerability:
description:
- Name of the already defined vulnerability profile.
default: None
spyware:
description:
- Name of the already defined spyware profile.
default: None
url_filtering:
description:
- Name of the already defined url_filtering profile.
default: None
file_blocking:
description:
- Name of the already defined file_blocking profile.
default: None
data_filtering:
description:
- Name of the already defined data_filtering profile.
default: None
wildfire_analysis:
description:
- Name of the already defined wildfire_analysis profile.
default: None
devicegroup:
description: >
Device groups are used for the Panorama interaction with Firewall(s). The group must exists on Panorama.
If device group is not define we assume that we are contacting Firewall.
default: None
commit:
description:
- Commit configuration if changed.
default: true
'''
EXAMPLES = '''
- name: permit ssh to 1.1.1.1
panos_security_policy:
ip_address: '10.5.172.91'
username: 'admin'
password: 'paloalto'
rule_name: 'SSH permit'
description: 'SSH rule test'
from_zone: ['public']
to_zone: ['private']
source: ['any']
source_user: ['any']
destination: ['1.1.1.1']
category: ['any']
application: ['ssh']
service: ['application-default']
hip_profiles: ['any']
action: 'allow'
commit: false
- name: Allow HTTP multimedia only from CDNs
panos_security_policy:
ip_address: '10.5.172.91'
username: 'admin'
password: 'paloalto'
rule_name: 'HTTP Multimedia'
description: 'Allow HTTP multimedia only to host at 1.1.1.1'
from_zone: ['public']
to_zone: ['private']
source: ['any']
source_user: ['any']
destination: ['1.1.1.1']
category: ['content-delivery-networks']
application: ['http-video', 'http-audio']
service: ['service-http', 'service-https']
hip_profiles: ['any']
action: 'allow'
commit: false
- name: more complex fictitious rule that uses profiles
panos_security_policy:
ip_address: '10.5.172.91'
username: 'admin'
password: 'paloalto'
rule_name: 'Allow HTTP w profile'
log_start: false
log_end: true
action: 'allow'
antivirus: 'default'
vulnerability: 'default'
spyware: 'default'
url_filtering: 'default'
wildfire_analysis: 'default'
commit: false
- name: deny all
panos_security_policy:
ip_address: '10.5.172.91'
username: 'admin'
password: 'paloalto'
rule_name: 'DenyAll'
log_start: true
log_end: true
action: 'deny'
rule_type: 'interzone'
commit: false
# permit ssh to 1.1.1.1 using panorama and pushing the configuration to firewalls
# that are defined in 'DeviceGroupA' device group
- name: permit ssh to 1.1.1.1 through Panorama
panos_security_policy:
ip_address: '10.5.172.92'
password: 'paloalto'
rule_name: 'SSH permit'
description: 'SSH rule test'
from_zone: ['public']
to_zone: ['private']
source: ['any']
source_user: ['any']
destination: ['1.1.1.1']
category: ['any']
application: ['ssh']
service: ['application-default']
hip_profiles: ['any']
action: 'allow'
devicegroup: 'DeviceGroupA'
'''
RETURN = '''
# Default return values
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import get_exception
try:
import pan.xapi
from pan.xapi import PanXapiError
import pandevice
import pandevice.firewall
import pandevice.panorama
import pandevice.objects
import pandevice.policies
HAS_LIB = True
except ImportError:
HAS_LIB = False
def security_rule_exists(device, rule_name):
if isinstance(device, pandevice.firewall.Firewall):
rule_base = pandevice.policies.Rulebase.refreshall(device)
elif isinstance(device, pandevice.panorama.Panorama):
# look for only pre-rulebase ATM
rule_base = pandevice.policies.PreRulebase.refreshall(device)
if rule_base:
rule_base = rule_base[0]
security_rules = rule_base.findall(pandevice.policies.SecurityRule)
if security_rules:
for r in security_rules:
if r.name == rule_name:
return True
return False
def create_security_rule(**kwargs):
security_rule = pandevice.policies.SecurityRule(
name=kwargs['rule_name'],
description=kwargs['description'],
tozone=kwargs['to_zone'],
fromzone=kwargs['from_zone'],
source=kwargs['source'],
source_user=kwargs['source_user'],
destination=kwargs['destination'],
category=kwargs['category'],
application=kwargs['application'],
service=kwargs['service'],
hip_profiles=kwargs['hip_profiles'],
log_start=kwargs['log_start'],
log_end=kwargs['log_end'],
type=kwargs['rule_type'],
action=kwargs['action'])
if 'tag' in kwargs:
security_rule.tag = kwargs['tag']
# profile settings
if 'group_profile' in kwargs:
security_rule.group = kwargs['group_profile']
else:
if 'antivirus' in kwargs:
security_rule.virus = kwargs['antivirus']
if 'vulnerability' in kwargs:
security_rule.vulnerability = kwargs['vulnerability']
if 'spyware' in kwargs:
security_rule.spyware = kwargs['spyware']
if 'url_filtering' in kwargs:
security_rule.url_filtering = kwargs['url_filtering']
if 'file_blocking' in kwargs:
security_rule.file_blocking = kwargs['file_blocking']
if 'data_filtering' in kwargs:
security_rule.data_filtering = kwargs['data_filtering']
if 'wildfire_analysis' in kwargs:
security_rule.wildfire_analysis = kwargs['wildfire_analysis']
return security_rule
def add_security_rule(device, sec_rule):
if isinstance(device, pandevice.firewall.Firewall):
rule_base = pandevice.policies.Rulebase.refreshall(device)
elif isinstance(device, pandevice.panorama.Panorama):
# look for only pre-rulebase ATM
rule_base = pandevice.policies.PreRulebase.refreshall(device)
if rule_base:
rule_base = rule_base[0]
rule_base.add(sec_rule)
sec_rule.create()
return True
else:
return False
def _commit(device, device_group=None):
"""
:param device: either firewall or panorama
:param device_group: panorama device group or if none then 'all'
:return: True if successful
"""
result = device.commit(sync=True)
if isinstance(device, pandevice.panorama.Panorama):
result = device.commit_all(sync=True, sync_all=True, devicegroup=device_group)
return result
def main():
argument_spec = dict(
ip_address=dict(required=True),
password=dict(no_log=True),
username=dict(default='admin'),
api_key=dict(no_log=True),
rule_name=dict(required=True),
description=dict(default=''),
tag=dict(),
to_zone=dict(type='list', default=['any']),
from_zone=dict(type='list', default=['any']),
source=dict(type='list', default=["any"]),
source_user=dict(type='list', default=['any']),
destination=dict(type='list', default=["any"]),
category=dict(type='list', default=['any']),
application=dict(type='list', default=['any']),
service=dict(type='list', default=['application-default']),
hip_profiles=dict(type='list', default=['any']),
group_profile=dict(),
antivirus=dict(),
vulnerability=dict(),
spyware=dict(),
url_filtering=dict(),
file_blocking=dict(),
data_filtering=dict(),
wildfire_analysis=dict(),
log_start=dict(type='bool', default=False),
log_end=dict(type='bool', default=True),
rule_type=dict(default='universal'),
action=dict(default='allow'),
devicegroup=dict(),
commit=dict(type='bool', default=True)
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False,
required_one_of=[['api_key', 'password']])
if not HAS_LIB:
module.fail_json(msg='Missing required pan-python and pandevice modules.')
ip_address = module.params["ip_address"]
password = module.params["password"]
username = module.params['username']
api_key = module.params['api_key']
rule_name = module.params['rule_name']
description = module.params['description']
tag = module.params['tag']
from_zone = module.params['from_zone']
to_zone = module.params['to_zone']
source = module.params['source']
source_user = module.params['source_user']
destination = module.params['destination']
category = module.params['category']
application = module.params['application']
service = module.params['service']
hip_profiles = module.params['hip_profiles']
log_start = module.params['log_start']
log_end = module.params['log_end']
rule_type = module.params['rule_type']
action = module.params['action']
group_profile = module.params['group_profile']
antivirus = module.params['antivirus']
vulnerability = module.params['vulnerability']
spyware = module.params['spyware']
url_filtering = module.params['url_filtering']
file_blocking = module.params['file_blocking']
data_filtering = module.params['data_filtering']
wildfire_analysis = module.params['wildfire_analysis']
devicegroup = module.params['devicegroup']
commit = module.params['commit']
if devicegroup:
device = pandevice.panorama.Panorama(ip_address, username, password, api_key=api_key)
dev_grps = device.refresh_devices()
for grp in dev_grps:
if grp.name == devicegroup:
break
module.fail_json(msg=' \'%s\' device group not found in Panorama. Is the name correct?' % devicegroup)
else:
device = pandevice.firewall.Firewall(ip_address, username, password, api_key=api_key)
if security_rule_exists(device, rule_name):
module.fail_json(msg='Rule with the same name already exists.')
try:
sec_rule = create_security_rule(
rule_name=rule_name,
description=description,
tag=tag,
from_zone=from_zone,
to_zone=to_zone,
source=source,
source_user=source_user,
destination=destination,
category=category,
application=application,
service=service,
hip_profiles=hip_profiles,
group_profile=group_profile,
antivirus=antivirus,
vulnerability=vulnerability,
spyware=spyware,
url_filtering=url_filtering,
file_blocking=file_blocking,
data_filtering=data_filtering,
wildfire_analysis=wildfire_analysis,
log_start=log_start,
log_end=log_end,
rule_type=rule_type,
action=action
)
changed = add_security_rule(device, sec_rule)
except PanXapiError:
exc = get_exception()
module.fail_json(msg=exc.message)
if changed and commit:
result = _commit(device, devicegroup)
module.exit_json(changed=changed, msg="okey dokey")
if __name__ == '__main__':
main()
|
scylladb/scylla-cluster-tests | refs/heads/master | unit_tests/test_sct_events_monitors.py | 1 | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 LICENSE for more details.
#
# Copyright (c) 2020 ScyllaDB
import pickle
import unittest
from sdcm.sct_events import Severity
from sdcm.sct_events.monitors import PrometheusAlertManagerEvent
RAW_ALERT = dict(
annotations=dict(
description="[10.0.201.178] has been down for more than 30 seconds.",
summary="Instance [10.0.201.178] down",
),
endsAt="2019-12-26T06:21:09.591Z",
startsAt="2019-12-24T17:00:09.591Z",
updatedAt="2019-12-26T06:18:09.593Z",
labels=dict(
alertname="InstanceDown",
instance="[10.0.201.178]",
job="scylla",
monitor="scylla-monitor",
severity="2",
),
)
class TestPrometheusAlertManagerEvent(unittest.TestCase):
def test_msgfmt(self):
event = PrometheusAlertManagerEvent.start(raw_alert=RAW_ALERT)
event.event_id = "536eaf22-3d8f-418a-9381-fe0bcdce7ad9"
self.assertEqual(
str(event),
"(PrometheusAlertManagerEvent Severity.WARNING) period_type=not-set "
"event_id=536eaf22-3d8f-418a-9381-fe0bcdce7ad9: alert_name=InstanceDown type=start"
" start=2019-12-24T17:00:09.591Z end=2019-12-26T06:21:09.591Z"
" description=[10.0.201.178] has been down for more than 30 seconds. updated=2019-12-26T06:18:09.593Z"
" state= fingerprint=None labels={'alertname': 'InstanceDown', 'instance': '[10.0.201.178]',"
" 'job': 'scylla', 'monitor': 'scylla-monitor', 'severity': '2'}"
)
self.assertEqual(event, pickle.loads(pickle.dumps(event)))
def test_sct_severity(self):
event = PrometheusAlertManagerEvent.end(raw_alert=dict(labels=dict(sct_severity="CRITICAL")))
self.assertEqual(event.severity, Severity.CRITICAL)
self.assertTrue(str(event).startswith("(PrometheusAlertManagerEvent Severity.CRITICAL)"))
self.assertEqual(event, pickle.loads(pickle.dumps(event)))
def test_sct_severity_wrong(self):
event = PrometheusAlertManagerEvent.end(raw_alert=dict(labels=dict(sct_severity="WRONG")))
self.assertEqual(event.severity, Severity.WARNING)
self.assertTrue(str(event).startswith("(PrometheusAlertManagerEvent Severity.WARNING)"))
self.assertEqual(event, pickle.loads(pickle.dumps(event)))
|
keisukefukuda/mpienv | refs/heads/master | mpienv/piplib.py | 1 | # coding: utf-8
import os
import pip
import re
from subprocess import check_call
from subprocess import check_output # NOQA
from subprocess import PIPE # NOQA
from subprocess import Popen # NOQA
import sys
# We support pip 10.x.x, 9.x.x and 1.5
_pip_ver = None
def _get_pip_ver():
global _pip_ver
ver = pip.__version__
m = re.match(r'(\d+)[.](\S+)', ver)
major_ver = int(m.group(1))
if major_ver >= 9:
_pip_ver = str(major_ver)
elif ver.startswith("1.5"):
_pip_ver = '1.5'
else:
raise RuntimeError("Error: Unsupported pip version")
def install(libname, target_dir, build_dir, env):
if _pip_ver is None:
_get_pip_ver()
# if 'LD_LIBRARY_PATH' not in env:
# env['LD_LIBRARY_PATH'] = ""
cmd = None
if float(_pip_ver) > 8: # >= 9
# 9.x.x
cmd = [sys.executable, '-m', 'pip', 'install',
# '-q',
'--no-binary', ':all:',
'-t', target_dir,
'-b', build_dir,
# '--no-cache-dir',
libname]
else:
# 1.5.x
cmd = ['pip', 'install',
# '-q',
'-t', target_dir,
'-b', build_dir,
libname]
if os.environ.get("MPIENV_PIP_VERBOSE") is not None:
cmd[2:3] = ['-v']
# sys.stderr.write("{}\n".format(' '.join(cmd)))
check_call(cmd,
stdout=sys.stderr,
env=env)
|
haozai309/hello_python | refs/heads/master | google-python-exercises/basic/solution/list1.py | 209 | #!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
# Basic list exercises
# Fill in the code for the functions below. main() is already set up
# to call the functions with a few different inputs,
# printing 'OK' when each function is correct.
# The starter code for each function includes a 'return'
# which is just a placeholder for your code.
# It's ok if you do not complete all the functions, and there
# are some additional functions to try in list2.py.
# A. match_ends
# Given a list of strings, return the count of the number of
# strings where the string length is 2 or more and the first
# and last chars of the string are the same.
# Note: python does not have a ++ operator, but += works.
def match_ends(words):
# +++your code here+++
# LAB(begin solution)
count = 0
for word in words:
if len(word) >= 2 and word[0] == word[-1]:
count = count + 1
return count
# LAB(replace solution)
# return
# LAB(end solution)
# B. front_x
# Given a list of strings, return a list with the strings
# in sorted order, except group all the strings that begin with 'x' first.
# e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields
# ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']
# Hint: this can be done by making 2 lists and sorting each of them
# before combining them.
def front_x(words):
# +++your code here+++
# LAB(begin solution)
# Put each word into the x_list or the other_list.
x_list = []
other_list = []
for w in words:
if w.startswith('x'):
x_list.append(w)
else:
other_list.append(w)
return sorted(x_list) + sorted(other_list)
# LAB(replace solution)
# return
# LAB(end solution)
# LAB(begin solution)
# Extract the last element from a tuple -- used for custom sorting below.
def last(a):
return a[-1]
# LAB(end solution)
# C. sort_last
# Given a list of non-empty tuples, return a list sorted in increasing
# order by the last element in each tuple.
# e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
# [(2, 2), (1, 3), (3, 4, 5), (1, 7)]
# Hint: use a custom key= function to extract the last element form each tuple.
def sort_last(tuples):
# +++your code here+++
# LAB(begin solution)
return sorted(tuples, key=last)
# LAB(replace solution)
# return
# LAB(end solution)
# Simple provided test() function used in main() to print
# what each function returns vs. what it's supposed to return.
def test(got, expected):
if got == expected:
prefix = ' OK '
else:
prefix = ' X '
print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))
# Calls the above functions with interesting inputs.
def main():
print 'match_ends'
test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3)
test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2)
test(match_ends(['aaa', 'be', 'abc', 'hello']), 1)
print
print 'front_x'
test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']),
['xaa', 'xzz', 'axx', 'bbb', 'ccc'])
test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']),
['xaa', 'xcc', 'aaa', 'bbb', 'ccc'])
test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']),
['xanadu', 'xyz', 'aardvark', 'apple', 'mix'])
print
print 'sort_last'
test(sort_last([(1, 3), (3, 2), (2, 1)]),
[(2, 1), (3, 2), (1, 3)])
test(sort_last([(2, 3), (1, 2), (3, 1)]),
[(3, 1), (1, 2), (2, 3)])
test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]),
[(2, 2), (1, 3), (3, 4, 5), (1, 7)])
if __name__ == '__main__':
main()
|
glwu/python-for-android | refs/heads/master | python3-alpha/python3-src/Lib/idlelib/idle.py | 269 | import os.path
import sys
# If we are working on a development version of IDLE, we need to prepend the
# parent of this idlelib dir to sys.path. Otherwise, importing idlelib gets
# the version installed with the Python used to call this module:
idlelib_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, idlelib_dir)
import idlelib.PyShell
idlelib.PyShell.main()
|
MTK6580/walkie-talkie | refs/heads/master | ALPS.L1.MP6.V2_HEXING6580_WE_L/alps/cts/apps/CameraITS/tests/scene1/test_param_sensitivity.py | 3 | # Copyright 2013 The Android Open Source Project
#
# 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 its.image
import its.caps
import its.device
import its.objects
import its.target
import pylab
import os.path
import matplotlib
import matplotlib.pyplot
def main():
"""Test that the android.sensor.sensitivity parameter is applied.
"""
NAME = os.path.basename(__file__).split(".")[0]
NUM_STEPS = 5
sensitivities = None
r_means = []
g_means = []
b_means = []
with its.device.ItsSession() as cam:
props = cam.get_camera_properties()
its.caps.skip_unless(its.caps.compute_target_exposure(props) and
its.caps.per_frame_control(props))
expt,_ = its.target.get_target_exposure_combos(cam)["midSensitivity"]
sens_range = props['android.sensor.info.sensitivityRange']
sens_step = (sens_range[1] - sens_range[0]) / float(NUM_STEPS-1)
sensitivities = [sens_range[0] + i * sens_step for i in range(NUM_STEPS)]
for s in sensitivities:
req = its.objects.manual_capture_request(s, expt)
cap = cam.do_capture(req)
img = its.image.convert_capture_to_rgb_image(cap)
its.image.write_image(
img, "%s_iso=%04d.jpg" % (NAME, s))
tile = its.image.get_image_patch(img, 0.45, 0.45, 0.1, 0.1)
rgb_means = its.image.compute_image_means(tile)
r_means.append(rgb_means[0])
g_means.append(rgb_means[1])
b_means.append(rgb_means[2])
# Draw a plot.
pylab.plot(sensitivities, r_means, 'r')
pylab.plot(sensitivities, g_means, 'g')
pylab.plot(sensitivities, b_means, 'b')
pylab.ylim([0,1])
matplotlib.pyplot.savefig("%s_plot_means.png" % (NAME))
# Test for pass/fail: check that each shot is brighter than the previous.
for means in [r_means, g_means, b_means]:
for i in range(len(means)-1):
assert(means[i+1] > means[i])
if __name__ == '__main__':
main()
|
bzero/statsmodels | refs/heads/master | statsmodels/duration/hazard_regression.py | 9 | import numpy as np
from statsmodels.base import model
import statsmodels.base.model as base
from statsmodels.tools.decorators import cache_readonly
from scipy.optimize import brent
"""
Implementation of proportional hazards regression models for duration
data that may be censored ("Cox models").
References
----------
T Therneau (1996). Extending the Cox model. Technical report.
http://www.mayo.edu/research/documents/biostat-58pdf/DOC-10027288
G Rodriguez (2005). Non-parametric estimation in survival models.
http://data.princeton.edu/pop509/NonParametricSurvival.pdf
B Gillespie (2006). Checking the assumptions in the Cox proportional
hazards model.
http://www.mwsug.org/proceedings/2006/stats/MWSUG-2006-SD08.pdf
"""
_predict_docstring = """
Returns predicted values from the proportional hazards
regression model.
Parameters
----------
params : array-like
The proportional hazards model parameters.
exog : array-like
Data to use as `exog` in forming predictions. If not
provided, the `exog` values from the model used to fit the
data are used.%(cov_params_doc)s
endog : array-like
Duration (time) values at which the predictions are made.
Only used if pred_type is either 'cumhaz' or 'surv'. If
using model `exog`, defaults to model `endog` (time), but
may be provided explicitly to make predictions at
alternative times.
strata : array-like
A vector of stratum values used to form the predictions.
Not used (may be 'None') if pred_type is 'lhr' or 'hr'.
If `exog` is None, the model stratum values are used. If
`exog` is not None and pred_type is 'surv' or 'cumhaz',
stratum values must be provided (unless there is only one
stratum).
offset : array-like
Offset values used to create the predicted values.
pred_type : string
If 'lhr', returns log hazard ratios, if 'hr' returns
hazard ratios, if 'surv' returns the survival function, if
'cumhaz' returns the cumulative hazard function.
Returns
-------
A bunch containing two fields: `predicted_values` and
`standard_errors`.
Notes
-----
Standard errors are only returned when predicting the log
hazard ratio (pred_type is 'lhr').
Types `surv` and `cumhaz` require estimation of the cumulative
hazard function.
"""
_predict_cov_params_docstring = """
cov_params : array-like
The covariance matrix of the estimated `params` vector,
used to obtain prediction errors if pred_type='lhr',
otherwise optional."""
class PHSurvivalTime(object):
def __init__(self, time, status, exog, strata=None, entry=None,
offset=None):
"""
Represent a collection of survival times with possible
stratification and left truncation.
Parameters
----------
time : array_like
The times at which either the event (failure) occurs or
the observation is censored.
status : array_like
Indicates whether the event (failure) occurs at `time`
(`status` is 1), or if `time` is a censoring time (`status`
is 0).
exog : array_like
The exogeneous (covariate) data matrix, cases are rows and
variables are columns.
strata : array_like
Grouping variable defining the strata. If None, all
observations are in a single stratum.
entry : array_like
Entry (left truncation) times. The observation is not
part of the risk set for times before the entry time. If
None, the entry time is treated as being zero, which
gives no left truncation. The entry time must be less
than or equal to `time`.
offset : array-like
An optional array of offsets
"""
# Default strata
if strata is None:
strata = np.zeros(len(time), dtype=np.int32)
# Default entry times
if entry is None:
entry = np.zeros(len(time))
# Parameter validity checks.
n1, n2, n3, n4 = len(time), len(status), len(strata),\
len(entry)
nv = [n1, n2, n3, n4]
if max(nv) != min(nv):
raise ValueError("endog, status, strata, and " +
"entry must all have the same length")
if min(time) < 0:
raise ValueError("endog must be non-negative")
if min(entry) < 0:
raise ValueError("entry time must be non-negative")
# In Stata, this is entry >= time, in R it is >.
if np.any(entry > time):
raise ValueError("entry times may not occur " +
"after event or censoring times")
# Get the row indices for the cases in each stratum
if strata is not None:
stu = np.unique(strata)
#sth = {x: [] for x in stu} # needs >=2.7
sth = dict([(x, []) for x in stu])
for i,k in enumerate(strata):
sth[k].append(i)
stratum_rows = [np.asarray(sth[k], dtype=np.int32) for k in stu]
stratum_names = stu
else:
stratum_rows = [np.arange(len(time)),]
stratum_names = [0,]
# Remove strata with no events
ix = [i for i,ix in enumerate(stratum_rows) if status[ix].sum() > 0]
stratum_rows = [stratum_rows[i] for i in ix]
stratum_names = [stratum_names[i] for i in ix]
# The number of strata
nstrat = len(stratum_rows)
self.nstrat = nstrat
# Remove subjects whose entry time occurs after the last event
# in their stratum.
for stx,ix in enumerate(stratum_rows):
last_failure = max(time[ix][status[ix] == 1])
# Stata uses < here, R uses <=
ii = [i for i,t in enumerate(entry[ix]) if
t <= last_failure]
stratum_rows[stx] = stratum_rows[stx][ii]
# Remove subjects who are censored before the first event in
# their stratum.
for stx,ix in enumerate(stratum_rows):
first_failure = min(time[ix][status[ix] == 1])
ii = [i for i,t in enumerate(time[ix]) if
t >= first_failure]
stratum_rows[stx] = stratum_rows[stx][ii]
# Order by time within each stratum
for stx,ix in enumerate(stratum_rows):
ii = np.argsort(time[ix])
stratum_rows[stx] = stratum_rows[stx][ii]
if offset is not None:
self.offset_s = []
for stx in range(nstrat):
self.offset_s.append(offset[stratum_rows[stx]])
else:
self.offset_s = None
# Number of informative subjects
self.n_obs = sum([len(ix) for ix in stratum_rows])
# Split everything by stratum
self.time_s = []
self.exog_s = []
self.status_s = []
self.entry_s = []
for ix in stratum_rows:
self.time_s.append(time[ix])
self.exog_s.append(exog[ix,:])
self.status_s.append(status[ix])
self.entry_s.append(entry[ix])
self.stratum_rows = stratum_rows
self.stratum_names = stratum_names
# Precalculate some indices needed to fit Cox models.
# Distinct failure times within a stratum are always taken to
# be sorted in ascending order.
#
# ufailt_ix[stx][k] is a list of indices for subjects who fail
# at the k^th sorted unique failure time in stratum stx
#
# risk_enter[stx][k] is a list of indices for subjects who
# enter the risk set at the k^th sorted unique failure time in
# stratum stx
#
# risk_exit[stx][k] is a list of indices for subjects who exit
# the risk set at the k^th sorted unique failure time in
# stratum stx
self.ufailt_ix, self.risk_enter, self.risk_exit, self.ufailt =\
[], [], [], []
for stx in range(self.nstrat):
# All failure times
ift = np.flatnonzero(self.status_s[stx] == 1)
ft = self.time_s[stx][ift]
# Unique failure times
uft = np.unique(ft)
nuft = len(uft)
# Indices of cases that fail at each unique failure time
#uft_map = {x:i for i,x in enumerate(uft)} # requires >=2.7
uft_map = dict([(x, i) for i,x in enumerate(uft)]) # 2.6
uft_ix = [[] for k in range(nuft)]
for ix,ti in zip(ift,ft):
uft_ix[uft_map[ti]].append(ix)
# Indices of cases (failed or censored) that enter the
# risk set at each unique failure time.
risk_enter1 = [[] for k in range(nuft)]
for i,t in enumerate(self.time_s[stx]):
ix = np.searchsorted(uft, t, "right") - 1
if ix >= 0:
risk_enter1[ix].append(i)
# Indices of cases (failed or censored) that exit the
# risk set at each unique failure time.
risk_exit1 = [[] for k in range(nuft)]
for i,t in enumerate(self.entry_s[stx]):
ix = np.searchsorted(uft, t)
risk_exit1[ix].append(i)
self.ufailt.append(uft)
self.ufailt_ix.append([np.asarray(x, dtype=np.int32) for x in uft_ix])
self.risk_enter.append([np.asarray(x, dtype=np.int32) for x in risk_enter1])
self.risk_exit.append([np.asarray(x, dtype=np.int32) for x in risk_exit1])
class PHReg(model.LikelihoodModel):
"""
Fit the Cox proportional hazards regression model for right
censored data.
Parameters
----------
endog : array-like
The observed times (event or censoring)
exog : 2D array-like
The covariates or exogeneous variables
status : array-like
The censoring status values; status=1 indicates that an
event occured (e.g. failure or death), status=0 indicates
that the observation was right censored. If None, defaults
to status=1 for all cases.
entry : array-like
The entry times, if left truncation occurs
strata : array-like
Stratum labels. If None, all observations are taken to be
in a single stratum.
ties : string
The method used to handle tied times, must be either 'breslow'
or 'efron'.
offset : array-like
Array of offset values
missing : string
The method used to handle missing data
Notes
-----
Proportional hazards regression models should not include an
explicit or implicit intercept. The effect of an intercept is
not identified using the partial likelihood approach.
`endog`, `event`, `strata`, `entry`, and the first dimension
of `exog` all must have the same length
"""
def __init__(self, endog, exog, status=None, entry=None,
strata=None, offset=None, ties='breslow',
missing='drop', **kwargs):
# Default is no censoring
if status is None:
status = np.ones(len(endog))
super(PHReg, self).__init__(endog, exog, status=status,
entry=entry, strata=strata,
offset=offset, missing=missing,
**kwargs)
# endog and exog are automatically converted, but these are
# not
if self.status is not None:
self.status = np.asarray(self.status)
if self.entry is not None:
self.entry = np.asarray(self.entry)
if self.strata is not None:
self.strata = np.asarray(self.strata)
if self.offset is not None:
self.offset = np.asarray(self.offset)
self.surv = PHSurvivalTime(self.endog, self.status,
self.exog, self.strata,
self.entry, self.offset)
# TODO: not used?
self.missing = missing
ties = ties.lower()
if ties not in ("efron", "breslow"):
raise ValueError("`ties` must be either `efron` or " +
"`breslow`")
self.ties = ties
@classmethod
def from_formula(cls, formula, data, status=None, entry=None,
strata=None, offset=None, subset=None,
ties='breslow', missing='drop', *args, **kwargs):
"""
Create a proportional hazards regression model from a formula
and dataframe.
Parameters
----------
formula : str or generic Formula object
The formula specifying the model
data : array-like
The data for the model. See Notes.
status : array-like
The censoring status values; status=1 indicates that an
event occured (e.g. failure or death), status=0 indicates
that the observation was right censored. If None, defaults
to status=1 for all cases.
entry : array-like
The entry times, if left truncation occurs
strata : array-like
Stratum labels. If None, all observations are taken to be
in a single stratum.
offset : array-like
Array of offset values
subset : array-like
An array-like object of booleans, integers, or index
values that indicate the subset of df to use in the
model. Assumes df is a `pandas.DataFrame`
ties : string
The method used to handle tied times, must be either 'breslow'
or 'efron'.
missing : string
The method used to handle missing data
args : extra arguments
These are passed to the model
kwargs : extra keyword arguments
These are passed to the model with one exception. The
``eval_env`` keyword is passed to patsy. It can be either a
:class:`patsy:patsy.EvalEnvironment` object or an integer
indicating the depth of the namespace to use. For example, the
default ``eval_env=0`` uses the calling namespace. If you wish
to use a "clean" environment set ``eval_env=-1``.
Returns
-------
model : PHReg model instance
"""
# Allow array arguments to be passed by column name.
if type(status) is str:
status = data[status]
if type(entry) is str:
entry = data[entry]
if type(strata) is str:
strata = data[strata]
if type(offset) is str:
offset = data[offset]
mod = super(PHReg, cls).from_formula(formula, data,
status=status, entry=entry, strata=strata,
offset=offset, subset=subset, ties=ties,
missing=missing, *args, **kwargs)
return mod
def fit(self, groups=None, **args):
"""
Fit a proportional hazards regression model.
Parameters
----------
groups : array-like
Labels indicating groups of observations that may be
dependent. If present, the standard errors account for
this dependence. Does not affect fitted values.
Returns a PHregResults instance.
"""
# TODO process for missing values
if groups is not None:
self.groups = np.asarray(groups)
else:
self.groups = None
if 'disp' not in args:
args['disp'] = False
fit_rslts = super(PHReg, self).fit(**args)
if self.groups is None:
cov_params = fit_rslts.cov_params()
else:
cov_params = self.robust_covariance(fit_rslts.params)
results = PHRegResults(self, fit_rslts.params, cov_params)
return results
def fit_regularized(self, method="coord_descent", maxiter=100,
alpha=0., L1_wt=1., start_params=None,
cnvrg_tol=1e-7, zero_tol=1e-8, **kwargs):
"""
Return a regularized fit to a linear regression model.
Parameters
----------
method :
Only the coordinate descent algorithm is implemented.
maxiter : integer
The maximum number of iteration cycles (an iteration cycle
involves running coordinate descent on all variables).
alpha : scalar or array-like
The penalty weight. If a scalar, the same penalty weight
applies to all variables in the model. If a vector, it
must have the same length as `params`, and contains a
penalty weight for each coefficient.
L1_wt : scalar
The fraction of the penalty given to the L1 penalty term.
Must be between 0 and 1 (inclusive). If 0, the fit is
a ridge fit, if 1 it is a lasso fit.
start_params : array-like
Starting values for `params`.
cnvrg_tol : scalar
If `params` changes by less than this amount (in sup-norm)
in once iteration cycle, the algorithm terminates with
convergence.
zero_tol : scalar
Any estimated coefficient smaller than this value is
replaced with zero.
Returns
-------
A PHregResults object, of the same type returned by `fit`.
Notes
-----
The penalty is the"elastic net" penalty, which
is a convex combination of L1 and L2 penalties.
The function that is minimized is: ..math::
-loglike/n + alpha*((1-L1_wt)*|params|_2^2/2 + L1_wt*|params|_1)
where :math:`|*|_1` and :math:`|*|_2` are the L1 and L2 norms.
Post-estimation results are based on the same data used to
select variables, hence may be subject to overfitting biases.
"""
k_exog = self.exog.shape[1]
n_exog = self.exog.shape[0]
if np.isscalar(alpha):
alpha = alpha * np.ones(k_exog, dtype=np.float64)
# regularization cannot be used with groups
self.groups = None
# Define starting params
if start_params is None:
params = np.zeros(k_exog, dtype=np.float64)
else:
params = start_params.copy()
# Maybe could be a shallow copy, but just in case...
import copy
surv = copy.deepcopy(self.surv)
# This is the base offset, onto which the effects of
# constrained variables are added.
if self.offset is None:
offset_s_base = [np.zeros(len(x)) for x in surv.stratum_rows]
surv.offset_s = [x.copy() for x in offset_s_base]
else:
offset_s_base = [x.copy() for x in surv.offset_s]
# Create a model instance for optimizing a single variable
model_1var = copy.deepcopy(self)
model_1var.surv = surv
model_1var.ties = self.ties
# All the negative penalized loglikeihood functions.
def gen_npfuncs(k):
def nploglike(params):
pen = alpha[k]*((1 - L1_wt)*params**2/2 + L1_wt*np.abs(params))
return -model_1var.loglike(np.r_[params]) / n_exog + pen
def npscore(params):
pen_grad = alpha[k]*(1 - L1_wt)*params
return -model_1var.score(np.r_[params])[0] / n_exog + pen_grad
def nphess(params):
pen_hess = alpha[k]*(1 - L1_wt)
return -model_1var.hessian(np.r_[params])[0,0] / n_exog + pen_hess
return nploglike, npscore, nphess
nploglike_funcs = [gen_npfuncs(k) for k in range(len(params))]
# 1-dimensional exog's
exog_s = []
for k in range(k_exog):
ex = [x[:, k][:, None] for x in surv.exog_s]
exog_s.append(ex)
converged = False
btol = 1e-8
params_zero = np.zeros(len(params), dtype=bool)
for itr in range(maxiter):
# Sweep through the parameters
params_save = params.copy()
for k in range(k_exog):
# Under the active set method, if a parameter becomes
# zero we don't try to change it again.
if params_zero[k]:
continue
# Set exog to include only the variable whose effect
# is being estimated.
surv.exog_s = exog_s[k]
# Set the offset to account for the variables that are
# being held fixed.
params0 = params.copy()
params0[k] = 0
for stx in range(self.surv.nstrat):
v = np.dot(self.surv.exog_s[stx], params0)
surv.offset_s[stx] = offset_s_base[stx] + v
params[k] = _opt_1d(nploglike_funcs[k], params[k],
alpha[k]*L1_wt, tol=btol)
# Update the active set
if itr > 0 and np.abs(params[k]) < zero_tol:
params_zero[k] = True
params[k] = 0.
# Check for convergence
pchange = np.max(np.abs(params - params_save))
if pchange < cnvrg_tol:
converged = True
break
# Set approximate zero coefficients to be exactly zero
params *= np.abs(params) >= zero_tol
# Fit the reduced model to get standard errors and other
# post-estimation results.
ii = np.flatnonzero(params)
cov = np.zeros((k_exog, k_exog), dtype=np.float64)
if len(ii) > 0:
model = self.__class__(self.endog, self.exog[:, ii],
status=self.status, entry=self.entry,
strata=self.strata, offset=self.offset,
ties=self.ties, missing=self.missing)
rslt = model.fit()
cov[np.ix_(ii, ii)] = rslt.normalized_cov_params
rfit = PHRegResults(self, params, cov_params=cov)
rfit.converged = converged
rfit.regularized = True
return rfit
def loglike(self, params):
"""
Returns the log partial likelihood function evaluated at
`params`.
"""
if self.ties == "breslow":
return self.breslow_loglike(params)
elif self.ties == "efron":
return self.efron_loglike(params)
def score(self, params):
"""
Returns the score function evaluated at `params`.
"""
if self.ties == "breslow":
return self.breslow_gradient(params)
elif self.ties == "efron":
return self.efron_gradient(params)
def hessian(self, params):
"""
Returns the Hessian matrix of the log partial likelihood
function evaluated at `params`.
"""
if self.ties == "breslow":
return self.breslow_hessian(params)
else:
return self.efron_hessian(params)
def breslow_loglike(self, params):
"""
Returns the value of the log partial likelihood function
evaluated at `params`, using the Breslow method to handle tied
times.
"""
surv = self.surv
like = 0.
# Loop over strata
for stx in range(surv.nstrat):
uft_ix = surv.ufailt_ix[stx]
exog_s = surv.exog_s[stx]
nuft = len(uft_ix)
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
linpred -= linpred.max()
e_linpred = np.exp(linpred)
xp0 = 0.
# Iterate backward through the unique failure times.
for i in range(nuft)[::-1]:
# Update for new cases entering the risk set.
ix = surv.risk_enter[stx][i]
xp0 += e_linpred[ix].sum()
# Account for all cases that fail at this point.
ix = uft_ix[i]
like += (linpred[ix] - np.log(xp0)).sum()
# Update for cases leaving the risk set.
ix = surv.risk_exit[stx][i]
xp0 -= e_linpred[ix].sum()
return like
def efron_loglike(self, params):
"""
Returns the value of the log partial likelihood function
evaluated at `params`, using the Efron method to handle tied
times.
"""
surv = self.surv
like = 0.
# Loop over strata
for stx in range(surv.nstrat):
# exog and linear predictor for this stratum
exog_s = surv.exog_s[stx]
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
linpred -= linpred.max()
e_linpred = np.exp(linpred)
xp0 = 0.
# Iterate backward through the unique failure times.
uft_ix = surv.ufailt_ix[stx]
nuft = len(uft_ix)
for i in range(nuft)[::-1]:
# Update for new cases entering the risk set.
ix = surv.risk_enter[stx][i]
xp0 += e_linpred[ix].sum()
xp0f = e_linpred[uft_ix[i]].sum()
# Account for all cases that fail at this point.
ix = uft_ix[i]
like += linpred[ix].sum()
m = len(ix)
J = np.arange(m, dtype=np.float64) / m
like -= np.log(xp0 - J*xp0f).sum()
# Update for cases leaving the risk set.
ix = surv.risk_exit[stx][i]
xp0 -= e_linpred[ix].sum()
return like
def breslow_gradient(self, params):
"""
Returns the gradient of the log partial likelihood, using the
Breslow method to handle tied times.
"""
surv = self.surv
grad = 0.
# Loop over strata
for stx in range(surv.nstrat):
# Indices of subjects in the stratum
strat_ix = surv.stratum_rows[stx]
# Unique failure times in the stratum
uft_ix = surv.ufailt_ix[stx]
nuft = len(uft_ix)
# exog and linear predictor for the stratum
exog_s = surv.exog_s[stx]
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
linpred -= linpred.max()
e_linpred = np.exp(linpred)
xp0, xp1 = 0., 0.
# Iterate backward through the unique failure times.
for i in range(nuft)[::-1]:
# Update for new cases entering the risk set.
ix = surv.risk_enter[stx][i]
if len(ix) > 0:
v = exog_s[ix,:]
xp0 += e_linpred[ix].sum()
xp1 += (e_linpred[ix][:,None] * v).sum(0)
# Account for all cases that fail at this point.
ix = uft_ix[i]
grad += (exog_s[ix,:] - xp1 / xp0).sum(0)
# Update for cases leaving the risk set.
ix = surv.risk_exit[stx][i]
if len(ix) > 0:
v = exog_s[ix,:]
xp0 -= e_linpred[ix].sum()
xp1 -= (e_linpred[ix][:,None] * v).sum(0)
return grad
def efron_gradient(self, params):
"""
Returns the gradient of the log partial likelihood evaluated
at `params`, using the Efron method to handle tied times.
"""
surv = self.surv
grad = 0.
# Loop over strata
for stx in range(surv.nstrat):
# Indices of cases in the stratum
strat_ix = surv.stratum_rows[stx]
# exog and linear predictor of the stratum
exog_s = surv.exog_s[stx]
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
linpred -= linpred.max()
e_linpred = np.exp(linpred)
xp0, xp1 = 0., 0.
# Iterate backward through the unique failure times.
uft_ix = surv.ufailt_ix[stx]
nuft = len(uft_ix)
for i in range(nuft)[::-1]:
# Update for new cases entering the risk set.
ix = surv.risk_enter[stx][i]
if len(ix) > 0:
v = exog_s[ix,:]
xp0 += e_linpred[ix].sum()
xp1 += (e_linpred[ix][:,None] * v).sum(0)
ixf = uft_ix[i]
if len(ixf) > 0:
v = exog_s[ixf,:]
xp0f = e_linpred[ixf].sum()
xp1f = (e_linpred[ixf][:,None] * v).sum(0)
# Consider all cases that fail at this point.
grad += v.sum(0)
m = len(ixf)
J = np.arange(m, dtype=np.float64) / m
numer = xp1 - np.outer(J, xp1f)
denom = xp0 - np.outer(J, xp0f)
ratio = numer / denom
rsum = ratio.sum(0)
grad -= rsum
# Update for cases leaving the risk set.
ix = surv.risk_exit[stx][i]
if len(ix) > 0:
v = exog_s[ix,:]
xp0 -= e_linpred[ix].sum()
xp1 -= (e_linpred[ix][:,None] * v).sum(0)
return grad
def breslow_hessian(self, params):
"""
Returns the Hessian of the log partial likelihood evaluated at
`params`, using the Breslow method to handle tied times.
"""
surv = self.surv
hess = 0.
# Loop over strata
for stx in range(surv.nstrat):
uft_ix = surv.ufailt_ix[stx]
nuft = len(uft_ix)
exog_s = surv.exog_s[stx]
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
linpred -= linpred.max()
e_linpred = np.exp(linpred)
xp0, xp1, xp2 = 0., 0., 0.
# Iterate backward through the unique failure times.
for i in range(nuft)[::-1]:
# Update for new cases entering the risk set.
ix = surv.risk_enter[stx][i]
if len(ix) > 0:
xp0 += e_linpred[ix].sum()
v = exog_s[ix,:]
xp1 += (e_linpred[ix][:,None] * v).sum(0)
mat = v[None,:,:]
elx = e_linpred[ix]
xp2 += (mat.T * mat * elx[None,:,None]).sum(1)
# Account for all cases that fail at this point.
m = len(uft_ix[i])
hess += m*(xp2 / xp0 - np.outer(xp1, xp1) / xp0**2)
# Update for new cases entering the risk set.
ix = surv.risk_exit[stx][i]
if len(ix) > 0:
xp0 -= e_linpred[ix].sum()
v = exog_s[ix,:]
xp1 -= (e_linpred[ix][:,None] * v).sum(0)
mat = v[None,:,:]
elx = e_linpred[ix]
xp2 -= (mat.T * mat * elx[None,:,None]).sum(1)
return -hess
def efron_hessian(self, params):
"""
Returns the Hessian matrix of the partial log-likelihood
evaluated at `params`, using the Efron method to handle tied
times.
"""
surv = self.surv
hess = 0.
# Loop over strata
for stx in range(surv.nstrat):
exog_s = surv.exog_s[stx]
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
linpred -= linpred.max()
e_linpred = np.exp(linpred)
xp0, xp1, xp2 = 0., 0., 0.
# Iterate backward through the unique failure times.
uft_ix = surv.ufailt_ix[stx]
nuft = len(uft_ix)
for i in range(nuft)[::-1]:
# Update for new cases entering the risk set.
ix = surv.risk_enter[stx][i]
if len(ix) > 0:
xp0 += e_linpred[ix].sum()
v = exog_s[ix,:]
xp1 += (e_linpred[ix][:,None] * v).sum(0)
mat = v[None,:,:]
elx = e_linpred[ix]
xp2 += (mat.T * mat * elx[None,:,None]).sum(1)
ixf = uft_ix[i]
if len(ixf) > 0:
v = exog_s[ixf,:]
xp0f = e_linpred[ixf].sum()
xp1f = (e_linpred[ixf][:,None] * v).sum(0)
mat = v[None,:,:]
elx = e_linpred[ixf]
xp2f = (mat.T * mat * elx[None,:,None]).sum(1)
# Account for all cases that fail at this point.
m = len(uft_ix[i])
J = np.arange(m, dtype=np.float64) / m
c0 = xp0 - J*xp0f
mat = (xp2[None,:,:] - J[:,None,None]*xp2f) / c0[:,None,None]
hess += mat.sum(0)
mat = (xp1[None, :] - np.outer(J, xp1f)) / c0[:, None]
mat = mat[:, :, None] * mat[:, None, :]
hess -= mat.sum(0)
# Update for new cases entering the risk set.
ix = surv.risk_exit[stx][i]
if len(ix) > 0:
xp0 -= e_linpred[ix].sum()
v = exog_s[ix,:]
xp1 -= (e_linpred[ix][:,None] * v).sum(0)
mat = v[None,:,:]
elx = e_linpred[ix]
xp2 -= (mat.T * mat * elx[None,:,None]).sum(1)
return -hess
def robust_covariance(self, params):
"""
Returns a covariance matrix for the proportional hazards model
regresion coefficient estimates that is robust to certain
forms of model misspecification.
Parameters
----------
params : ndarray
The parameter vector at which the covariance matrix is
calculated.
Returns
-------
The robust covariance matrix as a square ndarray.
Notes
-----
This function uses the `groups` argument to determine groups
within which observations may be dependent. The covariance
matrix is calculated using the Huber-White "sandwich" approach.
"""
if self.groups is None:
raise ValueError("`groups` must be specified to calculate the robust covariance matrix")
hess = self.hessian(params)
score_obs = self.score_residuals(params)
# Collapse
grads = {}
for i,g in enumerate(self.groups):
if g not in grads:
grads[g] = 0.
grads[g] += score_obs[i, :]
grads = np.asarray(list(grads.values()))
mat = grads[None, :, :]
mat = mat.T * mat
mat = mat.sum(1)
hess_inv = np.linalg.inv(hess)
cmat = np.dot(hess_inv, np.dot(mat, hess_inv))
return cmat
def score_residuals(self, params):
"""
Returns the score residuals calculated at a given vector of
parameters.
Parameters
----------
params : ndarray
The parameter vector at which the score residuals are
calculated.
Returns
-------
The score residuals, returned as a ndarray having the same
shape as `exog`.
Notes
-----
Observations in a stratum with no observed events have undefined
score residuals, and contain NaN in the returned matrix.
"""
surv = self.surv
score_resid = np.zeros(self.exog.shape, dtype=np.float64)
# Use to set undefined values to NaN.
mask = np.zeros(self.exog.shape[0], dtype=np.int32)
w_avg = self.weighted_covariate_averages(params)
# Loop over strata
for stx in range(surv.nstrat):
uft_ix = surv.ufailt_ix[stx]
exog_s = surv.exog_s[stx]
nuft = len(uft_ix)
strat_ix = surv.stratum_rows[stx]
xp0 = 0.
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
linpred -= linpred.max()
e_linpred = np.exp(linpred)
at_risk_ix = set([])
# Iterate backward through the unique failure times.
for i in range(nuft)[::-1]:
# Update for new cases entering the risk set.
ix = surv.risk_enter[stx][i]
at_risk_ix |= set(ix)
xp0 += e_linpred[ix].sum()
atr_ix = list(at_risk_ix)
leverage = exog_s[atr_ix, :] - w_avg[stx][i, :]
# Event indicators
d = np.zeros(exog_s.shape[0])
d[uft_ix[i]] = 1
# The increment in the cumulative hazard
dchaz = len(uft_ix[i]) / xp0
# Piece of the martingale residual
mrp = d[atr_ix] - e_linpred[atr_ix] * dchaz
# Update the score residuals
ii = strat_ix[atr_ix]
score_resid[ii,:] += leverage * mrp[:, None]
mask[ii] = 1
# Update for cases leaving the risk set.
ix = surv.risk_exit[stx][i]
at_risk_ix -= set(ix)
xp0 -= e_linpred[ix].sum()
jj = np.flatnonzero(mask == 0)
if len(jj) > 0:
score_resid[jj, :] = np.nan
return score_resid
def weighted_covariate_averages(self, params):
"""
Returns the hazard-weighted average of covariate values for
subjects who are at-risk at a particular time.
Parameters
----------
params : ndarray
Parameter vector
Returns
-------
averages : list of ndarrays
averages[stx][i,:] is a row vector containing the weighted
average values (for all the covariates) of at-risk
subjects a the i^th largest observed failure time in
stratum `stx`, using the hazard multipliers as weights.
Notes
-----
Used to calculate leverages and score residuals.
"""
surv = self.surv
averages = []
xp0, xp1 = 0., 0.
# Loop over strata
for stx in range(surv.nstrat):
uft_ix = surv.ufailt_ix[stx]
exog_s = surv.exog_s[stx]
nuft = len(uft_ix)
average_s = np.zeros((len(uft_ix), exog_s.shape[1]),
dtype=np.float64)
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
linpred -= linpred.max()
e_linpred = np.exp(linpred)
# Iterate backward through the unique failure times.
for i in range(nuft)[::-1]:
# Update for new cases entering the risk set.
ix = surv.risk_enter[stx][i]
xp0 += e_linpred[ix].sum()
xp1 += np.dot(e_linpred[ix], exog_s[ix, :])
average_s[i, :] = xp1 / xp0
# Update for cases leaving the risk set.
ix = surv.risk_exit[stx][i]
xp0 -= e_linpred[ix].sum()
xp1 -= np.dot(e_linpred[ix], exog_s[ix, :])
averages.append(average_s)
return averages
def baseline_cumulative_hazard(self, params):
"""
Estimate the baseline cumulative hazard and survival
functions.
Parameters
----------
params : ndarray
The model parameters.
Returns
-------
A list of triples (time, hazard, survival) containing the time
values and corresponding cumulative hazard and survival
function values for each stratum.
Notes
-----
Uses the Nelson-Aalen estimator.
"""
# TODO: some disagreements with R, not the same algorithm but
# hard to deduce what R is doing. Our results are reasonable.
surv = self.surv
rslt = []
# Loop over strata
for stx in range(surv.nstrat):
uft = surv.ufailt[stx]
uft_ix = surv.ufailt_ix[stx]
exog_s = surv.exog_s[stx]
nuft = len(uft_ix)
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
e_linpred = np.exp(linpred)
xp0 = 0.
h0 = np.zeros(nuft, dtype=np.float64)
# Iterate backward through the unique failure times.
for i in range(nuft)[::-1]:
# Update for new cases entering the risk set.
ix = surv.risk_enter[stx][i]
xp0 += e_linpred[ix].sum()
# Account for all cases that fail at this point.
ix = uft_ix[i]
h0[i] = len(ix) / xp0
# Update for cases leaving the risk set.
ix = surv.risk_exit[stx][i]
xp0 -= e_linpred[ix].sum()
cumhaz = np.cumsum(h0) - h0
current_strata_surv = np.exp(-cumhaz)
rslt.append([uft, cumhaz, current_strata_surv])
return rslt
def baseline_cumulative_hazard_function(self, params):
"""
Returns a function that calculates the baseline cumulative
hazard function for each stratum.
Parameters
----------
params : ndarray
The model parameters.
Returns
-------
A dict mapping stratum names to the estimated baseline
cumulative hazard function.
"""
from scipy.interpolate import interp1d
surv = self.surv
base = self.baseline_cumulative_hazard(params)
cumhaz_f = {}
for stx in range(surv.nstrat):
time_h = base[stx][0]
cumhaz = base[stx][1]
time_h = np.r_[-np.inf, time_h, np.inf]
cumhaz = np.r_[cumhaz[0], cumhaz, cumhaz[-1]]
func = interp1d(time_h, cumhaz, kind='zero')
cumhaz_f[self.surv.stratum_names[stx]] = func
return cumhaz_f
def predict(self, params, exog=None, cov_params=None, endog=None,
strata=None, offset=None, pred_type="lhr"):
# docstring attached below
pred_type = pred_type.lower()
if pred_type not in ["lhr", "hr", "surv", "cumhaz"]:
msg = "Type %s not allowed for prediction" % pred_type
raise ValueError(msg)
class bunch:
predicted_values = None
standard_errors = None
ret_val = bunch()
# Don't do anything with offset here because we want to allow
# different offsets to be specified even if exog is the model
# exog.
exog_provided = True
if exog is None:
exog = self.exog
exog_provided = False
lhr = np.dot(exog, params)
if offset is not None:
lhr += offset
# Never use self.offset unless we are also using self.exog
elif self.offset is not None and not exog_provided:
lhr += self.offset
# Handle lhr and hr prediction first, since they don't make
# use of the hazard function.
if pred_type == "lhr":
ret_val.predicted_values = lhr
if cov_params is not None:
mat = np.dot(exog, cov_params)
va = (mat * exog).sum(1)
ret_val.standard_errors = np.sqrt(va)
return ret_val
hr = np.exp(lhr)
if pred_type == "hr":
ret_val.predicted_values = hr
return ret_val
# Makes sure endog is defined
if endog is None and exog_provided:
msg = "If `exog` is provided `endog` must be provided."
raise ValueError(msg)
# Use model endog if using model exog
elif endog is None and not exog_provided:
endog = self.endog
# Make sure strata is defined
if strata is None:
if exog_provided and self.surv.nstrat > 1:
raise ValueError("`strata` must be provided")
if self.strata is None:
strata = [self.surv.stratum_names[0],] * len(endog)
else:
strata = self.strata
cumhaz = np.nan * np.ones(len(endog), dtype=np.float64)
stv = np.unique(strata)
bhaz = self.baseline_cumulative_hazard_function(params)
for stx in stv:
ix = np.flatnonzero(strata == stx)
func = bhaz[stx]
cumhaz[ix] = func(endog[ix]) * hr[ix]
if pred_type == "cumhaz":
ret_val.predicted_values = cumhaz
elif pred_type == "surv":
ret_val.predicted_values = np.exp(-cumhaz)
return ret_val
predict.__doc__ = _predict_docstring % {'cov_params_doc': _predict_cov_params_docstring}
def get_distribution(self, params):
"""
Returns a scipy distribution object corresponding to the
distribution of uncensored endog (duration) values for each
case.
Parameters
----------
params : arrayh-like
The model proportional hazards model parameters.
Returns
-------
A list of objects of type scipy.stats.distributions.rv_discrete
Notes
-----
The distributions are obtained from a simple discrete estimate
of the survivor function that puts all mass on the observed
failure times wihtin a stratum.
"""
# TODO: this returns a Python list of rv_discrete objects, so
# nothing can be vectorized. It appears that rv_discrete does
# not allow vectorization.
from scipy.stats.distributions import rv_discrete
surv = self.surv
bhaz = self.baseline_cumulative_hazard(params)
# The arguments to rv_discrete_float, first obtained by
# stratum
pk, xk = [], []
for stx in range(self.surv.nstrat):
exog_s = surv.exog_s[stx]
linpred = np.dot(exog_s, params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
e_linpred = np.exp(linpred)
# The unique failure times for this stratum (the support
# of the distribution).
pts = bhaz[stx][0]
# The individual cumulative hazards for everyone in this
# stratum.
ichaz = np.outer(e_linpred, bhaz[stx][1])
# The individual survival functions.
usurv = np.exp(-ichaz)
usurv = np.concatenate((usurv, np.zeros((usurv.shape[0], 1))),
axis=1)
# The individual survival probability masses.
probs = -np.diff(usurv, 1)
pk.append(probs)
xk.append(np.outer(np.ones(probs.shape[0]), pts))
# Pad to make all strata have the same shape
mxc = max([x.shape[1] for x in xk])
for k in range(self.surv.nstrat):
if xk[k].shape[1] < mxc:
xk1 = np.zeros((xk.shape[0], mxc))
pk1 = np.zeros((pk.shape[0], mxc))
xk1[:, -mxc:] = xk
pk1[:, -mxc:] = pk
xk[k], pk[k] = xk1, pk1
xka = np.nan * np.zeros((len(self.endog), mxc), dtype=np.float64)
pka = np.ones((len(self.endog), mxc), dtype=np.float64) / mxc
for stx in range(self.surv.nstrat):
ix = self.surv.stratum_rows[stx]
xka[ix, :] = xk[stx]
pka[ix, :] = pk[stx]
dist = rv_discrete_float(xka, pka)
return dist
class PHRegResults(base.LikelihoodModelResults):
'''
Class to contain results of fitting a Cox proportional hazards
survival model.
PHregResults inherits from statsmodels.LikelihoodModelResults
Parameters
----------
See statsmodels.LikelihoodModelResults
Returns
-------
**Attributes**
model : class instance
PHreg model instance that called fit.
normalized_cov_params : array
The sampling covariance matrix of the estimates
params : array
The coefficients of the fitted model. Each coefficient is the
log hazard ratio corresponding to a 1 unit difference in a
single covariate while holding the other covariates fixed.
bse : array
The standard errors of the fitted parameters.
See Also
--------
statsmodels.LikelihoodModelResults
'''
def __init__(self, model, params, cov_params, covariance_type="naive"):
self.covariance_type = covariance_type
super(PHRegResults, self).__init__(model, params,
normalized_cov_params=cov_params)
@cache_readonly
def standard_errors(self):
"""
Returns the standard errors of the parameter estimates.
"""
return np.sqrt(np.diag(self.cov_params()))
@cache_readonly
def bse(self):
"""
Returns the standard errors of the parameter estimates.
"""
return self.standard_errors
def get_distribution(self):
"""
Returns a scipy distribution object corresponding to the
distribution of uncensored endog (duration) values for each
case.
Returns
-------
A list of objects of type scipy.stats.distributions.rv_discrete
Notes
-----
The distributions are obtained from a simple discrete estimate
of the survivor function that puts all mass on the observed
failure times wihtin a stratum.
"""
return self.model.get_distribution(self.params)
def predict(self, endog=None, exog=None, strata=None,
offset=None, transform=True, pred_type="lhr"):
# docstring attached below
return super(PHRegResults, self).predict(exog=exog,
transform=transform,
cov_params=self.cov_params(),
endog=endog,
strata=strata,
offset=offset,
pred_type=pred_type)
predict.__doc__ = _predict_docstring % {'cov_params_doc': ''}
def _group_stats(self, groups):
"""
Descriptive statistics of the groups.
"""
gsize = {}
for x in groups:
if x not in gsize:
gsize[x] = 0
gsize[x] += 1
gsize = np.asarray(gsize.values())
return gsize.min(), gsize.max(), gsize.mean()
@cache_readonly
def weighted_covariate_averages(self):
"""
The average covariate values within the at-risk set at each
event time point, weighted by hazard.
"""
return self.model.weighted_covariate_averages(self.params)
@cache_readonly
def score_residuals(self):
"""
A matrix containing the score residuals.
"""
return self.model.score_residuals(self.params)
@cache_readonly
def baseline_cumulative_hazard(self):
"""
A list (corresponding to the strata) containing the baseline
cumulative hazard function evaluated at the event points.
"""
return self.model.baseline_cumulative_hazard(self.params)
@cache_readonly
def baseline_cumulative_hazard_function(self):
"""
A list (corresponding to the strata) containing function
objects that calculate the cumulative hazard function.
"""
return self.model.baseline_cumulative_hazard_function(self.params)
@cache_readonly
def schoenfeld_residuals(self):
"""
A matrix containing the Schoenfeld residuals.
Notes
-----
Schoenfeld residuals for censored observations are set to zero.
"""
surv = self.model.surv
w_avg = self.weighted_covariate_averages
# Initialize at NaN since rows that belong to strata with no
# events have undefined residuals.
sch_resid = np.nan*np.ones(self.model.exog.shape, dtype=np.float64)
# Loop over strata
for stx in range(surv.nstrat):
uft = surv.ufailt[stx]
exog_s = surv.exog_s[stx]
time_s = surv.time_s[stx]
strat_ix = surv.stratum_rows[stx]
ii = np.searchsorted(uft, time_s)
# These subjects are censored after the last event in
# their stratum, so have empty risk sets and undefined
# residuals.
jj = np.flatnonzero(ii < len(uft))
sch_resid[strat_ix[jj], :] = exog_s[jj, :] - w_avg[stx][ii[jj], :]
jj = np.flatnonzero(self.model.status == 0)
sch_resid[jj, :] = np.nan
return sch_resid
@cache_readonly
def martingale_residuals(self):
"""
The martingale residuals.
"""
surv = self.model.surv
# Initialize at NaN since rows that belong to strata with no
# events have undefined residuals.
mart_resid = np.nan*np.ones(len(self.model.endog), dtype=np.float64)
cumhaz_f_list = self.baseline_cumulative_hazard_function
# Loop over strata
for stx in range(surv.nstrat):
cumhaz_f = cumhaz_f_list[stx]
exog_s = surv.exog_s[stx]
time_s = surv.time_s[stx]
linpred = np.dot(exog_s, self.params)
if surv.offset_s is not None:
linpred += surv.offset_s[stx]
e_linpred = np.exp(linpred)
ii = surv.stratum_rows[stx]
chaz = cumhaz_f(time_s)
mart_resid[ii] = self.model.status[ii] - e_linpred * chaz
return mart_resid
def summary(self, yname=None, xname=None, title=None, alpha=.05):
"""
Summarize the proportional hazards regression results.
Parameters
-----------
yname : string, optional
Default is `y`
xname : list of strings, optional
Default is `x#` for ## in p the number of regressors
title : string, optional
Title for the top table. If not None, then this replaces
the default title
alpha : float
significance level for the confidence intervals
Returns
-------
smry : Summary instance
this holds the summary tables and text, which can be
printed or converted to various output formats.
See Also
--------
statsmodels.iolib.summary.Summary : class to hold summary
results
"""
from statsmodels.iolib import summary2
from statsmodels.compat.collections import OrderedDict
smry = summary2.Summary()
float_format = "%8.3f"
info = OrderedDict()
info["Model:"] = "PH Reg"
if yname is None:
yname = self.model.endog_names
info["Dependent variable:"] = yname
info["Ties:"] = self.model.ties.capitalize()
info["Sample size:"] = str(self.model.surv.n_obs)
info["Num. events:"] = str(int(sum(self.model.status)))
if self.model.groups is not None:
mn, mx, avg = self._group_stats(self.model.groups)
info["Max. group size:"] = str(mx)
info["Min. group size:"] = str(mn)
info["Avg. group size:"] = str(avg)
smry.add_dict(info, align='l', float_format=float_format)
param = summary2.summary_params(self, alpha=alpha)
param = param.rename(columns={"Coef.": "log HR",
"Std.Err.": "log HR SE"})
param.insert(2, "HR", np.exp(param["log HR"]))
a = "[%.3f" % (alpha / 2)
param.loc[:, a] = np.exp(param.loc[:, a])
a = "%.3f]" % (1 - alpha / 2)
param.loc[:, a] = np.exp(param.loc[:, a])
if xname != None:
param.index = xname
smry.add_df(param, float_format=float_format)
smry.add_title(title=title, results=self)
smry.add_text("Confidence intervals are for the hazard ratios")
if self.model.groups is not None:
smry.add_text("Standard errors account for dependence within groups")
if hasattr(self, "regularized"):
smry.add_text("Standard errors do not account for the regularization")
return smry
class rv_discrete_float(object):
"""
A class representing a collection of discrete distributions.
Parameters
----------
xk : 2d array-like
The support points, should be non-decreasing within each
row.
pk : 2d array-like
The probabilities, should sum to one within each row.
Notes
-----
Each row of `xk`, and the corresponding row of `pk` describe a
discrete distribution.
`xk` and `pk` should both be two-dimensional ndarrays. Each row
of `pk` should sum to 1.
This class is used as a substitute for scipy.distributions.
rv_discrete, since that class does not allow non-integer support
points, or vectorized operations.
Only a limited number of methods are implemented here compared to
the other scipy distribution classes.
"""
def __init__(self, xk, pk):
self.xk = xk
self.pk = pk
self.cpk = np.cumsum(self.pk, axis=1)
def rvs(self):
"""
Returns a random sample from the discrete distribution.
A vector is returned containing a single draw from each row of
`xk`, using the probabilities of the corresponding row of `pk`
"""
n = self.xk.shape[0]
u = np.random.uniform(size=n)
ix = (self.cpk < u[:, None]).sum(1)
ii = np.arange(n, dtype=np.int32)
return self.xk[(ii,ix)]
def mean(self):
"""
Returns a vector containing the mean values of the discrete
distributions.
A vector is returned containing the mean value of each row of
`xk`, using the probabilities in the corresponding row of
`pk`.
"""
return (self.xk * self.pk).sum(1)
def var(self):
"""
Returns a vector containing the variances of the discrete
distributions.
A vector is returned containing the variance for each row of
`xk`, using the probabilities in the corresponding row of
`pk`.
"""
mn = self.mean()
xkc = self.xk - mn[:, None]
return (self.pk * (self.xk - xkc)**2).sum(1)
def std(self):
"""
Returns a vector containing the standard deviations of the
discrete distributions.
A vector is returned containing the standard deviation for
each row of `xk`, using the probabilities in the corresponding
row of `pk`.
"""
return np.sqrt(self.var())
def _opt_1d(funcs, start, L1_wt, tol):
"""
Optimize a L1-penalized smooth one-dimensional function of a
single variable.
Parameters
----------
funcs : tuple of functions
funcs[0] is the objective function to be minimized. funcs[1]
and funcs[2] are, respectively, the first and second
derivatives of the smooth part of funcs[0] (i.e. excluding the
L1 penalty).
start : real
A starting value for the function argument
L1_wt : non-negative real
The weight for the L1 penalty function.
tol : non-negative real
A convergence threshold.
Returns
-------
The argmin of the objective function.
"""
# TODO: can we detect failures without calling funcs[0] twice?
x = start
f = funcs[0](x)
b = funcs[1](x)
c = funcs[2](x)
d = b - c*x
if L1_wt > np.abs(d):
return 0.
elif d >= 0:
x += (L1_wt - b) / c
elif d < 0:
x -= (L1_wt + b) / c
f1 = funcs[0](x)
# This is an expensive fall-back if the quadratic
# approximation is poor and sends us far off-course.
if f1 > f + 1e-10:
return brent(funcs[0], brack=(x-0.2, x+0.2), tol=tol)
return x
|
ashray/VTK-EVM | refs/heads/yiq | ThirdParty/Twisted/twisted/names/test/__init__.py | 139 | "Tests for twisted.names"
|
jesseklein406/data-structures | refs/heads/master | tests/test_stack.py | 2 | # -*- coding: utf-8 -*-
"""Test file for 'stack.py'
Run this file with pytest to test conditions
"""
from __future__ import unicode_literals
import pytest
import stack
value = [1, 2, 3, 4, 5]
foo = stack.Stack(value)
# init
def test_init_type():
"""Check instance is type 'stack'"""
assert type(foo) == stack.Stack
def test_init_push():
"""Check 'push' in dir(foo)"""
assert 'push' in dir(foo)
def test_init_pop():
"""Check 'pop' in dir(foo)"""
assert 'pop' in dir(foo)
def test_init_insert():
"""Check 'insert' is not in dir(foo)"""
assert 'insert' not in dir(foo)
def test_init_size():
"""Check 'size' is not in dir(foo)"""
assert 'size' not in dir(foo)
def test_init_search():
"""Check 'search' is not in dir(foo)"""
assert 'search' not in dir(foo)
def test_init_remove():
"""Check 'remove' is not in dir(foo)"""
assert 'remove' not in dir(foo)
def test_init_display():
"""Check 'display' is not in dir(foo)"""
assert 'display' not in dir(foo)
# pop
bar = foo.pop()
def test_pop_value():
"""Check bar = 5"""
assert bar == 5
empty = stack.Stack([])
def test_pop_empty():
"""Assert empty.pop() raises Exception"""
with pytest.raises(AttributeError):
nothing = empty.pop()
# push
foo.push(bar)
def test_push_restore():
"""Check foo.pop() = 5"""
assert foo.pop() == 5
|
tristandeleu/switching-kalman-filter | refs/heads/master | test/test_switching_kalman_filter.py | 1 | import csv, time
import numpy as np
from utils.kalman import SwitchingKalmanState, SwitchingKalmanFilter, KalmanState
from utils.kalman.models import NDCWPA, NDBrownian
from utils.helpers import *
import matplotlib.pyplot as plt
# positions = load_trajectory(1080, 100)
# positions = load_trajectory(1462, 79)
positions = load_trajectory(3331, 100)
# positions = load_random_trajectory()
n = positions.shape[0]
models = [
NDCWPA(dt=1.0, q=2e-1, r=10.0, n_dim=2),
NDBrownian(dt=1.0, q=2e-1, r=10.0, n_dim=2)
]
Z = np.log(np.asarray([
[0.99, 0.01],
[0.01, 0.99]
]))
masks = [
np.asarray([
np.diag([1, 0, 1, 0, 1, 0]),
np.diag([0, 1, 0, 1, 0, 1])
]),
np.asarray([
np.diag([1, 0]),
np.diag([0, 1])
])
]
T = np.asarray([
[1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0]
])
embeds = [
[np.eye(6), T],
[T.T, np.eye(2)]
]
kalman = SwitchingKalmanFilter(models=models, log_transmat=Z, masks=masks, embeds=embeds)
start_time = time.time()
# Kalman Filter
state = SwitchingKalmanState(n_models=2)
state._states[0] = KalmanState(mean=np.zeros(6), covariance=10.0 * np.eye(6))
state._states[1] = KalmanState(mean=np.zeros(2), covariance=10.0 * np.eye(2))
state.M = np.ones(2) / 2.0
filtered_states = [state] * n
for i in xrange(n):
observation = positions[i]
state = kalman.filter(state, observation)
filtered_states[i] = state
smoothed_states = [state] * n
for i in xrange(1, n):
j = n - 1 - i
state = kalman.smoother(state, filtered_states[j])
smoothed_states[j] = state
print '---- %.3f seconds ----' % (time.time() - start_time,)
# output_states = filtered_states
output_states = smoothed_states
embeds_f = [np.eye(6), T.T]
smoothed_collapsed = map(lambda state: state.collapse(embeds_f), output_states)
smoothed = np.asarray(map(lambda state: state.m, smoothed_collapsed))
stops = np.asarray(map(lambda state: np.exp(state.M[1]), output_states))
subplot_shape = (2,2)
plt.subplot2grid(subplot_shape, (0,0), rowspan=2)
plt.plot(positions[:,0], positions[:,1], 'b-')
plt.plot(smoothed[:,0], smoothed[:,1], 'g-')
plt.plot(smoothed[stops>0.50,0], smoothed[stops>0.50,1], 'ro')
plt.subplot2grid(subplot_shape, (0,1))
plt.plot(range(n), stops)
plt.plot(range(n), 0.5 * np.ones(n), 'r--')
plt.subplot2grid(subplot_shape, (1,1))
velocity = np.asarray(map(lambda state: state.m[2:4], smoothed_collapsed))
plt.plot(range(n), map(lambda v: 3.6 * np.linalg.norm(v), velocity))
# for state in output_states:
# # print state._states[1].P[0:2,0:2]
# # print np.linalg.det(state.collapse(embeds_f).P)
# print state.collapse(embeds_f).P[0:2,0:2]
plt.show() |
BlindHunter/django | refs/heads/master | tests/utils_tests/test_crypto.py | 447 | from __future__ import unicode_literals
import binascii
import hashlib
import unittest
from django.utils.crypto import constant_time_compare, pbkdf2
class TestUtilsCryptoMisc(unittest.TestCase):
def test_constant_time_compare(self):
# It's hard to test for constant time, just test the result.
self.assertTrue(constant_time_compare(b'spam', b'spam'))
self.assertFalse(constant_time_compare(b'spam', b'eggs'))
self.assertTrue(constant_time_compare('spam', 'spam'))
self.assertFalse(constant_time_compare('spam', 'eggs'))
class TestUtilsCryptoPBKDF2(unittest.TestCase):
# http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06
rfc_vectors = [
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 1,
"dklen": 20,
"digest": hashlib.sha1,
},
"result": "0c60c80f961f0e71f3a9b524af6012062fe037a6",
},
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 2,
"dklen": 20,
"digest": hashlib.sha1,
},
"result": "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957",
},
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 4096,
"dklen": 20,
"digest": hashlib.sha1,
},
"result": "4b007901b765489abead49d926f721d065a429c1",
},
# # this takes way too long :(
# {
# "args": {
# "password": "password",
# "salt": "salt",
# "iterations": 16777216,
# "dklen": 20,
# "digest": hashlib.sha1,
# },
# "result": "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984",
# },
{
"args": {
"password": "passwordPASSWORDpassword",
"salt": "saltSALTsaltSALTsaltSALTsaltSALTsalt",
"iterations": 4096,
"dklen": 25,
"digest": hashlib.sha1,
},
"result": "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038",
},
{
"args": {
"password": "pass\0word",
"salt": "sa\0lt",
"iterations": 4096,
"dklen": 16,
"digest": hashlib.sha1,
},
"result": "56fa6aa75548099dcc37d7f03425e0c3",
},
]
regression_vectors = [
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 1,
"dklen": 20,
"digest": hashlib.sha256,
},
"result": "120fb6cffcf8b32c43e7225256c4f837a86548c9",
},
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 1,
"dklen": 20,
"digest": hashlib.sha512,
},
"result": "867f70cf1ade02cff3752599a3a53dc4af34c7a6",
},
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 1000,
"dklen": 0,
"digest": hashlib.sha512,
},
"result": ("afe6c5530785b6cc6b1c6453384731bd5ee432ee"
"549fd42fb6695779ad8a1c5bf59de69c48f774ef"
"c4007d5298f9033c0241d5ab69305e7b64eceeb8d"
"834cfec"),
},
# Check leading zeros are not stripped (#17481)
{
"args": {
"password": b'\xba',
"salt": "salt",
"iterations": 1,
"dklen": 20,
"digest": hashlib.sha1,
},
"result": '0053d3b91a7f1e54effebd6d68771e8a6e0b2c5b',
},
]
def test_public_vectors(self):
for vector in self.rfc_vectors:
result = pbkdf2(**vector['args'])
self.assertEqual(binascii.hexlify(result).decode('ascii'),
vector['result'])
def test_regression_vectors(self):
for vector in self.regression_vectors:
result = pbkdf2(**vector['args'])
self.assertEqual(binascii.hexlify(result).decode('ascii'),
vector['result'])
|
sparkslabs/kamaelia_ | refs/heads/master | Sketches/JL/IRC/guitest.py | 3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# 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 string
from Axon.Component import component
defaultChannel = '#kamtest'
def informat(text):
if text[0] != '/' or text.split()[0] == '/': #in case we were passed "/ word words", or simply "/"
return ('PRIVMSG', defaultChannel, text)
words = text.split()
tag = words[0]
tag = tag.lstrip('/').upper()
if tag == 'MSG':
tag = 'PRIVMSG'
try:
if tag == 'QUIT' and len(words) >= 2:
return (tag, string.join(words[1:]))
elif tag in ('PRIVMSG', 'MSG', 'NOTICE', 'KILL', 'TOPIC', 'SQUERY') and len(words) >= 3:
return (tag, words[1], string.join(words[2:]))
elif tag == 'KICK' and len(words) >= 4:
return (tag, words[1], words[2], string.join(words[3:]))
elif tag == 'USER':
return (tag, words[1], words[2], words[3], string.join(words[4:]))
elif tag == 'ME' and len(words) >= 2:
return (tag, defaultChannel, string.join(words[1:]))
else:
words[0] = tag
if tag: #only false if we were passed "/" as text
return words
except IndexError:
words[0] = tag
return words
def outformat(data):
msgtype, sender, recipient, body = data
end = '\n'
if msgtype == 'PRIVMSG':
if body[0:5] == '[off]': #we don't want to log lines prefixed by "[off]"
return
text = '<%s> %s' % (sender, body)
elif msgtype == 'JOIN' :
text = '*** %s has joined %s' % (sender, recipient)
elif msgtype == 'PART' :
text = '*** %s has parted %s' % (sender, recipient)
elif msgtype == 'NICK':
text = '*** %s is now known as %s' % (sender, recipient)
elif msgtype == 'ACTION':
text = '*** %s %s' % (sender, body)
elif msgtype == 'TOPIC':
text = '*** %s changed the topic to %s' % (sender, body)
elif msgtype == 'QUIT': #test this, channel to outbox, not system
text = '*** %s has quit IRC' % (sender)
elif msgtype == 'MODE' and recipient == defaultChannel:
text = '*** %s has set channel mode: %s' % (sender, body)
elif msgtype > '000' and msgtype < '400':
text = 'Reply %s from %s to %s: %s' % data
elif msgtype >= '400' and msgtype < '600':
text = 'Error! %s %s %s %s' % data
elif msgtype >= '600' and msgtype < '1000':
text = 'Unknown numeric reply: %s %s %s %s' % data
else:
text = '%s from %s: %s' % (msgtype, sender, body)
return text + end
if __name__ == '__main__':
from Kamaelia.Util.Console import ConsoleEchoer
from Kamaelia.Chassis.Pipeline import Pipeline
from Kamaelia.Chassis.Graphline import Graphline
from Kamaelia.Internet.TCPClient import TCPClient
from Kamaelia.Util.PureTransformer import PureTransformer
from Axon.Ipc import producerFinished
from IRCClient import IRC_Client
from Textbox import Textbox
from TextDisplayer import TextDisplayer
#to connect to IRC, you need to type "/nick yournickname" followed by "/user arg1 arg2 arg3 arg4"
#very fast, before the connection times out.
testfile = '/home/jlei/files/InputFormatter_test.txt'
class LineFileReader(component):
def main(self):
fle = open(testfile, "r")
data = "dummy"
while data:
yield 1
data = fle.readline()
if data and data != '\n':
self.send(data.rstrip('\n'))
self.send(producerFinished(), "signal")
g = Graphline(irc = IRC_Client(),
tcp = TCPClient('irc.freenode.net', 6667),
linkages = {("self", "inbox") : ("irc" , "talk"),
("irc", "outbox") : ("tcp" , "inbox"),
("tcp", "outbox") : ("irc", "inbox"),
("irc", "heard") : ("self", "outbox"),
}
)
Pipeline(Textbox(position=(0,340)), PureTransformer(informat), g, PureTransformer(outformat),
TextDisplayer()
).run()
|
BigDataTrade/AlgorithmicTradingApiPython | refs/heads/master | setup.py | 2 | from setuptools import setup
setup(name='BigDataTradeAPIPy',
version='0.0.2',
description='BigDataTrade API in python',
url='https://github.com/bigdatatrade/AlgorithmicTradingApiPython',
author='Nacass Tommy',
author_email='tommy.nacass@gmail.com',
license='MIT',
packages=['bigdatatrade'],
zip_safe=False)
|
kkintaro/termite-data-server | refs/heads/master | web2py/gluon/storage.py | 16 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework
Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
Provides:
- List; like list but returns None instead of IndexOutOfBounds
- Storage; like dictionary allowing also for `obj.foo` for `obj['foo']`
"""
import cPickle
import gluon.portalocker as portalocker
__all__ = ['List', 'Storage', 'Settings', 'Messages',
'StorageList', 'load_storage', 'save_storage']
DEFAULT = lambda:0
class Storage(dict):
"""
A Storage object is like a dictionary except `obj.foo` can be used
in addition to `obj['foo']`, and setting obj.foo = None deletes item foo.
>>> o = Storage(a=1)
>>> print o.a
1
>>> o['a']
1
>>> o.a = 2
>>> print o['a']
2
>>> del o.a
>>> print o.a
None
"""
__slots__ = ()
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
__getitem__ = dict.get
__getattr__ = dict.get
__repr__ = lambda self: '<Storage %s>' % dict.__repr__(self)
# http://stackoverflow.com/questions/5247250/why-does-pickle-getstate-accept-as-a-return-value-the-very-instance-it-requi
__getstate__ = lambda self: None
__copy__ = lambda self: Storage(self)
def getlist(self, key):
"""
Return a Storage value as a list.
If the value is a list it will be returned as-is.
If object is None, an empty list will be returned.
Otherwise, [value] will be returned.
Example output for a query string of ?x=abc&y=abc&y=def
>>> request = Storage()
>>> request.vars = Storage()
>>> request.vars.x = 'abc'
>>> request.vars.y = ['abc', 'def']
>>> request.vars.getlist('x')
['abc']
>>> request.vars.getlist('y')
['abc', 'def']
>>> request.vars.getlist('z')
[]
"""
value = self.get(key, [])
if value is None or isinstance(value, (list, tuple)):
return value
else:
return [value]
def getfirst(self, key, default=None):
"""
Return the first or only value when given a request.vars-style key.
If the value is a list, its first item will be returned;
otherwise, the value will be returned as-is.
Example output for a query string of ?x=abc&y=abc&y=def
>>> request = Storage()
>>> request.vars = Storage()
>>> request.vars.x = 'abc'
>>> request.vars.y = ['abc', 'def']
>>> request.vars.getfirst('x')
'abc'
>>> request.vars.getfirst('y')
'abc'
>>> request.vars.getfirst('z')
"""
values = self.getlist(key)
return values[0] if values else default
def getlast(self, key, default=None):
"""
Returns the last or only single value when
given a request.vars-style key.
If the value is a list, the last item will be returned;
otherwise, the value will be returned as-is.
Simulated output with a query string of ?x=abc&y=abc&y=def
>>> request = Storage()
>>> request.vars = Storage()
>>> request.vars.x = 'abc'
>>> request.vars.y = ['abc', 'def']
>>> request.vars.getlast('x')
'abc'
>>> request.vars.getlast('y')
'def'
>>> request.vars.getlast('z')
"""
values = self.getlist(key)
return values[-1] if values else default
PICKABLE = (str, int, long, float, bool, list, dict, tuple, set)
class StorageList(Storage):
"""
like Storage but missing elements default to [] instead of None
"""
def __getitem__(self, key):
return self.__getattr__(key)
def __getattr__(self, key):
if key in self:
return getattr(self, key)
else:
r = []
setattr(self, key, r)
return r
def load_storage(filename):
fp = None
try:
fp = portalocker.LockedFile(filename, 'rb')
storage = cPickle.load(fp)
finally:
if fp:
fp.close()
return Storage(storage)
def save_storage(storage, filename):
fp = None
try:
fp = portalocker.LockedFile(filename, 'wb')
cPickle.dump(dict(storage), fp)
finally:
if fp:
fp.close()
class Settings(Storage):
def __setattr__(self, key, value):
if key != 'lock_keys' and self['lock_keys'] and key not in self:
raise SyntaxError('setting key \'%s\' does not exist' % key)
if key != 'lock_values' and self['lock_values']:
raise SyntaxError('setting value cannot be changed: %s' % key)
self[key] = value
class Messages(Settings):
def __init__(self, T):
Storage.__init__(self, T=T)
def __getattr__(self, key):
value = self[key]
if isinstance(value, str):
return str(self.T(value))
return value
class FastStorage(dict):
"""
Eventually this should replace class Storage but causes memory leak
because of http://bugs.python.org/issue1469629
>>> s = FastStorage()
>>> s.a = 1
>>> s.a
1
>>> s['a']
1
>>> s.b
>>> s['b']
>>> s['b']=2
>>> s['b']
2
>>> s.b
2
>>> isinstance(s,dict)
True
>>> dict(s)
{'a': 1, 'b': 2}
>>> dict(FastStorage(s))
{'a': 1, 'b': 2}
>>> import pickle
>>> s = pickle.loads(pickle.dumps(s))
>>> dict(s)
{'a': 1, 'b': 2}
>>> del s.b
>>> del s.a
>>> s.a
>>> s.b
>>> s['a']
>>> s['b']
"""
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
def __getattr__(self, key):
return getattr(self, key) if key in self else None
def __getitem__(self, key):
return dict.get(self, key, None)
def copy(self):
self.__dict__ = {}
s = FastStorage(self)
self.__dict__ = self
return s
def __repr__(self):
return '<Storage %s>' % dict.__repr__(self)
def __getstate__(self):
return dict(self)
def __setstate__(self, sdict):
dict.__init__(self, sdict)
self.__dict__ = self
def update(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
class List(list):
"""
Like a regular python list but a[i] if i is out of bounds return None
instead of IndexOutOfBounds
"""
def __call__(self, i, default=DEFAULT, cast=None, otherwise=None):
"""
request.args(0,default=0,cast=int,otherwise='http://error_url')
request.args(0,default=0,cast=int,otherwise=lambda:...)
"""
n = len(self)
if 0 <= i < n or -n <= i < 0:
value = self[i]
elif default is DEFAULT:
value = None
else:
value, cast = default, False
if cast:
try:
value = cast(value)
except (ValueError, TypeError):
from http import HTTP, redirect
if otherwise is None:
raise HTTP(404)
elif isinstance(otherwise, str):
redirect(otherwise)
elif callable(otherwise):
return otherwise()
else:
raise RuntimeError("invalid otherwise")
return value
if __name__ == '__main__':
import doctest
doctest.testmod()
|
ssbarnea/ansible | refs/heads/devel | test/units/ansible_test/ci/test_shippable.py | 27 | from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from .util import common_auth_test
def test_auth():
# noinspection PyProtectedMember
from ansible_test._internal.ci.shippable import (
ShippableAuthHelper,
)
class TestShippableAuthHelper(ShippableAuthHelper):
def __init__(self):
self.public_key_pem = None
self.private_key_pem = None
def publish_public_key(self, public_key_pem):
# avoid publishing key
self.public_key_pem = public_key_pem
def initialize_private_key(self):
# cache in memory instead of on disk
if not self.private_key_pem:
self.private_key_pem = self.generate_private_key()
return self.private_key_pem
auth = TestShippableAuthHelper()
common_auth_test(auth)
|
suranap/qiime | refs/heads/master | tests/test_make_otu_heatmap.py | 15 | #!/usr/bin/env python
# file test_make_otu_heatmap.py
__author__ = "Dan Knights"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Dan Knights"]
__license__ = "GPL"
__version__ = "1.9.1-dev"
__maintainer__ = "Dan Knights"
__email__ = "daniel.knights@colorado.edu"
from os import close
from os.path import exists
from tempfile import mkstemp
from numpy import array, log10, asarray, float64, argwhere
from unittest import TestCase, main
from numpy.testing import assert_almost_equal
from skbio.util import remove_files
from qiime.make_otu_heatmap import (extract_metadata_column,
get_order_from_categories, get_order_from_tree, make_otu_labels,
names_to_indices, get_log_transform, get_clusters,
get_fontsize, plot_heatmap)
from biom.table import Table
class TopLevelTests(TestCase):
"""Tests of top-level functions"""
def setUp(self):
"""define some top-level data"""
self.otu_table_values = array([[0, 0, 9, 5, 3, 1],
[1, 5, 4, 0, 3, 2],
[2, 3, 1, 1, 2, 5]])
{(0, 2): 9.0, (0, 3): 5.0, (0, 4): 3.0, (0, 5): 1.0,
(1, 0): 1.0, (1, 1): 5.0, (1, 2): 4.0, (1, 4): 3.0, (1, 5): 2.0,
(2, 0): 2.0, (2, 1): 3.0, (2, 2): 1.0, (2, 3): 1.0, (2, 4): 2.0, (2, 5): 5.0}
self.otu_table = Table(self.otu_table_values,
['OTU1', 'OTU2', 'OTU3'],
['Sample1', 'Sample2', 'Sample3',
'Sample4', 'Sample5', 'Sample6'],
[{"taxonomy": ['Bacteria']},
{"taxonomy": ['Archaea']},
{"taxonomy": ['Streptococcus']}],
[None, None, None, None, None, None])
self.otu_table_f = Table(self.otu_table_values,
['OTU1', 'OTU2', 'OTU3'],
['Sample1', 'Sample2', 'Sample3',
'Sample4', 'Sample5', 'Sample6'],
[{"taxonomy": ['1A', '1B', '1C', 'Bacteria']},
{"taxonomy":
['2A', '2B', '2C', 'Archaea']},
{"taxonomy": ['3A', '3B', '3C', 'Streptococcus']}],
[None, None, None, None, None, None])
self.full_lineages = [['1A', '1B', '1C', 'Bacteria'],
['2A', '2B', '2C', 'Archaea'],
['3A', '3B', '3C', 'Streptococcus']]
self.metadata = [[['Sample1', 'NA', 'A'],
['Sample2', 'NA', 'B'],
['Sample3', 'NA', 'A'],
['Sample4', 'NA', 'B'],
['Sample5', 'NA', 'A'],
['Sample6', 'NA', 'B']],
['SampleID', 'CAT1', 'CAT2'], []]
self.tree_text = ["('OTU3',('OTU1','OTU2'))"]
fh, self.tmp_heatmap_fpath = mkstemp(prefix='test_heatmap_',
suffix='.pdf')
close(fh)
def test_extract_metadata_column(self):
"""Extracts correct column from mapping file"""
obs = extract_metadata_column(self.otu_table.ids(),
self.metadata, category='CAT2')
exp = ['A', 'B', 'A', 'B', 'A', 'B']
self.assertEqual(obs, exp)
def test_get_order_from_categories(self):
"""Sample indices should be clustered within each category"""
category_labels = ['A', 'B', 'A', 'B', 'A', 'B']
obs = get_order_from_categories(self.otu_table, category_labels)
group_string = "".join([category_labels[i] for i in obs])
self.assertTrue("AAABBB" == group_string or group_string == "BBBAAA")
def test_get_order_from_tree(self):
obs = get_order_from_tree(
self.otu_table.ids(axis='observation'),
self.tree_text)
exp = [2, 0, 1]
assert_almost_equal(obs, exp)
def test_make_otu_labels(self):
lineages = []
for val, id, meta in self.otu_table.iter(axis='observation'):
lineages.append([v for v in meta['taxonomy']])
obs = make_otu_labels(self.otu_table.ids(axis='observation'),
lineages, n_levels=1)
exp = ['Bacteria (OTU1)', 'Archaea (OTU2)', 'Streptococcus (OTU3)']
self.assertEqual(obs, exp)
full_lineages = []
for val, id, meta in self.otu_table_f.iter(axis='observation'):
full_lineages.append([v for v in meta['taxonomy']])
obs = make_otu_labels(self.otu_table_f.ids(axis='observation'),
full_lineages, n_levels=3)
exp = ['1B;1C;Bacteria (OTU1)',
'2B;2C;Archaea (OTU2)',
'3B;3C;Streptococcus (OTU3)']
self.assertEqual(obs, exp)
def test_names_to_indices(self):
new_order = ['Sample4', 'Sample2', 'Sample3',
'Sample6', 'Sample5', 'Sample1']
obs = names_to_indices(self.otu_table.ids(), new_order)
exp = [3, 1, 2, 5, 4, 0]
assert_almost_equal(obs, exp)
def test_get_log_transform(self):
obs = get_log_transform(self.otu_table)
data = [val for val in self.otu_table.iter_data(axis='observation')]
xform = asarray(data, dtype=float64)
for (i, val) in enumerate(obs.iter_data(axis='observation')):
non_zeros = argwhere(xform[i] != 0)
xform[i, non_zeros] = log10(xform[i, non_zeros])
assert_almost_equal(val, xform[i])
def test_get_clusters(self):
data = asarray([val for val in self.otu_table.iter_data(axis='observation')])
obs = get_clusters(data, axis='row')
self.assertTrue([0, 1, 2] == obs or obs == [1, 2, 0])
obs = get_clusters(data, axis='column')
exp = [2, 3, 1, 4, 0, 5]
self.assertEqual(obs, exp)
def test_plot_heatmap(self):
plot_heatmap(
self.otu_table, self.otu_table.ids(axis='observation'),
self.otu_table.ids(), self.tmp_heatmap_fpath)
self.assertEqual(exists(self.tmp_heatmap_fpath), True)
remove_files(set([self.tmp_heatmap_fpath]))
# run tests if called from command line
if __name__ == "__main__":
main()
|
janusnic/cookiecutter | refs/heads/master | tests/test_generate_copy_without_render.py | 25 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_generate_copy_without_render
---------------------------------
"""
from __future__ import unicode_literals
import os
import pytest
from cookiecutter import generate
from cookiecutter import utils
@pytest.fixture(scope='function')
def remove_test_dir(request):
"""
Remove the folder that is created by the test.
"""
def fin_remove_test_dir():
if os.path.exists('test_copy_without_render'):
utils.rmtree('test_copy_without_render')
request.addfinalizer(fin_remove_test_dir)
@pytest.mark.usefixtures('clean_system', 'remove_test_dir')
def test_generate_copy_without_render_extensions():
generate.generate_files(
context={
'cookiecutter': {
'repo_name': 'test_copy_without_render',
'render_test': 'I have been rendered!',
'_copy_without_render': [
'*not-rendered',
'rendered/not_rendered.yml',
'*.txt',
]}
},
repo_dir='tests/test-generate-copy-without-render'
)
dir_contents = os.listdir('test_copy_without_render')
assert '{{cookiecutter.repo_name}}-not-rendered' in dir_contents
assert 'test_copy_without_render-rendered' in dir_contents
with open('test_copy_without_render/README.txt') as f:
assert '{{cookiecutter.render_test}}' in f.read()
with open('test_copy_without_render/README.rst') as f:
assert 'I have been rendered!' in f.read()
with open('test_copy_without_render/'
'test_copy_without_render-rendered/'
'README.txt') as f:
assert '{{cookiecutter.render_test}}' in f.read()
with open('test_copy_without_render/'
'test_copy_without_render-rendered/'
'README.rst') as f:
assert 'I have been rendered' in f.read()
with open('test_copy_without_render/'
'{{cookiecutter.repo_name}}-not-rendered/'
'README.rst') as f:
assert '{{cookiecutter.render_test}}' in f.read()
with open('test_copy_without_render/rendered/not_rendered.yml') as f:
assert '{{cookiecutter.render_test}}' in f.read()
|
nasa/CrisisMappingToolkit | refs/heads/master | bin/detect_flood_modis.py | 1 | # -----------------------------------------------------------------------------
# Copyright * 2014, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The Crisis Mapping Toolkit (CMT) v1 platform is 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 logging
logging.basicConfig(level=logging.ERROR)
try:
import cmt.ee_authenticate
except:
import sys
import os.path
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
import cmt.ee_authenticate
import matplotlib
# matplotlib.use('tkagg')
import sys
import os
import ee
import functools
import threading
import cmt.domain
from cmt.modis.flood_algorithms import *
from cmt.mapclient_qt import centerMap, addToMap
import cmt.util.evaluation
import cmt.util.gui_util
'''
Tool for testing MODIS based flood detection algorithms using a simple GUI.
'''
# --------------------------------------------------------------
# Configuration
# Specify each algorithm to be concurrently run on the data set - see /modis/flood_algorithms.py
# ALGORITHMS = [DARTMOUTH, DART_LEARNED, DIFFERENCE, DIFF_LEARNED, FAI, FAI_LEARNED, EVI, XIAO, SVM, RANDOM_FORESTS, CART, DNNS, DNNS_DEM]
# ALGORITHMS = [DART_LEARNED, DIFF_LEARNED, FAI_LEARNED, MODNDWI_LEARNED, EVI, XIAO, MARTINIS_TREE, SVM, RANDOM_FORESTS, CART, DNNS, DNNS_DEM, ADABOOST, ADABOOST_DEM]
# ALGORITHMS = [DNNS, DNNS_DEM]
# ALGORITHMS = [SVM, RANDOM_FORESTS, CART]
# ALGORITHMS = [ADABOOST, ADABOOST_DEM]
# ALGORITHMS = [ACTIVE_CONTOUR]
#ALGORITHMS = [DART_LEARNED, EVI, XIAO, MARTINIS_TREE, CART, ADABOOST, ADABOOST_DEM]
ALGORITHMS = [DIFFERENCE, EVI, XIAO, ADABOOST]
#ALGORITHMS = []
# --------------------------------------------------------------
# Functions
def evaluation_function(pair, alg):
'''Pretty print an algorithm and its statistics'''
(precision, recall, evalRes, noTruth) = pair
print '%s: (%4g, %4g, %4g)' % (get_algorithm_name(alg), precision, recall, noTruth)
# --------------------------------------------------------------
def main():
# Get the domain XML file from the command line arguments
if len(sys.argv) < 2:
print 'Usage: detect_flood_modis.py domain.xml'
sys.exit(0)
cmt.ee_authenticate.initialize()
# Fetch data set information
domain = cmt.domain.Domain()
domain.load_xml(sys.argv[1])
# Display the Landsat and MODIS data for the data set
cmt.util.gui_util.visualizeDomain(domain)
#
# import cmt.modis.adaboost
# cmt.modis.adaboost.adaboost_learn() # Adaboost training
# #cmt.modis.adaboost.adaboost_dem_learn(None) # Adaboost DEM stats collection
# raise Exception('DEBUG')
waterMask = ee.Image("MODIS/MOD44W/MOD44W_005_2000_02_24").select(['water_mask'], ['b1'])
addToMap(waterMask.mask(waterMask), {'min': 0, 'max': 1}, 'Permanent Water Mask', False)
# For each of the algorithms
for a in range(len(ALGORITHMS)):
# Run the algorithm on the data and get the results
try:
(alg, result) = detect_flood(domain, ALGORITHMS[a])
if result is None:
continue
# These lines are needed for certain data sets which EE is not properly masking!!!
# result = result.mask(domain.skybox_nir.image.reduce(ee.Reducer.allNonZero()))
# result = result.mask(domain.skybox.image.reduce(ee.Reducer.allNonZero()))
# Get a color pre-associated with the algorithm, then draw it on the map
color = get_algorithm_color(ALGORITHMS[a])
addToMap(result.mask(result), {'min': 0, 'max': 1, 'opacity': 0.5, 'palette': '000000, ' + color},
alg, False)
# Compare the algorithm output to the ground truth and print the results
if domain.ground_truth:
cmt.util.evaluation.evaluate_approach_thread(functools.partial(
evaluation_function, alg=ALGORITHMS[a]), result, domain.ground_truth, domain.bounds,
is_algorithm_fractional(ALGORITHMS[a]))
except Exception, e:
print('Caught exception running algorithm: ' + get_algorithm_name(ALGORITHMS[a]) + '\n' +
str(e) + '\n')
# This code needs to be outside the main function for OSX!
t = threading.Thread(target=main)
t.start()
cmt.mapclient_qt.run()
|
paulmadore/Eric-IDE | refs/heads/master | 6-6.0.9/eric/Plugins/VcsPlugins/vcsMercurial/HgCommandDialog.py | 2 | # -*- coding: utf-8 -*-
# Copyright (c) 2010 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing the Mercurial command dialog.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog, QDialogButtonBox
from .Ui_HgCommandDialog import Ui_HgCommandDialog
import Utilities
class HgCommandDialog(QDialog, Ui_HgCommandDialog):
"""
Class implementing the Mercurial command dialog.
It implements a dialog that is used to enter an
arbitrary Mercurial command. It asks the user to enter
the commandline parameters.
"""
def __init__(self, argvList, ppath, parent=None):
"""
Constructor
@param argvList history list of commandline arguments (list of strings)
@param ppath pathname of the project directory (string)
@param parent parent widget of this dialog (QWidget)
"""
super(HgCommandDialog, self).__init__(parent)
self.setupUi(self)
self.okButton = self.buttonBox.button(QDialogButtonBox.Ok)
self.okButton.setEnabled(False)
self.commandCombo.clear()
self.commandCombo.addItems(argvList)
if len(argvList) > 0:
self.commandCombo.setCurrentIndex(0)
self.projectDirLabel.setText(ppath)
# modify some what's this help texts
t = self.commandCombo.whatsThis()
if t:
t += Utilities.getPercentReplacementHelp()
self.commandCombo.setWhatsThis(t)
msh = self.minimumSizeHint()
self.resize(max(self.width(), msh.width()), msh.height())
@pyqtSlot(str)
def on_commandCombo_editTextChanged(self, text):
"""
Private method used to enable/disable the OK-button.
@param text ignored
"""
self.okButton.setDisabled(self.commandCombo.currentText() == "")
def getData(self):
"""
Public method to retrieve the data entered into this dialog.
@return commandline parameters (string)
"""
return self.commandCombo.currentText()
|
DanielG/gr-osmosdr | refs/heads/master | docs/doxygen/doxyxml/generated/compound.py | 344 | #!/usr/bin/env python
"""
Generated Mon Feb 9 19:08:05 2009 by generateDS.py.
"""
from string import lower as str_lower
from xml.dom import minidom
from xml.dom import Node
import sys
import compoundsuper as supermod
from compoundsuper import MixedContainer
class DoxygenTypeSub(supermod.DoxygenType):
def __init__(self, version=None, compounddef=None):
supermod.DoxygenType.__init__(self, version, compounddef)
def find(self, details):
return self.compounddef.find(details)
supermod.DoxygenType.subclass = DoxygenTypeSub
# end class DoxygenTypeSub
class compounddefTypeSub(supermod.compounddefType):
def __init__(self, kind=None, prot=None, id=None, compoundname='', title='', basecompoundref=None, derivedcompoundref=None, includes=None, includedby=None, incdepgraph=None, invincdepgraph=None, innerdir=None, innerfile=None, innerclass=None, innernamespace=None, innerpage=None, innergroup=None, templateparamlist=None, sectiondef=None, briefdescription=None, detaileddescription=None, inheritancegraph=None, collaborationgraph=None, programlisting=None, location=None, listofallmembers=None):
supermod.compounddefType.__init__(self, kind, prot, id, compoundname, title, basecompoundref, derivedcompoundref, includes, includedby, incdepgraph, invincdepgraph, innerdir, innerfile, innerclass, innernamespace, innerpage, innergroup, templateparamlist, sectiondef, briefdescription, detaileddescription, inheritancegraph, collaborationgraph, programlisting, location, listofallmembers)
def find(self, details):
if self.id == details.refid:
return self
for sectiondef in self.sectiondef:
result = sectiondef.find(details)
if result:
return result
supermod.compounddefType.subclass = compounddefTypeSub
# end class compounddefTypeSub
class listofallmembersTypeSub(supermod.listofallmembersType):
def __init__(self, member=None):
supermod.listofallmembersType.__init__(self, member)
supermod.listofallmembersType.subclass = listofallmembersTypeSub
# end class listofallmembersTypeSub
class memberRefTypeSub(supermod.memberRefType):
def __init__(self, virt=None, prot=None, refid=None, ambiguityscope=None, scope='', name=''):
supermod.memberRefType.__init__(self, virt, prot, refid, ambiguityscope, scope, name)
supermod.memberRefType.subclass = memberRefTypeSub
# end class memberRefTypeSub
class compoundRefTypeSub(supermod.compoundRefType):
def __init__(self, virt=None, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None):
supermod.compoundRefType.__init__(self, mixedclass_, content_)
supermod.compoundRefType.subclass = compoundRefTypeSub
# end class compoundRefTypeSub
class reimplementTypeSub(supermod.reimplementType):
def __init__(self, refid=None, valueOf_='', mixedclass_=None, content_=None):
supermod.reimplementType.__init__(self, mixedclass_, content_)
supermod.reimplementType.subclass = reimplementTypeSub
# end class reimplementTypeSub
class incTypeSub(supermod.incType):
def __init__(self, local=None, refid=None, valueOf_='', mixedclass_=None, content_=None):
supermod.incType.__init__(self, mixedclass_, content_)
supermod.incType.subclass = incTypeSub
# end class incTypeSub
class refTypeSub(supermod.refType):
def __init__(self, prot=None, refid=None, valueOf_='', mixedclass_=None, content_=None):
supermod.refType.__init__(self, mixedclass_, content_)
supermod.refType.subclass = refTypeSub
# end class refTypeSub
class refTextTypeSub(supermod.refTextType):
def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None):
supermod.refTextType.__init__(self, mixedclass_, content_)
supermod.refTextType.subclass = refTextTypeSub
# end class refTextTypeSub
class sectiondefTypeSub(supermod.sectiondefType):
def __init__(self, kind=None, header='', description=None, memberdef=None):
supermod.sectiondefType.__init__(self, kind, header, description, memberdef)
def find(self, details):
for memberdef in self.memberdef:
if memberdef.id == details.refid:
return memberdef
return None
supermod.sectiondefType.subclass = sectiondefTypeSub
# end class sectiondefTypeSub
class memberdefTypeSub(supermod.memberdefType):
def __init__(self, initonly=None, kind=None, volatile=None, const=None, raise_=None, virt=None, readable=None, prot=None, explicit=None, new=None, final=None, writable=None, add=None, static=None, remove=None, sealed=None, mutable=None, gettable=None, inline=None, settable=None, id=None, templateparamlist=None, type_=None, definition='', argsstring='', name='', read='', write='', bitfield='', reimplements=None, reimplementedby=None, param=None, enumvalue=None, initializer=None, exceptions=None, briefdescription=None, detaileddescription=None, inbodydescription=None, location=None, references=None, referencedby=None):
supermod.memberdefType.__init__(self, initonly, kind, volatile, const, raise_, virt, readable, prot, explicit, new, final, writable, add, static, remove, sealed, mutable, gettable, inline, settable, id, templateparamlist, type_, definition, argsstring, name, read, write, bitfield, reimplements, reimplementedby, param, enumvalue, initializer, exceptions, briefdescription, detaileddescription, inbodydescription, location, references, referencedby)
supermod.memberdefType.subclass = memberdefTypeSub
# end class memberdefTypeSub
class descriptionTypeSub(supermod.descriptionType):
def __init__(self, title='', para=None, sect1=None, internal=None, mixedclass_=None, content_=None):
supermod.descriptionType.__init__(self, mixedclass_, content_)
supermod.descriptionType.subclass = descriptionTypeSub
# end class descriptionTypeSub
class enumvalueTypeSub(supermod.enumvalueType):
def __init__(self, prot=None, id=None, name='', initializer=None, briefdescription=None, detaileddescription=None, mixedclass_=None, content_=None):
supermod.enumvalueType.__init__(self, mixedclass_, content_)
supermod.enumvalueType.subclass = enumvalueTypeSub
# end class enumvalueTypeSub
class templateparamlistTypeSub(supermod.templateparamlistType):
def __init__(self, param=None):
supermod.templateparamlistType.__init__(self, param)
supermod.templateparamlistType.subclass = templateparamlistTypeSub
# end class templateparamlistTypeSub
class paramTypeSub(supermod.paramType):
def __init__(self, type_=None, declname='', defname='', array='', defval=None, briefdescription=None):
supermod.paramType.__init__(self, type_, declname, defname, array, defval, briefdescription)
supermod.paramType.subclass = paramTypeSub
# end class paramTypeSub
class linkedTextTypeSub(supermod.linkedTextType):
def __init__(self, ref=None, mixedclass_=None, content_=None):
supermod.linkedTextType.__init__(self, mixedclass_, content_)
supermod.linkedTextType.subclass = linkedTextTypeSub
# end class linkedTextTypeSub
class graphTypeSub(supermod.graphType):
def __init__(self, node=None):
supermod.graphType.__init__(self, node)
supermod.graphType.subclass = graphTypeSub
# end class graphTypeSub
class nodeTypeSub(supermod.nodeType):
def __init__(self, id=None, label='', link=None, childnode=None):
supermod.nodeType.__init__(self, id, label, link, childnode)
supermod.nodeType.subclass = nodeTypeSub
# end class nodeTypeSub
class childnodeTypeSub(supermod.childnodeType):
def __init__(self, relation=None, refid=None, edgelabel=None):
supermod.childnodeType.__init__(self, relation, refid, edgelabel)
supermod.childnodeType.subclass = childnodeTypeSub
# end class childnodeTypeSub
class linkTypeSub(supermod.linkType):
def __init__(self, refid=None, external=None, valueOf_=''):
supermod.linkType.__init__(self, refid, external)
supermod.linkType.subclass = linkTypeSub
# end class linkTypeSub
class listingTypeSub(supermod.listingType):
def __init__(self, codeline=None):
supermod.listingType.__init__(self, codeline)
supermod.listingType.subclass = listingTypeSub
# end class listingTypeSub
class codelineTypeSub(supermod.codelineType):
def __init__(self, external=None, lineno=None, refkind=None, refid=None, highlight=None):
supermod.codelineType.__init__(self, external, lineno, refkind, refid, highlight)
supermod.codelineType.subclass = codelineTypeSub
# end class codelineTypeSub
class highlightTypeSub(supermod.highlightType):
def __init__(self, class_=None, sp=None, ref=None, mixedclass_=None, content_=None):
supermod.highlightType.__init__(self, mixedclass_, content_)
supermod.highlightType.subclass = highlightTypeSub
# end class highlightTypeSub
class referenceTypeSub(supermod.referenceType):
def __init__(self, endline=None, startline=None, refid=None, compoundref=None, valueOf_='', mixedclass_=None, content_=None):
supermod.referenceType.__init__(self, mixedclass_, content_)
supermod.referenceType.subclass = referenceTypeSub
# end class referenceTypeSub
class locationTypeSub(supermod.locationType):
def __init__(self, bodystart=None, line=None, bodyend=None, bodyfile=None, file=None, valueOf_=''):
supermod.locationType.__init__(self, bodystart, line, bodyend, bodyfile, file)
supermod.locationType.subclass = locationTypeSub
# end class locationTypeSub
class docSect1TypeSub(supermod.docSect1Type):
def __init__(self, id=None, title='', para=None, sect2=None, internal=None, mixedclass_=None, content_=None):
supermod.docSect1Type.__init__(self, mixedclass_, content_)
supermod.docSect1Type.subclass = docSect1TypeSub
# end class docSect1TypeSub
class docSect2TypeSub(supermod.docSect2Type):
def __init__(self, id=None, title='', para=None, sect3=None, internal=None, mixedclass_=None, content_=None):
supermod.docSect2Type.__init__(self, mixedclass_, content_)
supermod.docSect2Type.subclass = docSect2TypeSub
# end class docSect2TypeSub
class docSect3TypeSub(supermod.docSect3Type):
def __init__(self, id=None, title='', para=None, sect4=None, internal=None, mixedclass_=None, content_=None):
supermod.docSect3Type.__init__(self, mixedclass_, content_)
supermod.docSect3Type.subclass = docSect3TypeSub
# end class docSect3TypeSub
class docSect4TypeSub(supermod.docSect4Type):
def __init__(self, id=None, title='', para=None, internal=None, mixedclass_=None, content_=None):
supermod.docSect4Type.__init__(self, mixedclass_, content_)
supermod.docSect4Type.subclass = docSect4TypeSub
# end class docSect4TypeSub
class docInternalTypeSub(supermod.docInternalType):
def __init__(self, para=None, sect1=None, mixedclass_=None, content_=None):
supermod.docInternalType.__init__(self, mixedclass_, content_)
supermod.docInternalType.subclass = docInternalTypeSub
# end class docInternalTypeSub
class docInternalS1TypeSub(supermod.docInternalS1Type):
def __init__(self, para=None, sect2=None, mixedclass_=None, content_=None):
supermod.docInternalS1Type.__init__(self, mixedclass_, content_)
supermod.docInternalS1Type.subclass = docInternalS1TypeSub
# end class docInternalS1TypeSub
class docInternalS2TypeSub(supermod.docInternalS2Type):
def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None):
supermod.docInternalS2Type.__init__(self, mixedclass_, content_)
supermod.docInternalS2Type.subclass = docInternalS2TypeSub
# end class docInternalS2TypeSub
class docInternalS3TypeSub(supermod.docInternalS3Type):
def __init__(self, para=None, sect3=None, mixedclass_=None, content_=None):
supermod.docInternalS3Type.__init__(self, mixedclass_, content_)
supermod.docInternalS3Type.subclass = docInternalS3TypeSub
# end class docInternalS3TypeSub
class docInternalS4TypeSub(supermod.docInternalS4Type):
def __init__(self, para=None, mixedclass_=None, content_=None):
supermod.docInternalS4Type.__init__(self, mixedclass_, content_)
supermod.docInternalS4Type.subclass = docInternalS4TypeSub
# end class docInternalS4TypeSub
class docURLLinkSub(supermod.docURLLink):
def __init__(self, url=None, valueOf_='', mixedclass_=None, content_=None):
supermod.docURLLink.__init__(self, mixedclass_, content_)
supermod.docURLLink.subclass = docURLLinkSub
# end class docURLLinkSub
class docAnchorTypeSub(supermod.docAnchorType):
def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None):
supermod.docAnchorType.__init__(self, mixedclass_, content_)
supermod.docAnchorType.subclass = docAnchorTypeSub
# end class docAnchorTypeSub
class docFormulaTypeSub(supermod.docFormulaType):
def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None):
supermod.docFormulaType.__init__(self, mixedclass_, content_)
supermod.docFormulaType.subclass = docFormulaTypeSub
# end class docFormulaTypeSub
class docIndexEntryTypeSub(supermod.docIndexEntryType):
def __init__(self, primaryie='', secondaryie=''):
supermod.docIndexEntryType.__init__(self, primaryie, secondaryie)
supermod.docIndexEntryType.subclass = docIndexEntryTypeSub
# end class docIndexEntryTypeSub
class docListTypeSub(supermod.docListType):
def __init__(self, listitem=None):
supermod.docListType.__init__(self, listitem)
supermod.docListType.subclass = docListTypeSub
# end class docListTypeSub
class docListItemTypeSub(supermod.docListItemType):
def __init__(self, para=None):
supermod.docListItemType.__init__(self, para)
supermod.docListItemType.subclass = docListItemTypeSub
# end class docListItemTypeSub
class docSimpleSectTypeSub(supermod.docSimpleSectType):
def __init__(self, kind=None, title=None, para=None):
supermod.docSimpleSectType.__init__(self, kind, title, para)
supermod.docSimpleSectType.subclass = docSimpleSectTypeSub
# end class docSimpleSectTypeSub
class docVarListEntryTypeSub(supermod.docVarListEntryType):
def __init__(self, term=None):
supermod.docVarListEntryType.__init__(self, term)
supermod.docVarListEntryType.subclass = docVarListEntryTypeSub
# end class docVarListEntryTypeSub
class docRefTextTypeSub(supermod.docRefTextType):
def __init__(self, refid=None, kindref=None, external=None, valueOf_='', mixedclass_=None, content_=None):
supermod.docRefTextType.__init__(self, mixedclass_, content_)
supermod.docRefTextType.subclass = docRefTextTypeSub
# end class docRefTextTypeSub
class docTableTypeSub(supermod.docTableType):
def __init__(self, rows=None, cols=None, row=None, caption=None):
supermod.docTableType.__init__(self, rows, cols, row, caption)
supermod.docTableType.subclass = docTableTypeSub
# end class docTableTypeSub
class docRowTypeSub(supermod.docRowType):
def __init__(self, entry=None):
supermod.docRowType.__init__(self, entry)
supermod.docRowType.subclass = docRowTypeSub
# end class docRowTypeSub
class docEntryTypeSub(supermod.docEntryType):
def __init__(self, thead=None, para=None):
supermod.docEntryType.__init__(self, thead, para)
supermod.docEntryType.subclass = docEntryTypeSub
# end class docEntryTypeSub
class docHeadingTypeSub(supermod.docHeadingType):
def __init__(self, level=None, valueOf_='', mixedclass_=None, content_=None):
supermod.docHeadingType.__init__(self, mixedclass_, content_)
supermod.docHeadingType.subclass = docHeadingTypeSub
# end class docHeadingTypeSub
class docImageTypeSub(supermod.docImageType):
def __init__(self, width=None, type_=None, name=None, height=None, valueOf_='', mixedclass_=None, content_=None):
supermod.docImageType.__init__(self, mixedclass_, content_)
supermod.docImageType.subclass = docImageTypeSub
# end class docImageTypeSub
class docDotFileTypeSub(supermod.docDotFileType):
def __init__(self, name=None, valueOf_='', mixedclass_=None, content_=None):
supermod.docDotFileType.__init__(self, mixedclass_, content_)
supermod.docDotFileType.subclass = docDotFileTypeSub
# end class docDotFileTypeSub
class docTocItemTypeSub(supermod.docTocItemType):
def __init__(self, id=None, valueOf_='', mixedclass_=None, content_=None):
supermod.docTocItemType.__init__(self, mixedclass_, content_)
supermod.docTocItemType.subclass = docTocItemTypeSub
# end class docTocItemTypeSub
class docTocListTypeSub(supermod.docTocListType):
def __init__(self, tocitem=None):
supermod.docTocListType.__init__(self, tocitem)
supermod.docTocListType.subclass = docTocListTypeSub
# end class docTocListTypeSub
class docLanguageTypeSub(supermod.docLanguageType):
def __init__(self, langid=None, para=None):
supermod.docLanguageType.__init__(self, langid, para)
supermod.docLanguageType.subclass = docLanguageTypeSub
# end class docLanguageTypeSub
class docParamListTypeSub(supermod.docParamListType):
def __init__(self, kind=None, parameteritem=None):
supermod.docParamListType.__init__(self, kind, parameteritem)
supermod.docParamListType.subclass = docParamListTypeSub
# end class docParamListTypeSub
class docParamListItemSub(supermod.docParamListItem):
def __init__(self, parameternamelist=None, parameterdescription=None):
supermod.docParamListItem.__init__(self, parameternamelist, parameterdescription)
supermod.docParamListItem.subclass = docParamListItemSub
# end class docParamListItemSub
class docParamNameListSub(supermod.docParamNameList):
def __init__(self, parametername=None):
supermod.docParamNameList.__init__(self, parametername)
supermod.docParamNameList.subclass = docParamNameListSub
# end class docParamNameListSub
class docParamNameSub(supermod.docParamName):
def __init__(self, direction=None, ref=None, mixedclass_=None, content_=None):
supermod.docParamName.__init__(self, mixedclass_, content_)
supermod.docParamName.subclass = docParamNameSub
# end class docParamNameSub
class docXRefSectTypeSub(supermod.docXRefSectType):
def __init__(self, id=None, xreftitle=None, xrefdescription=None):
supermod.docXRefSectType.__init__(self, id, xreftitle, xrefdescription)
supermod.docXRefSectType.subclass = docXRefSectTypeSub
# end class docXRefSectTypeSub
class docCopyTypeSub(supermod.docCopyType):
def __init__(self, link=None, para=None, sect1=None, internal=None):
supermod.docCopyType.__init__(self, link, para, sect1, internal)
supermod.docCopyType.subclass = docCopyTypeSub
# end class docCopyTypeSub
class docCharTypeSub(supermod.docCharType):
def __init__(self, char=None, valueOf_=''):
supermod.docCharType.__init__(self, char)
supermod.docCharType.subclass = docCharTypeSub
# end class docCharTypeSub
class docParaTypeSub(supermod.docParaType):
def __init__(self, char=None, valueOf_=''):
supermod.docParaType.__init__(self, char)
self.parameterlist = []
self.simplesects = []
self.content = []
def buildChildren(self, child_, nodeName_):
supermod.docParaType.buildChildren(self, child_, nodeName_)
if child_.nodeType == Node.TEXT_NODE:
obj_ = self.mixedclass_(MixedContainer.CategoryText,
MixedContainer.TypeNone, '', child_.nodeValue)
self.content.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == "ref":
obj_ = supermod.docRefTextType.factory()
obj_.build(child_)
self.content.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'parameterlist':
obj_ = supermod.docParamListType.factory()
obj_.build(child_)
self.parameterlist.append(obj_)
elif child_.nodeType == Node.ELEMENT_NODE and \
nodeName_ == 'simplesect':
obj_ = supermod.docSimpleSectType.factory()
obj_.build(child_)
self.simplesects.append(obj_)
supermod.docParaType.subclass = docParaTypeSub
# end class docParaTypeSub
def parse(inFilename):
doc = minidom.parse(inFilename)
rootNode = doc.documentElement
rootObj = supermod.DoxygenType.factory()
rootObj.build(rootNode)
return rootObj
|
mpharrigan/mdtraj | refs/heads/master | mdtraj/tests/test_psf.py | 5 | ##############################################################################
# MDTraj: A Python Library for Loading, Saving, and Manipulating
# Molecular Dynamics Trajectories.
# Copyright 2012-2013 Stanford University and the Authors
#
# Authors: Jason Swails
# Contributors: Robert McGibbon
#
# MDTraj is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 2.1
# of the License, or (at your option) any later version.
#
# This library 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 Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with MDTraj. If not, see <http://www.gnu.org/licenses/>.
##############################################################################
import os
import mdtraj as md
from mdtraj.testing import get_fn, eq, skipif
from mdtraj.formats import psf
from mdtraj.utils import enter_temp_directory
from distutils.spawn import find_executable
VMD = find_executable('vmd')
VMD_MSG = 'This test requires the VMD executable: http://www.ks.uiuc.edu/Research/vmd/'
def test_load_psf():
print('sddsfsfdsdsdf')
top = psf.load_psf(get_fn('ala_ala_ala.psf'))
ref_top = md.load(get_fn('ala_ala_ala.pdb')).topology
eq(top, ref_top)
# Test the XPLOR psf format parsing
top2 = psf.load_psf(get_fn('ala_ala_ala.xpsf'))
eq(top2, ref_top)
# Test segment_names are loaded properly
assert next(top.residues).segment_id == "AAL", "Segment id is not being assigned correctly for ala_ala_ala.psf"
assert next(top2.residues).segment_id == "AAL", "Segment id is not being assigned correctly for ala_ala_ala.xpsf"
def test_multichain_psf():
top = psf.load_psf(get_fn('3pqr_memb.psf'))
# Check that each segment was turned into a chain
eq(top.n_chains, 11)
chain_lengths = [5162, 185, 97, 28, 24, 24, 45, 35742, 72822, 75, 73]
for i, n in enumerate(chain_lengths):
eq(top.chain(i).n_atoms, n)
# There are some non-sequentially numbered residues across chain
# boundaries... make sure resSeq is properly taken from the PSF
eq(top.chain(0).residue(0).resSeq, 1)
eq(top.chain(0).residue(-1).resSeq, 326)
eq(top.chain(1).residue(0).resSeq, 340)
eq(top.chain(1).residue(-1).resSeq, 350)
eq(top.chain(2).residue(0).resSeq, 1)
eq(top.chain(2).residue(-1).resSeq, 4)
eq(top.chain(3).residue(0).resSeq, 1)
eq(top.chain(3).residue(-1).resSeq, 1)
eq(top.chain(4).residue(0).resSeq, 1)
eq(top.chain(4).residue(-1).resSeq, 1)
eq(top.chain(5).residue(0).resSeq, 1)
eq(top.chain(5).residue(-1).resSeq, 1)
eq(top.chain(6).residue(0).resSeq, 1)
eq(top.chain(6).residue(-1).resSeq, 2)
eq(top.chain(7).residue(0).resSeq, 1)
eq(top.chain(7).residue(-1).resSeq, 276)
eq(top.chain(8).residue(0).resSeq, 1)
eq(top.chain(8).residue(-1).resSeq, 24274)
eq(top.chain(9).residue(0).resSeq, 1)
eq(top.chain(9).residue(-1).resSeq, 75)
eq(top.chain(10).residue(0).resSeq, 1)
eq(top.chain(10).residue(-1).resSeq, 73)
def test_load_mdcrd_with_psf():
traj = md.load(get_fn('ala_ala_ala.mdcrd'), top=get_fn('ala_ala_ala.psf'))
ref_traj = md.load(get_fn('ala_ala_ala.pdb'))
eq(traj.topology, ref_traj.topology)
eq(traj.xyz, ref_traj.xyz)
@skipif(not VMD, VMD_MSG)
def test_vmd_psf():
yield lambda: _test_against_vmd(get_fn('1vii.pdb'))
yield lambda: _test_against_vmd(get_fn('2EQQ.pdb'))
def _test_against_vmd(pdb):
# this is probably not cross-platform compatible. I assume that the exact
# path to this CHARMM topology that is included with VMD depends on
# the install mechanism, especially for bundled mac or windows installers
VMD_ROOT = os.path.join(os.path.dirname(os.path.realpath(VMD)), '..')
top_paths = [os.path.join(r, f) for (r, _, fs) in os.walk(VMD_ROOT) for f in fs
if 'top_all27_prot_lipid_na.inp' in f]
assert len(top_paths) >= 0
top = os.path.abspath(top_paths[0]).replace(" ", "\\ ")
TEMPLATE = '''
package require psfgen
topology %(top)s
pdbalias residue HIS HSE
pdbalias atom ILE CD1 CD
segment U {pdb %(pdb)s}
coordpdb %(pdb)s U
guesscoord
writepdb out.pdb
writepsf out.psf
exit
''' % {'top': top, 'pdb' : pdb}
with enter_temp_directory():
with open('script.tcl', 'w') as f:
f.write(TEMPLATE)
os.system(' '.join([VMD.replace(' ', '\ '), '-e', 'script.tcl',
'-dispdev', 'none']))
out_pdb = md.load('out.pdb')
out_psf = md.load_psf('out.psf')
# make sure the two topologies are equal
eq(out_pdb.top, out_psf)
|
poojavade/Genomics_Docker | refs/heads/master | Dockerfiles/gedlab-khmer-filter-abund/pymodules/python2.7/lib/python/pygsl/poly.py | 1 | # Author : Pierre Schnizer
"""
Wrapper over the functions as described in Chaper 6 of the
reference manual.
There are routines for finding real and complex roots of quadratic and cubic
equations using analytic methods. An iterative polynomial solver is also
available for finding the roots of general polynomials with real coefficients
(of any order).
All the doc strings were taken form the gsl reference document.
"""
import pygsl
import pygsl._numobj as Numeric
import pygsl.errno
from . import _poly
get_typecode = pygsl.get_typecode
GSL_SUCCESS = pygsl.errno.GSL_SUCCESS
GSL_FAILURE = pygsl.errno.GSL_FAILURE
def poly_eval(*args):
"""
This function evaluates the polynomial
c[0] + c[1] x + c[2] x^2 + \dots + c[len-1] x^{len-1}
using Horner's method for stability
input: c, x
c ... array of coefficients
x ...
output: y
"""
return _poly.gsl_poly_eval(*args)
class poly_dd:
"""
This class manipulates polynomials stored in Newton's divided-difference
representation. The use of divided-differences is described in
Abramowitz & Stegun sections 25.1.4, 25.2.26.
"""
def __init__(self, xa, ya):
"""
This method computes a divided-difference representation of the
interpolating polynomial for the points (xa, ya) stored in the arrays
xa and ya. The divided-differences of (xa,ya) are stored internally.
input : xa, ya
xa ... array of x values
ya ... array of y values
These arrays must have the same size.
"""
self.xa = xa
tmp, dd = _poly.gsl_poly_dd_init(xa, ya)
assert(tmp == 0)
self.dd = dd
def eval(self, x):
"""
This method evaluates the polynomial stored in divided-difference form
at point x.
input : x
x ... point
output : y
"""
return _poly.gsl_poly_dd_eval(self.dd, self.xa, x)
def taylor(self, xp):
"""
This method converts the internal divided-difference representation of a
polynomial to a Taylor expansion.
input : xp
xp ... point to expand about
"""
w = Numeric.zeros(self.dd.shape, get_typecode(self.dd))
return _poly.gsl_poly_dd_taylor(xp, self.dd, self.xa, w)
class poly_complex:
"""
The roots of polynomial equations cannot be found analytically beyond the
special cases of the quadratic, cubic and quartic equation. This class
uses an iterative method to find the approximate locations of roots of
higher order polynomials.
"""
def __init__(self, dimension):
"""
Initalizes the class.
Input : n
n ... number of coefficients of the polynomial.
"""
self._myptr = None
self._myptr = _poly.gsl_poly_complex_workspace_alloc(dimension)
def solve(self, a):
"""
This function computes the roots of the general polynomial P(x) = a_0
+ a_1 x + a_2 x^2 + ... + a_{n-1} x^{n-1} using balanced-QR reduction
of the companion matrix. The parameter n specifies the length of the
coefficient array. The coefficient of the highest order term must be
non-zero. The function requires a workspace w of the appropriate
size. The n-1 roots are returned in the packed complex array z of
length 2(n-1), alternating real and imaginary parts.
The function returns GSL_SUCCESS if all the roots are found and
GSL_EFAILED if the QR reduction does not converge.
input : z
z ... Array of complex coefficients.
output : flag, z_out
flag ... GSL_SUCCESS or GSL_FAILURE
z ... Array of complex roots
"""
return _poly.gsl_poly_complex_solve(a, self._myptr)
def __del__(self):
if hasattr(self, '_myptr'):
if self._myptr != None:
_poly.gsl_poly_complex_workspace_free(self._myptr)
def solve_quadratic(*args):
"""
a x^2 + b x + c = 0
The number of real roots (either zero or two) is returned, and their
locations are stored in x0 and x1. If no real roots are found then x0 and
x1 are not modified. When two real roots are found they are stored in x0
and x1 in ascending order. The case of coincident roots is not considered
special. For example (x-1)^2=0 will have two roots, which happen to have
exactly equal values.
The number of roots found depends on the sign of the discriminant b^2 - 4
a c. This will be subject to rounding and cancellation errors when
computed in double precision, and will also be subject to errors if the
coefficients of the polynomial are inexact. These errors may cause a
discrete change in the number of roots. However, for polynomials with
small integer coefficients the discriminant can always be computed
exactly.
input : a, b, c
output : n, r1, r2
n ... number of roots found
r1 ... first root
r2 ... second root
"""
return _poly.gsl_poly_solve_quadratic(*args)
def complex_solve_quadratic(*args):
"""
The complex version of solve quadratic. See solve_quadratic for explanation.
"""
return _poly.gsl_poly_complex_solve_quadratic(*args)
def solve_cubic(*args):
"""
This function finds the real roots of the cubic equation,
x^3 + a x^2 + b x + c = 0
with a leading coefficient of unity. The number of real roots (either one
or three) is returned, and their locations are stored in x0, x1 and
x2. If one real root is found then only x0 is modified. When three real
roots are found they are stored in x0, x1 and x2 in ascending order. The
case of coincident roots is not considered special. For example, the
equation (x-1)^3=0 will have three roots with exactly equal values.
input : a, b, c
output : n, r1, r2
n ... number of roots found
r1 ... first root
r2 ... second root
r3 ... third root
"""
return _poly.gsl_poly_solve_cubic(*args)
def complex_solve_cubic(*args):
"""
This function finds the complex roots of the cubic equation,
z^3 + a z^2 + b z + c = 0
The number of complex roots is returned (always three) and the locations
of the roots are stored in z0, z1 and z2. The roots are returned in
ascending order, sorted first by their real components and then by their
imaginary components.
input : a, b, c
output : n, r1, r2
n ... number of roots found
r1 ... first root
r2 ... second root
r3 ... third root
"""
return _poly.gsl_poly_complex_solve_cubic(*args)
|
reviewboard/reviewboard | refs/heads/master | reviewboard/notifications/email/hooks.py | 2 | """Extension hooks for augmenting e-mail messages."""
from __future__ import unicode_literals
import warnings
from collections import defaultdict
from inspect import getargspec
from reviewboard.reviews.signals import (review_request_published,
review_published, reply_published,
review_request_closed)
# A mapping of signals to EmailHooks.
_hooks = defaultdict(set)
def register_email_hook(signal, handler):
"""Register an e-mail hook.
Args:
signal (django.dispatch.Signal):
The signal that will trigger the e-mail to be sent. This is one of
:py:data:`~reviewboard.reviews.signals.review_request_published`,
:py:data:`~reviewboard.reviews.signals.review_request_closed`,
:py:data:`~reviewboard.reviews.signals.review_published`, or
:py:data:`~reviewboard.reviews.signals.reply_published`.
handler (reviewboard.extensions.hooks.EmailHook):
The ``EmailHook`` that will be triggered when an e-mail of the
chosen type is about to be sent.
"""
assert signal in (review_request_published, review_request_closed,
review_published, reply_published), (
'Invalid signal %r' % signal)
_hooks[signal].add(handler)
def unregister_email_hook(signal, handler):
"""Unregister an e-mail hook.
Args:
signal (django.dispatch.Signal):
The signal that will trigger the e-mail to be sent. This is one of
:py:data:`~reviewboard.reviews.signals.review_request_published`,
:py:data:`~reviewboard.reviews.signals.review_request_closed`,
:py:data:`~reviewboard.reviews.signals.review_published`, or
:py:data:`~reviewboard.reviews.signals.reply_published`.
handler (reviewboard.extensions.hooks.EmailHook):
The ``EmailHook`` that will be triggered when an e-mail of the
chosen type is about to be sent.
"""
assert signal in (review_request_published, review_request_closed,
review_published, reply_published), (
'Invalid signal %r' % signal)
_hooks[signal].discard(handler)
def filter_email_recipients_from_hooks(to_field, cc_field, signal, **kwargs):
"""Filter the e-mail recipients through configured e-mail hooks.
Args:
to_field (set):
The original To field of the e-mail, as a set of
:py:class:`Users <django.contrib.auth.models.User>` and
:py:class:`Groups <reviewboard.reviews.models.Group>`.
cc_field (set):
The original CC field of the e-mail, as a set of
:py:class:`Users <django.contrib.auth.models.User>` and
:py:class:`Groups <reviewboard.reviews.models.Group>`.
signal (django.dispatch.Signal):
The signal that triggered the e-mail.
**kwargs (dict):
Extra keyword arguments to pass to the e-mail hook.
Returns:
tuple:
A 2-tuple of the To field and the CC field, as sets of
:py:class:`Users <django.contrib.auth.models.User>` and
:py:class:`Groups <reviewboard.reviews.models.Group>`.
"""
if signal in _hooks:
for hook in _hooks[signal]:
to_field = hook.get_to_field(to_field, **kwargs)
cc_field = hook.get_cc_field(cc_field, **kwargs)
return to_field, cc_field
|
pumodi/Slimy_Snakes_the_Difficult_Path | refs/heads/master | Ex2/ex2.py | 7 | # A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
print "I could have code like this." # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print "This will run." |
spottradingllc/zoom | refs/heads/master | server/zoom/www/cache/application_dependency_cache.py | 1 | import logging
import time
from xml.etree import ElementTree
from kazoo.exceptions import NoNodeError
from zoom.agent.predicate.time_window import TimeWindow
from zoom.agent.util.helpers import verify_attribute
from zoom.common.decorators import connected_with_return, TimeThis
from zoom.common.types import PredicateType, Weekdays
from zoom.www.messages.application_dependencies \
import ApplicationDependenciesMessage
from zoom.www.messages.message_throttler import MessageThrottle
from zoom.agent.util.helpers import zk_path_join
class ApplicationDependencyCache(object):
def __init__(self, configuration, zoo_keeper, web_socket_clients,
time_estimate_cache):
"""
:type configuration: zoom.config.configuration.Configuration
:type zoo_keeper: kazoo.client.KazooClient
:type web_socket_clients: list
"""
self._cache = ApplicationDependenciesMessage()
self._configuration = configuration
self._zoo_keeper = zoo_keeper
self._web_socket_clients = web_socket_clients
self._time_estimate_cache = time_estimate_cache
self._message_throttle = MessageThrottle(configuration,
web_socket_clients)
def start(self):
self._message_throttle.start()
def stop(self):
self._message_throttle.stop()
def load(self):
"""
:rtype: ApplicationDependenciesMessage
"""
try:
if not self._cache.application_dependencies:
self._load()
return self._cache
except Exception:
logging.exception('An unhandled Exception has occurred')
def reload(self):
"""
Clear cache, and re-walk agent config path.
"""
self._cache.clear()
logging.info("Application dependency cache cleared")
self._on_update_path(self._configuration.agent_configuration_path)
@TimeThis(__file__)
def _load(self):
"""
Walk full agent config path to get data. Load self._cache object
"""
self._cache.clear()
self._walk(self._configuration.agent_configuration_path, self._cache)
logging.info("Application dependency cache loaded from ZooKeeper {0}"
.format(self._configuration.agent_configuration_path))
self._recalc_downstream_dependencies()
self._time_estimate_cache.update_dependencies(
self._cache.application_dependencies)
@connected_with_return(None)
def _walk(self, path, result):
"""
:type path: str
:type result: ApplicationDependenciesMessage
"""
try:
children = self._zoo_keeper.get_children(path,
watch=self._on_update)
if children:
for child in children:
self._walk(zk_path_join(path, child), result)
else:
self._get_application_dependency(path, result)
except NoNodeError:
logging.debug('Node at {0} no longer exists.'.format(path))
def _get_application_dependency(self, path, result):
"""
Load result object with application dependencies
:type path: str
:type result: ApplicationDependenciesMessage
"""
if self._zoo_keeper.exists(path):
data, stat = self._zoo_keeper.get(path, watch=self._on_update)
if not data:
return
try:
root = ElementTree.fromstring(data)
for node in root.findall('Automation/Component'):
app_id = node.attrib.get('id')
registrationpath = node.attrib.get('registrationpath', None)
if registrationpath is None:
registrationpath = zk_path_join(
self._configuration.application_state_path, app_id)
start_action = node.find('Actions/Action[@id="start"]')
if start_action is None:
logging.warn("No Start Action Found for {0}"
.format(registrationpath))
dependencies = list()
else:
dependencies = self._parse_dependencies(start_action)
data = {
"configuration_path": registrationpath,
"dependencies": dependencies,
"downstream": list()
}
result.update({registrationpath: data})
except Exception:
logging.exception('An unhandled exception occurred')
else:
logging.warn("config path does not exist: {0}".format(path))
def _parse_dependencies(self, action):
"""
Parse dependencies out of XML
:type action: xml.etree.ElementTree.Element
:rtype: list
"""
# TODO: rename 'path' when it really isn't a path. this is a hack...
# prev_was_not keeps track of whether the outer class was 'not'
dependencies = []
prev_was_not = False
for predicate in action.iter('Predicate'):
pred_type = predicate.get('type').lower()
pred_path = predicate.get('path', None)
# pred_oper = predicate.get('operational', False)
pred_oper = bool(verify_attribute(predicate, 'operational',
none_allowed=True))
if pred_type == PredicateType.ZOOKEEPERHASCHILDREN:
dependencies.append({'type': pred_type,
'path': pred_path,
'operational': pred_oper})
prev_was_not = False
elif pred_type == PredicateType.ZOOKEEPERHASGRANDCHILDREN:
dependencies.append({'type': pred_type,
'path': pred_path,
'operational': pred_oper})
prev_was_not = False
elif pred_type == PredicateType.ZOOKEEPERGOODUNTILTIME:
if len(pred_path.split('gut/')) > 1:
dependencies.append(
{'type': pred_type,
'path': ("I should be up between: {0}"
.format(pred_path.split("gut/")[1])),
'operational': pred_oper})
else:
logging.debug('Invalid GUT path: {0}'.format(pred_path))
prev_was_not = False
elif pred_type == PredicateType.HOLIDAY:
dependencies.append(
{'type': pred_type,
'path': ("Does NOT run on holidays" if prev_was_not
else "Runs on holidays"),
'operational': pred_oper})
prev_was_not = False
elif pred_type == PredicateType.WEEKEND:
dependencies.append(
{'type': pred_type,
'path': ("Does NOT run on weekends" if prev_was_not
else "Runs on weekends"),
'operational': pred_oper})
prev_was_not = False
elif pred_type == PredicateType.TIMEWINDOW:
begin = predicate.get('begin', None)
end = predicate.get('end', None)
weekdays = predicate.get('weekdays', None)
msg = 'I should be up '
if begin is not None:
msg += 'after: {0} '.format(begin)
if end is not None:
msg += 'until: {0}'.format(end)
# only send dependency if there is something to send
if begin is not None or end is not None:
dependencies.append({'type': pred_type, 'path': msg,
'operational': pred_oper})
# pretend this is a weekend predicate for convenience
if weekdays is not None:
day_range = TimeWindow.parse_range(weekdays)
if Weekdays.SATURDAY in day_range or Weekdays.SUNDAY in day_range:
wk_msg = 'Runs on weekends'
else:
wk_msg = 'Does NOT run on weekends'
dependencies.append({'type': PredicateType.WEEKEND,
'path': wk_msg,
'operational': pred_oper})
elif pred_type == PredicateType.NOT:
prev_was_not = True
return dependencies
@TimeThis(__file__)
def _recalc_downstream_dependencies(self, tries=0):
"""
Loop over existing cache and link upstream with downstream elements
"""
# clear existing downstream
try:
for data in self._cache.application_dependencies.itervalues():
downstream = data.get('downstream')
del downstream[:]
dep_copy = self._cache.application_dependencies.copy()
for path, data in dep_copy.iteritems():
for key, value in self._cache.application_dependencies.iteritems():
for dep in data.get('dependencies'):
if dep['type'] == PredicateType.ZOOKEEPERHASGRANDCHILDREN:
if key.startswith(dep['path']):
value.get('downstream').append(path)
elif dep['type'] == PredicateType.ZOOKEEPERHASCHILDREN:
if dep['path'] == key:
value.get('downstream').append(path)
except RuntimeError:
time.sleep(1)
tries += 1
if tries < 3:
self._recalc_downstream_dependencies(tries=tries)
def _on_update(self, event):
"""
Callback to send updates via websocket on application state changes.
:type event: kazoo.protocol.states.WatchedEvent
"""
self._on_update_path(event.path)
def _on_update_path(self, path):
try:
message = ApplicationDependenciesMessage()
self._walk(path, message)
self._cache.update(message.application_dependencies)
self._recalc_downstream_dependencies()
self._message_throttle.add_message(message)
self._time_estimate_cache.update_dependencies(
self._cache.application_dependencies)
except Exception:
logging.exception('An unhandled Exception has occurred for path: '
'{0}'.format(path))
|
viveksh13/gymkhana | refs/heads/master | venv/lib/python2.7/site-packages/werkzeug/debug/repr.py | 280 | # -*- coding: utf-8 -*-
"""
werkzeug.debug.repr
~~~~~~~~~~~~~~~~~~~
This module implements object representations for debugging purposes.
Unlike the default repr these reprs expose a lot more information and
produce HTML instead of ASCII.
Together with the CSS and JavaScript files of the debugger this gives
a colorful and more compact output.
:copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD.
"""
import sys
import re
import codecs
from traceback import format_exception_only
try:
from collections import deque
except ImportError: # pragma: no cover
deque = None
from werkzeug.utils import escape
from werkzeug._compat import iteritems, PY2, text_type, integer_types, \
string_types
missing = object()
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
RegexType = type(_paragraph_re)
HELP_HTML = '''\
<div class=box>
<h3>%(title)s</h3>
<pre class=help>%(text)s</pre>
</div>\
'''
OBJECT_DUMP_HTML = '''\
<div class=box>
<h3>%(title)s</h3>
%(repr)s
<table>%(items)s</table>
</div>\
'''
def debug_repr(obj):
"""Creates a debug repr of an object as HTML unicode string."""
return DebugReprGenerator().repr(obj)
def dump(obj=missing):
"""Print the object details to stdout._write (for the interactive
console of the web debugger.
"""
gen = DebugReprGenerator()
if obj is missing:
rv = gen.dump_locals(sys._getframe(1).f_locals)
else:
rv = gen.dump_object(obj)
sys.stdout._write(rv)
class _Helper(object):
"""Displays an HTML version of the normal help, for the interactive
debugger only because it requires a patched sys.stdout.
"""
def __repr__(self):
return 'Type help(object) for help about object.'
def __call__(self, topic=None):
if topic is None:
sys.stdout._write('<span class=help>%s</span>' % repr(self))
return
import pydoc
pydoc.help(topic)
rv = sys.stdout.reset()
if isinstance(rv, bytes):
rv = rv.decode('utf-8', 'ignore')
paragraphs = _paragraph_re.split(rv)
if len(paragraphs) > 1:
title = paragraphs[0]
text = '\n\n'.join(paragraphs[1:])
else: # pragma: no cover
title = 'Help'
text = paragraphs[0]
sys.stdout._write(HELP_HTML % {'title': title, 'text': text})
helper = _Helper()
def _add_subclass_info(inner, obj, base):
if isinstance(base, tuple):
for base in base:
if type(obj) is base:
return inner
elif type(obj) is base:
return inner
module = ''
if obj.__class__.__module__ not in ('__builtin__', 'exceptions'):
module = '<span class="module">%s.</span>' % obj.__class__.__module__
return '%s%s(%s)' % (module, obj.__class__.__name__, inner)
class DebugReprGenerator(object):
def __init__(self):
self._stack = []
def _sequence_repr_maker(left, right, base=object(), limit=8):
def proxy(self, obj, recursive):
if recursive:
return _add_subclass_info(left + '...' + right, obj, base)
buf = [left]
have_extended_section = False
for idx, item in enumerate(obj):
if idx:
buf.append(', ')
if idx == limit:
buf.append('<span class="extended">')
have_extended_section = True
buf.append(self.repr(item))
if have_extended_section:
buf.append('</span>')
buf.append(right)
return _add_subclass_info(u''.join(buf), obj, base)
return proxy
list_repr = _sequence_repr_maker('[', ']', list)
tuple_repr = _sequence_repr_maker('(', ')', tuple)
set_repr = _sequence_repr_maker('set([', '])', set)
frozenset_repr = _sequence_repr_maker('frozenset([', '])', frozenset)
if deque is not None:
deque_repr = _sequence_repr_maker('<span class="module">collections.'
'</span>deque([', '])', deque)
del _sequence_repr_maker
def regex_repr(self, obj):
pattern = repr(obj.pattern)
if PY2:
pattern = pattern.decode('string-escape', 'ignore')
else:
pattern = codecs.decode(pattern, 'unicode-escape', 'ignore')
if pattern[:1] == 'u':
pattern = 'ur' + pattern[1:]
else:
pattern = 'r' + pattern
return u're.compile(<span class="string regex">%s</span>)' % pattern
def string_repr(self, obj, limit=70):
buf = ['<span class="string">']
escaped = escape(obj)
a = repr(escaped[:limit])
b = repr(escaped[limit:])
if isinstance(obj, text_type) and PY2:
buf.append('u')
a = a[1:]
b = b[1:]
if b != "''":
buf.extend((a[:-1], '<span class="extended">', b[1:], '</span>'))
else:
buf.append(a)
buf.append('</span>')
return _add_subclass_info(u''.join(buf), obj, (bytes, text_type))
def dict_repr(self, d, recursive, limit=5):
if recursive:
return _add_subclass_info(u'{...}', d, dict)
buf = ['{']
have_extended_section = False
for idx, (key, value) in enumerate(iteritems(d)):
if idx:
buf.append(', ')
if idx == limit - 1:
buf.append('<span class="extended">')
have_extended_section = True
buf.append('<span class="pair"><span class="key">%s</span>: '
'<span class="value">%s</span></span>' %
(self.repr(key), self.repr(value)))
if have_extended_section:
buf.append('</span>')
buf.append('}')
return _add_subclass_info(u''.join(buf), d, dict)
def object_repr(self, obj):
r = repr(obj)
if PY2:
r = r.decode('utf-8', 'replace')
return u'<span class="object">%s</span>' % escape(r)
def dispatch_repr(self, obj, recursive):
if obj is helper:
return u'<span class="help">%r</span>' % helper
if isinstance(obj, (integer_types, float, complex)):
return u'<span class="number">%r</span>' % obj
if isinstance(obj, string_types):
return self.string_repr(obj)
if isinstance(obj, RegexType):
return self.regex_repr(obj)
if isinstance(obj, list):
return self.list_repr(obj, recursive)
if isinstance(obj, tuple):
return self.tuple_repr(obj, recursive)
if isinstance(obj, set):
return self.set_repr(obj, recursive)
if isinstance(obj, frozenset):
return self.frozenset_repr(obj, recursive)
if isinstance(obj, dict):
return self.dict_repr(obj, recursive)
if deque is not None and isinstance(obj, deque):
return self.deque_repr(obj, recursive)
return self.object_repr(obj)
def fallback_repr(self):
try:
info = ''.join(format_exception_only(*sys.exc_info()[:2]))
except Exception: # pragma: no cover
info = '?'
if PY2:
info = info.decode('utf-8', 'ignore')
return u'<span class="brokenrepr"><broken repr (%s)>' \
u'</span>' % escape(info.strip())
def repr(self, obj):
recursive = False
for item in self._stack:
if item is obj:
recursive = True
break
self._stack.append(obj)
try:
try:
return self.dispatch_repr(obj, recursive)
except Exception:
return self.fallback_repr()
finally:
self._stack.pop()
def dump_object(self, obj):
repr = items = None
if isinstance(obj, dict):
title = 'Contents of'
items = []
for key, value in iteritems(obj):
if not isinstance(key, string_types):
items = None
break
items.append((key, self.repr(value)))
if items is None:
items = []
repr = self.repr(obj)
for key in dir(obj):
try:
items.append((key, self.repr(getattr(obj, key))))
except Exception:
pass
title = 'Details for'
title += ' ' + object.__repr__(obj)[1:-1]
return self.render_object_dump(items, title, repr)
def dump_locals(self, d):
items = [(key, self.repr(value)) for key, value in d.items()]
return self.render_object_dump(items, 'Local variables in frame')
def render_object_dump(self, items, title, repr=None):
html_items = []
for key, value in items:
html_items.append('<tr><th>%s<td><pre class=repr>%s</pre>' %
(escape(key), value))
if not html_items:
html_items.append('<tr><td><em>Nothing</em>')
return OBJECT_DUMP_HTML % {
'title': escape(title),
'repr': repr and '<pre class=repr>%s</pre>' % repr or '',
'items': '\n'.join(html_items)
}
|
alessandrolandim/liblightbase | refs/heads/master | liblightbase/lbmetaclass.py | 4 | # -*- coding: utf-8 -*-
from . import pytypes
class LBMetaClass(object):
""" This the metaclass, where all lightbase
classes will be generated from
"""
_structure = []
def __init__(self, *kwargs):
""" Create pytypes instances of all values in _structure
"""
for attr in self._structure:
typeclass = pytypes.get_lbtype(attr['type'])
setattr(self, attr['name'], typeclass(name=attr['name'], value=attr.get('value',None)))
def __setattr__(self, attr, value):
""" When setting an attribute, if it is a lbtype,
set the lbtype value instead
"""
method = getattr(self,attr,None)
if method and pytypes.is_lbtype(method):
self[attr] = value
else:
object.__setattr__(self, attr, value)
def __get_lbtype_attr__(self, attr):
""" Returns the attribute if the attribute
is an lbtype
"""
attr = getattr(self,attr)
if not pytypes.is_lbtype(attr):
raise KeyError('%s is not a valid lbtype attribute' %attr)
return attr
def __getitem__(self, attr):
""" When working as a dict, this class return the lbtype value
"""
return self.__get_lbtype_attr__(attr).value
def __setitem__(self, attr, value):
""" When working as a dict, this class sets the lbtype value
"""
self.__get_lbtype_attr__(attr).value = value
def __delitem__(self, attr):
""" When working as a dict, this class del the lbtype attribute
"""
attr = self.__get_lbtype_attr__(attr)
del attr
def generate_class(name, structure):
""" Generate a child class from LBMetaClass
"""
class new_class(LBMetaClass): pass
new_class.__name__ = name
new_class._structure = structure
return new_class
|
mikel-egana-aranguren/SADI-Galaxy-Docker | refs/heads/master | galaxy-dist/lib/galaxy/model/migrate/versions/0025_user_info.py | 1 | """
This script adds a foreign key to the form_values table in the galaxy_user table
"""
from sqlalchemy import *
from sqlalchemy.orm import *
from migrate import *
from migrate.changeset import *
import datetime
now = datetime.datetime.utcnow
import sys, logging
# Need our custom types, but don't import anything else from model
from galaxy.model.custom_types import *
log = logging.getLogger( __name__ )
log.setLevel(logging.DEBUG)
handler = logging.StreamHandler( sys.stdout )
format = "%(name)s %(levelname)s %(asctime)s %(message)s"
formatter = logging.Formatter( format )
handler.setFormatter( formatter )
log.addHandler( handler )
metadata = MetaData()
def display_migration_details():
print "========================================"
print "This script adds a foreign key to the form_values table in the galaxy_user table"
print "========================================"
def upgrade(migrate_engine):
metadata.bind = migrate_engine
display_migration_details()
# Load existing tables
metadata.reflect()
try:
User_table = Table( "galaxy_user", metadata, autoload=True )
except NoSuchTableError:
User_table = None
log.debug( "Failed loading table galaxy_user" )
if User_table is not None:
try:
col = Column( "form_values_id", Integer, index=True )
col.create( User_table, index_name='ix_user_form_values_id')
assert col is User_table.c.form_values_id
except Exception, e:
log.debug( "Adding column 'form_values_id' to galaxy_user table failed: %s" % ( str( e ) ) )
try:
FormValues_table = Table( "form_values", metadata, autoload=True )
except NoSuchTableError:
FormValues_table = None
log.debug( "Failed loading table form_values" )
if migrate_engine.name != 'sqlite':
# Add 1 foreign key constraint to the form_values table
if User_table is not None and FormValues_table is not None:
try:
cons = ForeignKeyConstraint( [User_table.c.form_values_id],
[FormValues_table.c.id],
name='user_form_values_id_fk' )
# Create the constraint
cons.create()
except Exception, e:
log.debug( "Adding foreign key constraint 'user_form_values_id_fk' to table 'galaxy_user' failed: %s" % ( str( e ) ) )
def downgrade(migrate_engine):
metadata.bind = migrate_engine
pass
|
0verl0ad/pyJuanker | refs/heads/master | scripts/xssUrl.py | 1 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
# by @aetsu
#
# Use: xssUrl.py url <payloads dictionary>
#
import requests
import urlparse
import sys
url = sys.argv[1]
if len(sys.argv) < 3:
payloads = ['<script>alert(1);</script>']
else:
filename = sys.argv[2]
payloads = [line.rstrip('\n') for line in open(filename)]
parsed = urlparse.urlparse(url)
parameters = urlparse.parse_qs(parsed.query)
newurl = urlparse.urljoin(parsed.scheme + "://" + parsed.netloc, parsed.path)
print ""
print "Url : " + url
for payload in payloads:
for p in parameters:
parameters[p] = payload
try:
req = requests.get(newurl, params=parameters)
if payload in req.text:
print "The url " + url
print "is possibly vulnerable!"
print "Payload: " + payload
break
except:
print "Error opening " + url
break
print ""
|
mitsuhiko/sqlalchemy | refs/heads/master | test/orm/inheritance/test_selects.py | 3 | from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy import testing
from sqlalchemy.testing import fixtures
class InheritingSelectablesTest(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global foo, bar, baz
foo = Table('foo', metadata,
Column('a', String(30), primary_key=1),
Column('b', String(30), nullable=0))
bar = foo.select(foo.c.b == 'bar').alias('bar')
baz = foo.select(foo.c.b == 'baz').alias('baz')
def test_load(self):
# TODO: add persistence test also
testing.db.execute(foo.insert(), a='not bar', b='baz')
testing.db.execute(foo.insert(), a='also not bar', b='baz')
testing.db.execute(foo.insert(), a='i am bar', b='bar')
testing.db.execute(foo.insert(), a='also bar', b='bar')
class Foo(fixtures.ComparableEntity): pass
class Bar(Foo): pass
class Baz(Foo): pass
mapper(Foo, foo, polymorphic_on=foo.c.b)
mapper(Baz, baz,
with_polymorphic=('*', foo.join(baz, foo.c.b=='baz').alias('baz')),
inherits=Foo,
inherit_condition=(foo.c.a==baz.c.a),
inherit_foreign_keys=[baz.c.a],
polymorphic_identity='baz')
mapper(Bar, bar,
with_polymorphic=('*', foo.join(bar, foo.c.b=='bar').alias('bar')),
inherits=Foo,
inherit_condition=(foo.c.a==bar.c.a),
inherit_foreign_keys=[bar.c.a],
polymorphic_identity='bar')
s = sessionmaker(bind=testing.db)()
assert [Baz(), Baz(), Bar(), Bar()] == s.query(Foo).order_by(Foo.b.desc()).all()
assert [Bar(), Bar()] == s.query(Bar).all()
|
DreamerKing/LightweightHtmlWidgets | refs/heads/master | LightweightHtmlWidgets/bin/Release/Ipy.Lib/code.py | 256 | """Utilities needed to emulate Python's interactive interpreter.
"""
# Inspired by similar code by Jeff Epler and Fredrik Lundh.
import sys
import traceback
from codeop import CommandCompiler, compile_command
__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact",
"compile_command"]
def softspace(file, newvalue):
oldvalue = 0
try:
oldvalue = file.softspace
except AttributeError:
pass
try:
file.softspace = newvalue
except (AttributeError, TypeError):
# "attribute-less object" or "read-only attributes"
pass
return oldvalue
class InteractiveInterpreter:
"""Base class for InteractiveConsole.
This class deals with parsing and interpreter state (the user's
namespace); it doesn't deal with input buffering or prompting or
input file naming (the filename is always passed in explicitly).
"""
def __init__(self, locals=None):
"""Constructor.
The optional 'locals' argument specifies the dictionary in
which code will be executed; it defaults to a newly created
dictionary with key "__name__" set to "__console__" and key
"__doc__" set to None.
"""
if locals is None:
locals = {"__name__": "__console__", "__doc__": None}
self.locals = locals
self.compile = CommandCompiler()
def runsource(self, source, filename="<input>", symbol="single"):
"""Compile and run some source in the interpreter.
Arguments are as for compile_command().
One several things can happen:
1) The input is incorrect; compile_command() raised an
exception (SyntaxError or OverflowError). A syntax traceback
will be printed by calling the showsyntaxerror() method.
2) The input is incomplete, and more input is required;
compile_command() returned None. Nothing happens.
3) The input is complete; compile_command() returned a code
object. The code is executed by calling self.runcode() (which
also handles run-time exceptions, except for SystemExit).
The return value is True in case 2, False in the other cases (unless
an exception is raised). The return value can be used to
decide whether to use sys.ps1 or sys.ps2 to prompt the next
line.
"""
try:
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Case 1
self.showsyntaxerror(filename)
return False
if code is None:
# Case 2
return True
# Case 3
self.runcode(code)
return False
def runcode(self, code):
"""Execute a code object.
When an exception occurs, self.showtraceback() is called to
display a traceback. All exceptions are caught except
SystemExit, which is reraised.
A note about KeyboardInterrupt: this exception may occur
elsewhere in this code, and may not always be caught. The
caller should be prepared to deal with it.
"""
try:
exec code in self.locals
except SystemExit:
raise
except:
self.showtraceback()
else:
if softspace(sys.stdout, 0):
print
def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred.
This doesn't display a stack trace because there isn't one.
If a filename is given, it is stuffed in the exception instead
of what was there before (because Python's parser always uses
"<string>" when reading from a string).
The output is written by self.write(), below.
"""
type, value, sys.last_traceback = sys.exc_info()
sys.last_type = type
sys.last_value = value
if filename and type is SyntaxError:
# Work hard to stuff the correct filename in the exception
try:
msg, (dummy_filename, lineno, offset, line) = value
except:
# Not the format we expect; leave it alone
pass
else:
# Stuff in the right filename
value = SyntaxError(msg, (filename, lineno, offset, line))
sys.last_value = value
list = traceback.format_exception_only(type, value)
map(self.write, list)
def showtraceback(self):
"""Display the exception that just occurred.
We remove the first stack item because it is our own code.
The output is written by self.write(), below.
"""
try:
type, value, tb = sys.exc_info()
sys.last_type = type
sys.last_value = value
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist[:1]
list = traceback.format_list(tblist)
if list:
list.insert(0, "Traceback (most recent call last):\n")
list[len(list):] = traceback.format_exception_only(type, value)
finally:
tblist = tb = None
map(self.write, list)
def write(self, data):
"""Write a string.
The base implementation writes to sys.stderr; a subclass may
replace this with a different implementation.
"""
sys.stderr.write(data)
class InteractiveConsole(InteractiveInterpreter):
"""Closely emulate the behavior of the interactive Python interpreter.
This class builds on InteractiveInterpreter and adds prompting
using the familiar sys.ps1 and sys.ps2, and input buffering.
"""
def __init__(self, locals=None, filename="<console>"):
"""Constructor.
The optional locals argument will be passed to the
InteractiveInterpreter base class.
The optional filename argument should specify the (file)name
of the input stream; it will show up in tracebacks.
"""
InteractiveInterpreter.__init__(self, locals)
self.filename = filename
self.resetbuffer()
def resetbuffer(self):
"""Reset the input buffer."""
self.buffer = []
def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.raw_input(prompt)
# Can be None if sys.stdin was redefined
encoding = getattr(sys.stdin, "encoding", None)
if encoding and not isinstance(line, unicode):
line = line.decode(encoding)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
def push(self, line):
"""Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
interpreter's runsource() method is called with the
concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
with in some way (this is the same as runsource()).
"""
self.buffer.append(line)
source = "\n".join(self.buffer)
more = self.runsource(source, self.filename)
if not more:
self.resetbuffer()
return more
def raw_input(self, prompt=""):
"""Write a prompt and read a line.
The returned line does not include the trailing newline.
When the user enters the EOF key sequence, EOFError is raised.
The base implementation uses the built-in function
raw_input(); a subclass may replace this with a different
implementation.
"""
return raw_input(prompt)
def interact(banner=None, readfunc=None, local=None):
"""Closely emulate the interactive Python interpreter.
This is a backwards compatible interface to the InteractiveConsole
class. When readfunc is not specified, it attempts to import the
readline module to enable GNU readline if it is available.
Arguments (all optional, all default to None):
banner -- passed to InteractiveConsole.interact()
readfunc -- if not None, replaces InteractiveConsole.raw_input()
local -- passed to InteractiveInterpreter.__init__()
"""
console = InteractiveConsole(local)
if readfunc is not None:
console.raw_input = readfunc
else:
try:
import readline
except ImportError:
pass
console.interact(banner)
if __name__ == "__main__":
interact()
|
DarkPrince304/MozDef | refs/heads/master | alerts/sshbruteforce_bro_pyes.py | 7 | #!/usr/bin/env python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2014 Mozilla Corporation
#
# Contributors:
# Michal Purzynski michal@mozilla.com
from lib.alerttask import AlertTask
import pyes
class AlertSSHManyConns(AlertTask):
def main(self):
# look for events in last 15 mins
date_timedelta = dict(minutes=15)
# Configure filters using pyes
must = [
pyes.TermFilter('_type', 'bro'),
pyes.TermFilter('eventsource', 'nsm'),
pyes.TermFilter('category', 'bronotice'),
pyes.ExistsFilter('details.sourceipaddress'),
pyes.QueryFilter(pyes.MatchQuery('details.note','SSH::Password_Guessing','phrase')),
]
self.filtersManual(date_timedelta, must=must)
# Search events
self.searchEventsSimple()
self.walkEvents()
# Set alert properties
def onEvent(self, event):
category = 'bruteforce'
tags = ['http']
severity = 'NOTICE'
hostname = event['_source']['hostname']
url = "https://mana.mozilla.org/wiki/display/SECURITY/NSM+IR+procedures"
# the summary of the alert is the same as the event
summary = '{0} {1}'.format(hostname, event['_source']['summary'])
# Create the alert object based on these properties
return self.createAlertDict(summary, category, tags, [event], severity=severity, url=url)
|
Etxea/gestioneide | refs/heads/master | gestioneide/migrations/0073_auto_20210618_1503.py | 1 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-06-18 13:03
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('gestioneide', '0072_centro_precio_matricula'),
]
operations = [
migrations.RemoveField(
model_name='turismoasignatura',
name='curso',
),
migrations.RemoveField(
model_name='turismoasignatura',
name='profesor',
),
migrations.RemoveField(
model_name='turismoasistencia',
name='alumno',
),
migrations.RemoveField(
model_name='turismoasistencia',
name='asignatura',
),
migrations.RemoveField(
model_name='turismoclase',
name='asignatura',
),
migrations.RemoveField(
model_name='turismoclase',
name='aula',
),
migrations.RemoveField(
model_name='turismoclase',
name='profesor',
),
migrations.RemoveField(
model_name='turismocurso',
name='year',
),
migrations.RemoveField(
model_name='turismofalta',
name='asistencia',
),
migrations.RemoveField(
model_name='turismojustificada',
name='asistencia',
),
migrations.RemoveField(
model_name='turismopresencia',
name='asistencia',
),
migrations.DeleteModel(
name='TurismoAsignatura',
),
migrations.DeleteModel(
name='TurismoAsistencia',
),
migrations.DeleteModel(
name='TurismoClase',
),
migrations.DeleteModel(
name='TurismoCurso',
),
migrations.DeleteModel(
name='TurismoFalta',
),
migrations.DeleteModel(
name='TurismoJustificada',
),
migrations.DeleteModel(
name='TurismoPresencia',
),
]
|
FusionSP/android_external_chromium_org | refs/heads/lp5.1 | tools/git/mffr.py | 167 | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Usage: mffr.py [-d] [-g *.h] [-g *.cc] REGEXP REPLACEMENT
This tool performs a fast find-and-replace operation on files in
the current git repository.
The -d flag selects a default set of globs (C++ and Objective-C/C++
source files). The -g flag adds a single glob to the list and may
be used multiple times. If neither -d nor -g is specified, the tool
searches all files (*.*).
REGEXP uses full Python regexp syntax. REPLACEMENT can use
back-references.
"""
import optparse
import re
import subprocess
import sys
# We need to use shell=True with subprocess on Windows so that it
# finds 'git' from the path, but can lead to undesired behavior on
# Linux.
_USE_SHELL = (sys.platform == 'win32')
def MultiFileFindReplace(original, replacement, file_globs):
"""Implements fast multi-file find and replace.
Given an |original| string and a |replacement| string, find matching
files by running git grep on |original| in files matching any
pattern in |file_globs|.
Once files are found, |re.sub| is run to replace |original| with
|replacement|. |replacement| may use capture group back-references.
Args:
original: '(#(include|import)\s*["<])chrome/browser/ui/browser.h([>"])'
replacement: '\1chrome/browser/ui/browser/browser.h\3'
file_globs: ['*.cc', '*.h', '*.m', '*.mm']
Returns the list of files modified.
Raises an exception on error.
"""
# Posix extended regular expressions do not reliably support the "\s"
# shorthand.
posix_ere_original = re.sub(r"\\s", "[[:space:]]", original)
if sys.platform == 'win32':
posix_ere_original = posix_ere_original.replace('"', '""')
out, err = subprocess.Popen(
['git', 'grep', '-E', '--name-only', posix_ere_original,
'--'] + file_globs,
stdout=subprocess.PIPE,
shell=_USE_SHELL).communicate()
referees = out.splitlines()
for referee in referees:
with open(referee) as f:
original_contents = f.read()
contents = re.sub(original, replacement, original_contents)
if contents == original_contents:
raise Exception('No change in file %s although matched in grep' %
referee)
with open(referee, 'wb') as f:
f.write(contents)
return referees
def main():
parser = optparse.OptionParser(usage='''
(1) %prog <options> REGEXP REPLACEMENT
REGEXP uses full Python regexp syntax. REPLACEMENT can use back-references.
(2) %prog <options> -i <file>
<file> should contain a list (in Python syntax) of
[REGEXP, REPLACEMENT, [GLOBS]] lists, e.g.:
[
[r"(foo|bar)", r"\1baz", ["*.cc", "*.h"]],
["54", "42"],
]
As shown above, [GLOBS] can be omitted for a given search-replace list, in which
case the corresponding search-replace will use the globs specified on the
command line.''')
parser.add_option('-d', action='store_true',
dest='use_default_glob',
help='Perform the change on C++ and Objective-C(++) source '
'and header files.')
parser.add_option('-f', action='store_true',
dest='force_unsafe_run',
help='Perform the run even if there are uncommitted local '
'changes.')
parser.add_option('-g', action='append',
type='string',
default=[],
metavar="<glob>",
dest='user_supplied_globs',
help='Perform the change on the specified glob. Can be '
'specified multiple times, in which case the globs are '
'unioned.')
parser.add_option('-i', "--input_file",
type='string',
action='store',
default='',
metavar="<file>",
dest='input_filename',
help='Read arguments from <file> rather than the command '
'line. NOTE: To be sure of regular expressions being '
'interpreted correctly, use raw strings.')
opts, args = parser.parse_args()
if opts.use_default_glob and opts.user_supplied_globs:
print '"-d" and "-g" cannot be used together'
parser.print_help()
return 1
from_file = opts.input_filename != ""
if (from_file and len(args) != 0) or (not from_file and len(args) != 2):
parser.print_help()
return 1
if not opts.force_unsafe_run:
out, err = subprocess.Popen(['git', 'status', '--porcelain'],
stdout=subprocess.PIPE,
shell=_USE_SHELL).communicate()
if out:
print 'ERROR: This tool does not print any confirmation prompts,'
print 'so you should only run it with a clean staging area and cache'
print 'so that reverting a bad find/replace is as easy as running'
print ' git checkout -- .'
print ''
print 'To override this safeguard, pass the -f flag.'
return 1
global_file_globs = ['*.*']
if opts.use_default_glob:
global_file_globs = ['*.cc', '*.h', '*.m', '*.mm']
elif opts.user_supplied_globs:
global_file_globs = opts.user_supplied_globs
# Construct list of search-replace tasks.
search_replace_tasks = []
if opts.input_filename == '':
original = args[0]
replacement = args[1]
search_replace_tasks.append([original, replacement, global_file_globs])
else:
f = open(opts.input_filename)
search_replace_tasks = eval("".join(f.readlines()))
for task in search_replace_tasks:
if len(task) == 2:
task.append(global_file_globs)
f.close()
for (original, replacement, file_globs) in search_replace_tasks:
print 'File globs: %s' % file_globs
print 'Original: %s' % original
print 'Replacement: %s' % replacement
MultiFileFindReplace(original, replacement, file_globs)
return 0
if __name__ == '__main__':
sys.exit(main())
|
andela-ifageyinbo/django | refs/heads/master | tests/utils_tests/test_crypto.py | 447 | from __future__ import unicode_literals
import binascii
import hashlib
import unittest
from django.utils.crypto import constant_time_compare, pbkdf2
class TestUtilsCryptoMisc(unittest.TestCase):
def test_constant_time_compare(self):
# It's hard to test for constant time, just test the result.
self.assertTrue(constant_time_compare(b'spam', b'spam'))
self.assertFalse(constant_time_compare(b'spam', b'eggs'))
self.assertTrue(constant_time_compare('spam', 'spam'))
self.assertFalse(constant_time_compare('spam', 'eggs'))
class TestUtilsCryptoPBKDF2(unittest.TestCase):
# http://tools.ietf.org/html/draft-josefsson-pbkdf2-test-vectors-06
rfc_vectors = [
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 1,
"dklen": 20,
"digest": hashlib.sha1,
},
"result": "0c60c80f961f0e71f3a9b524af6012062fe037a6",
},
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 2,
"dklen": 20,
"digest": hashlib.sha1,
},
"result": "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957",
},
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 4096,
"dklen": 20,
"digest": hashlib.sha1,
},
"result": "4b007901b765489abead49d926f721d065a429c1",
},
# # this takes way too long :(
# {
# "args": {
# "password": "password",
# "salt": "salt",
# "iterations": 16777216,
# "dklen": 20,
# "digest": hashlib.sha1,
# },
# "result": "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984",
# },
{
"args": {
"password": "passwordPASSWORDpassword",
"salt": "saltSALTsaltSALTsaltSALTsaltSALTsalt",
"iterations": 4096,
"dklen": 25,
"digest": hashlib.sha1,
},
"result": "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038",
},
{
"args": {
"password": "pass\0word",
"salt": "sa\0lt",
"iterations": 4096,
"dklen": 16,
"digest": hashlib.sha1,
},
"result": "56fa6aa75548099dcc37d7f03425e0c3",
},
]
regression_vectors = [
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 1,
"dklen": 20,
"digest": hashlib.sha256,
},
"result": "120fb6cffcf8b32c43e7225256c4f837a86548c9",
},
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 1,
"dklen": 20,
"digest": hashlib.sha512,
},
"result": "867f70cf1ade02cff3752599a3a53dc4af34c7a6",
},
{
"args": {
"password": "password",
"salt": "salt",
"iterations": 1000,
"dklen": 0,
"digest": hashlib.sha512,
},
"result": ("afe6c5530785b6cc6b1c6453384731bd5ee432ee"
"549fd42fb6695779ad8a1c5bf59de69c48f774ef"
"c4007d5298f9033c0241d5ab69305e7b64eceeb8d"
"834cfec"),
},
# Check leading zeros are not stripped (#17481)
{
"args": {
"password": b'\xba',
"salt": "salt",
"iterations": 1,
"dklen": 20,
"digest": hashlib.sha1,
},
"result": '0053d3b91a7f1e54effebd6d68771e8a6e0b2c5b',
},
]
def test_public_vectors(self):
for vector in self.rfc_vectors:
result = pbkdf2(**vector['args'])
self.assertEqual(binascii.hexlify(result).decode('ascii'),
vector['result'])
def test_regression_vectors(self):
for vector in self.regression_vectors:
result = pbkdf2(**vector['args'])
self.assertEqual(binascii.hexlify(result).decode('ascii'),
vector['result'])
|
sungkim11/mhargadh | refs/heads/master | django/contrib/localflavor/cl/forms.py | 201 | """
Chile specific form helpers.
"""
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import RegexField, Select
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_unicode
class CLRegionSelect(Select):
"""
A Select widget that uses a list of Chilean Regions (Regiones)
as its choices.
"""
def __init__(self, attrs=None):
from cl_regions import REGION_CHOICES
super(CLRegionSelect, self).__init__(attrs, choices=REGION_CHOICES)
class CLRutField(RegexField):
"""
Chilean "Rol Unico Tributario" (RUT) field. This is the Chilean national
identification number.
Samples for testing are available from
https://palena.sii.cl/cvc/dte/ee_empresas_emisoras.html
"""
default_error_messages = {
'invalid': _('Enter a valid Chilean RUT.'),
'strict': _('Enter a valid Chilean RUT. The format is XX.XXX.XXX-X.'),
'checksum': _('The Chilean RUT is not valid.'),
}
def __init__(self, *args, **kwargs):
if 'strict' in kwargs:
del kwargs['strict']
super(CLRutField, self).__init__(r'^(\d{1,2}\.)?\d{3}\.\d{3}-[\dkK]$',
error_message=self.default_error_messages['strict'], *args, **kwargs)
else:
# In non-strict mode, accept RUTs that validate but do not exist in
# the real world.
super(CLRutField, self).__init__(r'^[\d\.]{1,11}-?[\dkK]$', *args, **kwargs)
def clean(self, value):
"""
Check and clean the Chilean RUT.
"""
super(CLRutField, self).clean(value)
if value in EMPTY_VALUES:
return u''
rut, verificador = self._canonify(value)
if self._algorithm(rut) == verificador:
return self._format(rut, verificador)
else:
raise ValidationError(self.error_messages['checksum'])
def _algorithm(self, rut):
"""
Takes RUT in pure canonical form, calculates the verifier digit.
"""
suma = 0
multi = 2
for r in rut[::-1]:
suma += int(r) * multi
multi += 1
if multi == 8:
multi = 2
return u'0123456789K0'[11 - suma % 11]
def _canonify(self, rut):
"""
Turns the RUT into one normalized format. Returns a (rut, verifier)
tuple.
"""
rut = smart_unicode(rut).replace(' ', '').replace('.', '').replace('-', '')
return rut[:-1], rut[-1].upper()
def _format(self, code, verifier=None):
"""
Formats the RUT from canonical form to the common string representation.
If verifier=None, then the last digit in 'code' is the verifier.
"""
if verifier is None:
verifier = code[-1]
code = code[:-1]
while len(code) > 3 and '.' not in code[:3]:
pos = code.find('.')
if pos == -1:
new_dot = -3
else:
new_dot = pos - 3
code = code[:new_dot] + '.' + code[new_dot:]
return u'%s-%s' % (code, verifier)
|
aomelchenko/python_koans | refs/heads/master | python2/koans/about_lists.py | 2 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Based on AboutArrays in the Ruby Koans
#
from runner.koan import *
class AboutLists(Koan):
def test_creating_lists(self):
empty_list = list()
self.assertEqual(list, type(empty_list))
self.assertEqual(0, len(empty_list))
def test_list_literals(self):
nums = list()
self.assertEqual([], nums)
nums[0:] = [1]
self.assertEqual([1], nums)
nums[1:] = [2]
self.assertEqual([1, 2], nums)
nums.append(333)
self.assertEqual([1, 2, 333], nums)
def test_accessing_list_elements(self):
noms = ['peanut', 'butter', 'and', 'jelly']
self.assertEqual('peanut', noms[0])
self.assertEqual('jelly', noms[3])
self.assertEqual('jelly', noms[-1])
self.assertEqual('butter', noms[-3])
def test_slicing_lists(self):
noms = ['peanut', 'butter', 'and', 'jelly']
self.assertEqual(['peanut'], noms[0:1])
self.assertEqual(['peanut', 'butter'], noms[0:2])
self.assertEqual([], noms[2:2])
self.assertEqual(['and', 'jelly'], noms[2:20])
self.assertEqual([], noms[4:0])
self.assertEqual([], noms[4:100])
self.assertEqual([], noms[5:0])
def test_slicing_to_the_edge(self):
noms = ['peanut', 'butter', 'and', 'jelly']
self.assertEqual(['and', 'jelly'], noms[2:])
self.assertEqual(['peanut', 'butter'], noms[:2])
def test_lists_and_ranges(self):
self.assertEqual(list, type(range(5)))
self.assertEqual([0, 1, 2, 3, 4], range(5))
self.assertEqual([5, 6, 7, 8], range(5, 9))
def test_ranges_with_steps(self):
self.assertEqual([0, 2, 4, 6], range(0, 8, 2))
self.assertEqual([1, 4, 7], range(1, 8, 3))
self.assertEqual([5, 1, -3], range(5, -7, -4))
self.assertEqual([5, 1, -3, -7], range(5, -8, -4))
def test_insertions(self):
knight = ['you', 'shall', 'pass']
knight.insert(2, 'not')
self.assertEqual(['you', 'shall', 'not', 'pass'], knight)
knight.insert(0, 'Arthur')
self.assertEqual(['Arthur', 'you', 'shall', 'not', 'pass'], knight)
def test_popping_lists(self):
stack = [10, 20, 30, 40]
stack.append('last')
self.assertEqual([10, 20, 30, 40, 'last'], stack)
popped_value = stack.pop()
self.assertEqual('last', popped_value)
self.assertEqual([10, 20, 30, 40], stack)
popped_value = stack.pop(1)
self.assertEqual(20, popped_value)
self.assertEqual([10, 30, 40], stack)
# Notice that there is a "pop" but no "push" in python?
# Part of the Python philosophy is that there ideally should be one and
# only one way of doing anything. A 'push' is the same as an 'append'.
# To learn more about this try typing "import this" from the python
# console... ;)
def test_use_deques_for_making_queues(self):
from collections import deque
queue = deque([1, 2])
queue.append('last')
self.assertEqual([1, 2, 'last'], list(queue))
popped_value = queue.popleft()
self.assertEqual(1, popped_value)
self.assertEqual([2, 'last'], list(queue))
|
Universal-Model-Converter/UMC3.0a | refs/heads/master | data/Python/x86/Lib/site-packages/pygame/tests/cursors_test.py | 18 | #################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
if is_pygame_pkg:
from pygame.tests.test_utils \
import test_not_implemented, fixture_path, unittest
else:
from test.test_utils \
import test_not_implemented, fixture_path, unittest
import pygame
################################################################################
class CursorsModuleTest(unittest.TestCase):
def todo_test_compile(self):
# __doc__ (as of 2008-06-25) for pygame.cursors.compile:
# pygame.cursors.compile(strings, black, white,xor) -> data, mask
# compile cursor strings into cursor data
#
# This takes a set of strings with equal length and computes
# the binary data for that cursor. The string widths must be
# divisible by 8.
#
# The black and white arguments are single letter strings that
# tells which characters will represent black pixels, and which
# characters represent white pixels. All other characters are
# considered clear.
#
# This returns a tuple containing the cursor data and cursor mask
# data. Both these arguments are used when setting a cursor with
# pygame.mouse.set_cursor().
self.fail()
def test_load_xbm(self):
# __doc__ (as of 2008-06-25) for pygame.cursors.load_xbm:
# pygame.cursors.load_xbm(cursorfile, maskfile) -> cursor_args
# reads a pair of XBM files into set_cursor arguments
#
# Arguments can either be filenames or filelike objects
# with the readlines method. Not largely tested, but
# should work with typical XBM files.
# Test that load_xbm will take filenames as arguments
cursorfile = fixture_path(r"xbm_cursors/white_sizing.xbm")
maskfile = fixture_path(r"xbm_cursors/white_sizing_mask.xbm")
cursor = pygame.cursors.load_xbm(cursorfile, maskfile)
# Test that load_xbm will take file objects as arguments
cursorfile, maskfile = [open(pth) for pth in (cursorfile, maskfile)]
cursor = pygame.cursors.load_xbm(cursorfile, maskfile)
# Is it in a format that mouse.set_cursor won't blow up on?
pygame.display.init()
pygame.mouse.set_cursor(*cursor)
pygame.display.quit()
################################################################################
if __name__ == '__main__':
unittest.main()
################################################################################
|
ttm/oscEmRede | refs/heads/master | venv/lib/python2.7/site-packages/networkx/linalg/attrmatrix.py | 78 | """
Functions for constructing matrix-like objects from graph attributes.
"""
__all__ = ['attr_matrix', 'attr_sparse_matrix']
import networkx as nx
def _node_value(G, node_attr):
"""Returns a function that returns a value from G.node[u].
We return a function expecting a node as its sole argument. Then, in the
simplest scenario, the returned function will return G.node[u][node_attr].
However, we also handle the case when `node_attr` is None or when it is a
function itself.
Parameters
----------
G : graph
A NetworkX graph
node_attr : {None, str, callable}
Specification of how the value of the node attribute should be obtained
from the node attribute dictionary.
Returns
-------
value : function
A function expecting a node as its sole argument. The function will
returns a value from G.node[u] that depends on `edge_attr`.
"""
if node_attr is None:
value = lambda u: u
elif not hasattr(node_attr, '__call__'):
# assume it is a key for the node attribute dictionary
value = lambda u: G.node[u][node_attr]
else:
# Advanced: Allow users to specify something else.
#
# For example,
# node_attr = lambda u: G.node[u].get('size', .5) * 3
#
value = node_attr
return value
def _edge_value(G, edge_attr):
"""Returns a function that returns a value from G[u][v].
Suppose there exists an edge between u and v. Then we return a function
expecting u and v as arguments. For Graph and DiGraph, G[u][v] is
the edge attribute dictionary, and the function (essentially) returns
G[u][v][edge_attr]. However, we also handle cases when `edge_attr` is None
and when it is a function itself. For MultiGraph and MultiDiGraph, G[u][v]
is a dictionary of all edges between u and v. In this case, the returned
function sums the value of `edge_attr` for every edge between u and v.
Parameters
----------
G : graph
A NetworkX graph
edge_attr : {None, str, callable}
Specification of how the value of the edge attribute should be obtained
from the edge attribute dictionary, G[u][v]. For multigraphs, G[u][v]
is a dictionary of all the edges between u and v. This allows for
special treatment of multiedges.
Returns
-------
value : function
A function expecting two nodes as parameters. The nodes should
represent the from- and to- node of an edge. The function will
return a value from G[u][v] that depends on `edge_attr`.
"""
if edge_attr is None:
# topological count of edges
if G.is_multigraph():
value = lambda u,v: len(G[u][v])
else:
value = lambda u,v: 1
elif not hasattr(edge_attr, '__call__'):
# assume it is a key for the edge attribute dictionary
if edge_attr == 'weight':
# provide a default value
if G.is_multigraph():
value = lambda u,v: sum([d.get(edge_attr, 1) for d in G[u][v].values()])
else:
value = lambda u,v: G[u][v].get(edge_attr, 1)
else:
# otherwise, the edge attribute MUST exist for each edge
if G.is_multigraph():
value = lambda u,v: sum([d[edge_attr] for d in G[u][v].values()])
else:
value = lambda u,v: G[u][v][edge_attr]
else:
# Advanced: Allow users to specify something else.
#
# Alternative default value:
# edge_attr = lambda u,v: G[u][v].get('thickness', .5)
#
# Function on an attribute:
# edge_attr = lambda u,v: abs(G[u][v]['weight'])
#
# Handle Multi(Di)Graphs differently:
# edge_attr = lambda u,v: numpy.prod([d['size'] for d in G[u][v].values()])
#
# Ignore multiple edges
# edge_attr = lambda u,v: 1 if len(G[u][v]) else 0
#
value = edge_attr
return value
def attr_matrix(G, edge_attr=None, node_attr=None, normalized=False,
rc_order=None, dtype=None, order=None):
"""Returns a NumPy matrix using attributes from G.
If only `G` is passed in, then the adjacency matrix is constructed.
Let A be a discrete set of values for the node attribute `node_attr`. Then
the elements of A represent the rows and columns of the constructed matrix.
Now, iterate through every edge e=(u,v) in `G` and consider the value
of the edge attribute `edge_attr`. If ua and va are the values of the
node attribute `node_attr` for u and v, respectively, then the value of
the edge attribute is added to the matrix element at (ua, va).
Parameters
----------
G : graph
The NetworkX graph used to construct the NumPy matrix.
edge_attr : str, optional
Each element of the matrix represents a running total of the
specified edge attribute for edges whose node attributes correspond
to the rows/cols of the matirx. The attribute must be present for
all edges in the graph. If no attribute is specified, then we
just count the number of edges whose node attributes correspond
to the matrix element.
node_attr : str, optional
Each row and column in the matrix represents a particular value
of the node attribute. The attribute must be present for all nodes
in the graph. Note, the values of this attribute should be reliably
hashable. So, float values are not recommended. If no attribute is
specified, then the rows and columns will be the nodes of the graph.
normalized : bool, optional
If True, then each row is normalized by the summation of its values.
rc_order : list, optional
A list of the node attribute values. This list specifies the ordering
of rows and columns of the array. If no ordering is provided, then
the ordering will be random (and also, a return value).
Other Parameters
----------------
dtype : NumPy data-type, optional
A valid NumPy dtype used to initialize the array. Keep in mind certain
dtypes can yield unexpected results if the array is to be normalized.
The parameter is passed to numpy.zeros(). If unspecified, the NumPy
default is used.
order : {'C', 'F'}, optional
Whether to store multidimensional data in C- or Fortran-contiguous
(row- or column-wise) order in memory. This parameter is passed to
numpy.zeros(). If unspecified, the NumPy default is used.
Returns
-------
M : NumPy matrix
The attribute matrix.
ordering : list
If `rc_order` was specified, then only the matrix is returned.
However, if `rc_order` was None, then the ordering used to construct
the matrix is returned as well.
Examples
--------
Construct an adjacency matrix:
>>> G = nx.Graph()
>>> G.add_edge(0,1,thickness=1,weight=3)
>>> G.add_edge(0,2,thickness=2)
>>> G.add_edge(1,2,thickness=3)
>>> nx.attr_matrix(G, rc_order=[0,1,2])
matrix([[ 0., 1., 1.],
[ 1., 0., 1.],
[ 1., 1., 0.]])
Alternatively, we can obtain the matrix describing edge thickness.
>>> nx.attr_matrix(G, edge_attr='thickness', rc_order=[0,1,2])
matrix([[ 0., 1., 2.],
[ 1., 0., 3.],
[ 2., 3., 0.]])
We can also color the nodes and ask for the probability distribution over
all edges (u,v) describing:
Pr(v has color Y | u has color X)
>>> G.node[0]['color'] = 'red'
>>> G.node[1]['color'] = 'red'
>>> G.node[2]['color'] = 'blue'
>>> rc = ['red', 'blue']
>>> nx.attr_matrix(G, node_attr='color', normalized=True, rc_order=rc)
matrix([[ 0.33333333, 0.66666667],
[ 1. , 0. ]])
For example, the above tells us that for all edges (u,v):
Pr( v is red | u is red) = 1/3
Pr( v is blue | u is red) = 2/3
Pr( v is red | u is blue) = 1
Pr( v is blue | u is blue) = 0
Finally, we can obtain the total weights listed by the node colors.
>>> nx.attr_matrix(G, edge_attr='weight', node_attr='color', rc_order=rc)
matrix([[ 3., 2.],
[ 2., 0.]])
Thus, the total weight over all edges (u,v) with u and v having colors:
(red, red) is 3 # the sole contribution is from edge (0,1)
(red, blue) is 2 # contributions from edges (0,2) and (1,2)
(blue, red) is 2 # same as (red, blue) since graph is undirected
(blue, blue) is 0 # there are no edges with blue endpoints
"""
try:
import numpy as np
except ImportError:
raise ImportError(
"attr_matrix() requires numpy: http://scipy.org/ ")
edge_value = _edge_value(G, edge_attr)
node_value = _node_value(G, node_attr)
if rc_order is None:
ordering = list(set([node_value(n) for n in G]))
else:
ordering = rc_order
N = len(ordering)
undirected = not G.is_directed()
index = dict(zip(ordering, range(N)))
M = np.zeros((N,N), dtype=dtype, order=order)
seen = set([])
for u,nbrdict in G.adjacency_iter():
for v in nbrdict:
# Obtain the node attribute values.
i, j = index[node_value(u)], index[node_value(v)]
if v not in seen:
M[i,j] += edge_value(u,v)
if undirected:
M[j,i] = M[i,j]
if undirected:
seen.add(u)
if normalized:
M /= M.sum(axis=1).reshape((N,1))
M = np.asmatrix(M)
if rc_order is None:
return M, ordering
else:
return M
def attr_sparse_matrix(G, edge_attr=None, node_attr=None,
normalized=False, rc_order=None, dtype=None):
"""Returns a SciPy sparse matrix using attributes from G.
If only `G` is passed in, then the adjacency matrix is constructed.
Let A be a discrete set of values for the node attribute `node_attr`. Then
the elements of A represent the rows and columns of the constructed matrix.
Now, iterate through every edge e=(u,v) in `G` and consider the value
of the edge attribute `edge_attr`. If ua and va are the values of the
node attribute `node_attr` for u and v, respectively, then the value of
the edge attribute is added to the matrix element at (ua, va).
Parameters
----------
G : graph
The NetworkX graph used to construct the NumPy matrix.
edge_attr : str, optional
Each element of the matrix represents a running total of the
specified edge attribute for edges whose node attributes correspond
to the rows/cols of the matirx. The attribute must be present for
all edges in the graph. If no attribute is specified, then we
just count the number of edges whose node attributes correspond
to the matrix element.
node_attr : str, optional
Each row and column in the matrix represents a particular value
of the node attribute. The attribute must be present for all nodes
in the graph. Note, the values of this attribute should be reliably
hashable. So, float values are not recommended. If no attribute is
specified, then the rows and columns will be the nodes of the graph.
normalized : bool, optional
If True, then each row is normalized by the summation of its values.
rc_order : list, optional
A list of the node attribute values. This list specifies the ordering
of rows and columns of the array. If no ordering is provided, then
the ordering will be random (and also, a return value).
Other Parameters
----------------
dtype : NumPy data-type, optional
A valid NumPy dtype used to initialize the array. Keep in mind certain
dtypes can yield unexpected results if the array is to be normalized.
The parameter is passed to numpy.zeros(). If unspecified, the NumPy
default is used.
Returns
-------
M : SciPy sparse matrix
The attribute matrix.
ordering : list
If `rc_order` was specified, then only the matrix is returned.
However, if `rc_order` was None, then the ordering used to construct
the matrix is returned as well.
Examples
--------
Construct an adjacency matrix:
>>> G = nx.Graph()
>>> G.add_edge(0,1,thickness=1,weight=3)
>>> G.add_edge(0,2,thickness=2)
>>> G.add_edge(1,2,thickness=3)
>>> M = nx.attr_sparse_matrix(G, rc_order=[0,1,2])
>>> M.todense()
matrix([[ 0., 1., 1.],
[ 1., 0., 1.],
[ 1., 1., 0.]])
Alternatively, we can obtain the matrix describing edge thickness.
>>> M = nx.attr_sparse_matrix(G, edge_attr='thickness', rc_order=[0,1,2])
>>> M.todense()
matrix([[ 0., 1., 2.],
[ 1., 0., 3.],
[ 2., 3., 0.]])
We can also color the nodes and ask for the probability distribution over
all edges (u,v) describing:
Pr(v has color Y | u has color X)
>>> G.node[0]['color'] = 'red'
>>> G.node[1]['color'] = 'red'
>>> G.node[2]['color'] = 'blue'
>>> rc = ['red', 'blue']
>>> M = nx.attr_sparse_matrix(G, node_attr='color', \
normalized=True, rc_order=rc)
>>> M.todense()
matrix([[ 0.33333333, 0.66666667],
[ 1. , 0. ]])
For example, the above tells us that for all edges (u,v):
Pr( v is red | u is red) = 1/3
Pr( v is blue | u is red) = 2/3
Pr( v is red | u is blue) = 1
Pr( v is blue | u is blue) = 0
Finally, we can obtain the total weights listed by the node colors.
>>> M = nx.attr_sparse_matrix(G, edge_attr='weight',\
node_attr='color', rc_order=rc)
>>> M.todense()
matrix([[ 3., 2.],
[ 2., 0.]])
Thus, the total weight over all edges (u,v) with u and v having colors:
(red, red) is 3 # the sole contribution is from edge (0,1)
(red, blue) is 2 # contributions from edges (0,2) and (1,2)
(blue, red) is 2 # same as (red, blue) since graph is undirected
(blue, blue) is 0 # there are no edges with blue endpoints
"""
try:
import numpy as np
from scipy import sparse
except ImportError:
raise ImportError(
"attr_sparse_matrix() requires scipy: http://scipy.org/ ")
edge_value = _edge_value(G, edge_attr)
node_value = _node_value(G, node_attr)
if rc_order is None:
ordering = list(set([node_value(n) for n in G]))
else:
ordering = rc_order
N = len(ordering)
undirected = not G.is_directed()
index = dict(zip(ordering, range(N)))
M = sparse.lil_matrix((N,N), dtype=dtype)
seen = set([])
for u,nbrdict in G.adjacency_iter():
for v in nbrdict:
# Obtain the node attribute values.
i, j = index[node_value(u)], index[node_value(v)]
if v not in seen:
M[i,j] += edge_value(u,v)
if undirected:
M[j,i] = M[i,j]
if undirected:
seen.add(u)
if normalized:
norms = np.asarray(M.sum(axis=1)).ravel()
for i,norm in enumerate(norms):
M[i,:] /= norm
if rc_order is None:
return M, ordering
else:
return M
# fixture for nose tests
def setup_module(module):
from nose import SkipTest
try:
import numpy
except:
raise SkipTest("NumPy not available")
try:
import scipy
except:
raise SkipTest("SciPy not available")
|
Communities-Communications/cc-odoo | refs/heads/master | addons/account/wizard/account_tax_chart.py | 385 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class account_tax_chart(osv.osv_memory):
"""
For Chart of taxes
"""
_name = "account.tax.chart"
_description = "Account tax chart"
_columns = {
'period_id': fields.many2one('account.period', \
'Period', \
),
'target_move': fields.selection([('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Target Moves', required=True),
}
def _get_period(self, cr, uid, context=None):
"""Return default period value"""
period_ids = self.pool.get('account.period').find(cr, uid, context=context)
return period_ids and period_ids[0] or False
def account_tax_chart_open_window(self, cr, uid, ids, context=None):
"""
Opens chart of Accounts
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: List of account chart’s IDs
@return: dictionary of Open account chart window on given fiscalyear and all Entries or posted entries
"""
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
if context is None:
context = {}
data = self.browse(cr, uid, ids, context=context)[0]
result = mod_obj.get_object_reference(cr, uid, 'account', 'action_tax_code_tree')
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context=context)[0]
if data.period_id:
result['context'] = str({'period_id': data.period_id.id, \
'fiscalyear_id': data.period_id.fiscalyear_id.id, \
'state': data.target_move})
period_code = data.period_id.code
result['name'] += period_code and (':' + period_code) or ''
else:
result['context'] = str({'state': data.target_move})
return result
_defaults = {
'period_id': _get_period,
'target_move': 'posted'
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
wfxiang08/green | refs/heads/master | green/cmdline.py | 1 | from __future__ import unicode_literals
import os
import sys
try: # pragma: no cover
import coverage
coverage_version = "Coverage {}".format(coverage.__version__)
except: # pragma: no cover
coverage = None
coverage_version = "Coverage Not Installed"
# Importing from green (other than config) is done after coverage initialization
import green.config as config
def main(testing=False, coverage_testing=False):
args = config.parseArguments()
args = config.mergeConfig(args, testing, coverage_testing)
if args.shouldExit:
return args.exitCode
# Clear out all the passed-in-options just in case someone tries to run a
# test that assumes sys.argv is clean. I can't guess at the script name
# that they want, though, so we'll just leave ours.
sys.argv = sys.argv[:1]
# Set up our various main objects
from green.loader import loadTargets
from green.runner import run
from green.output import GreenStream, debug
import green.output
from green.suite import GreenTestSuite
GreenTestSuite.args = args
if args.debug:
green.output.debug_level = args.debug
stream = GreenStream(sys.stdout)
# Location of shell completion file
if args.completion_file:
print(os.path.join(os.path.dirname(__file__), 'shell_completion.sh'))
return 0
# Argument-completion for bash and zsh (for test-target completion)
if args.completions:
from green.loader import getCompletions
print(getCompletions(args.targets))
return 0
# Option-completion for bash and zsh
if args.options:
print('\n'.join(sorted(args.store_opt.options)))
return 0
# Add debug logging for stuff that happened before this point here
if config.files_loaded:
debug("Loaded config file(s): {}".format(
', '.join(config.files_loaded)))
# Discover/Load the test suite
if testing:
test_suite = None
else: # pragma: no cover
test_suite = loadTargets(args.targets, file_pattern = args.file_pattern)
# We didn't even load 0 tests...
if not test_suite:
debug(
"No test loading attempts succeeded. Created an empty test suite.")
test_suite = GreenTestSuite()
# Actually run the test_suite
if testing:
result = lambda: None
result.wasSuccessful = lambda: 0
else:
result = run(test_suite, stream, args) # pragma: no cover
if args.run_coverage and ((not testing) or coverage_testing):
stream.writeln()
args.cov.stop()
args.cov.save()
args.cov.combine()
args.cov.save()
args.cov.report(file=stream, omit=args.omit_patterns)
return(int(not result.wasSuccessful()))
if __name__ == '__main__': # pragma: no cover
sys.exit(main())
|
andela-earinde/bellatrix-py | refs/heads/master | app/js/lib/lib/modules/greenlet.py | 2 | import sys
import _continuation
__version__ = "0.4.7"
# ____________________________________________________________
# Exceptions
class GreenletExit(BaseException):
"""This special exception does not propagate to the parent greenlet; it
can be used to kill a single greenlet."""
error = _continuation.error
# ____________________________________________________________
# Helper function
def getcurrent():
"Returns the current greenlet (i.e. the one which called this function)."
try:
return _tls.current
except AttributeError:
# first call in this thread: current == main
_green_create_main()
return _tls.current
# ____________________________________________________________
# The 'greenlet' class
_continulet = _continuation.continulet
class greenlet(_continulet):
getcurrent = staticmethod(getcurrent)
error = error
GreenletExit = GreenletExit
__main = False
__started = False
def __new__(cls, *args, **kwds):
self = _continulet.__new__(cls)
self.parent = getcurrent()
return self
def __init__(self, run=None, parent=None):
if run is not None:
self.run = run
if parent is not None:
self.parent = parent
def switch(self, *args, **kwds):
"Switch execution to this greenlet, optionally passing the values "
"given as argument(s). Returns the value passed when switching back."
return self.__switch('switch', (args, kwds))
def throw(self, typ=GreenletExit, val=None, tb=None):
"raise exception in greenlet, return value passed when switching back"
return self.__switch('throw', typ, val, tb)
def __switch(target, methodname, *baseargs):
current = getcurrent()
#
while not (target.__main or _continulet.is_pending(target)):
# inlined __nonzero__ ^^^ in case it's overridden
if not target.__started:
if methodname == 'switch':
greenlet_func = _greenlet_start
else:
greenlet_func = _greenlet_throw
_continulet.__init__(target, greenlet_func, *baseargs)
methodname = 'switch'
baseargs = ()
target.__started = True
break
# already done, go to the parent instead
# (NB. infinite loop possible, but unlikely, unless you mess
# up the 'parent' explicitly. Good enough, because a Ctrl-C
# will show that the program is caught in this loop here.)
target = target.parent
# convert a "raise GreenletExit" into "return GreenletExit"
if methodname == 'throw':
try:
raise baseargs[0], baseargs[1]
except GreenletExit, e:
methodname = 'switch'
baseargs = (((e,), {}),)
except:
baseargs = sys.exc_info()[:2] + baseargs[2:]
#
try:
unbound_method = getattr(_continulet, methodname)
args, kwds = unbound_method(current, *baseargs, to=target)
finally:
_tls.current = current
#
if kwds:
if args:
return args, kwds
return kwds
elif len(args) == 1:
return args[0]
else:
return args
def __nonzero__(self):
return self.__main or _continulet.is_pending(self)
@property
def dead(self):
return self.__started and not self
@property
def gr_frame(self):
# xxx this doesn't work when called on either the current or
# the main greenlet of another thread
if self is getcurrent():
return None
if self.__main:
self = getcurrent()
f = _continulet.__reduce__(self)[2][0]
if not f:
return None
return f.f_back.f_back.f_back # go past start(), __switch(), switch()
# ____________________________________________________________
# Internal stuff
try:
from threading import local as _local
except ImportError:
class _local(object): # assume no threads
pass
_tls = _local()
def _green_create_main():
# create the main greenlet for this thread
_tls.current = None
gmain = greenlet.__new__(greenlet)
gmain._greenlet__main = True
gmain._greenlet__started = True
assert gmain.parent is None
_tls.main = gmain
_tls.current = gmain
def _greenlet_start(greenlet, args):
args, kwds = args
_tls.current = greenlet
try:
res = greenlet.run(*args, **kwds)
except GreenletExit, e:
res = e
finally:
_continuation.permute(greenlet, greenlet.parent)
return ((res,), None)
def _greenlet_throw(greenlet, exc, value, tb):
_tls.current = greenlet
try:
raise exc, value, tb
except GreenletExit, e:
res = e
finally:
_continuation.permute(greenlet, greenlet.parent)
return ((res,), None)
|
google/oauth2client | refs/heads/master | tests/test_file.py | 15 | # Copyright 2014 Google Inc. All rights reserved.
#
# 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.
"""Unit tests for oauth2client.file."""
import copy
import datetime
import json
import os
import pickle
import stat
import tempfile
import unittest
import warnings
import mock
import six
from six.moves import http_client
from six.moves import urllib_parse
from oauth2client import _helpers
from oauth2client import client
from oauth2client import file as file_module
from oauth2client import transport
from tests import http_mock
try:
# Python2
from future_builtins import oct
except ImportError: # pragma: NO COVER
pass
_filehandle, FILENAME = tempfile.mkstemp('oauth2client_test.data')
os.close(_filehandle)
class OAuth2ClientFileTests(unittest.TestCase):
def tearDown(self):
try:
os.unlink(FILENAME)
except OSError:
pass
def setUp(self):
warnings.simplefilter("ignore")
try:
os.unlink(FILENAME)
except OSError:
pass
def _create_test_credentials(self, client_id='some_client_id',
expiration=None):
access_token = 'foo'
client_secret = 'cOuDdkfjxxnv+'
refresh_token = '1/0/a.df219fjls0'
token_expiry = expiration or datetime.datetime.utcnow()
token_uri = 'https://www.google.com/accounts/o8/oauth2/token'
user_agent = 'refresh_checker/1.0'
credentials = client.OAuth2Credentials(
access_token, client_id, client_secret,
refresh_token, token_expiry, token_uri,
user_agent)
return credentials
@mock.patch('warnings.warn')
def test_non_existent_file_storage(self, warn_mock):
storage = file_module.Storage(FILENAME)
credentials = storage.get()
warn_mock.assert_called_with(
_helpers._MISSING_FILE_MESSAGE.format(FILENAME))
self.assertIsNone(credentials)
def test_directory_file_storage(self):
storage = file_module.Storage(FILENAME)
os.mkdir(FILENAME)
try:
with self.assertRaises(IOError):
storage.get()
finally:
os.rmdir(FILENAME)
@unittest.skipIf(not hasattr(os, 'symlink'), 'No symlink available')
def test_no_sym_link_credentials(self):
SYMFILENAME = FILENAME + '.sym'
os.symlink(FILENAME, SYMFILENAME)
storage = file_module.Storage(SYMFILENAME)
try:
with self.assertRaises(IOError):
storage.get()
finally:
os.unlink(SYMFILENAME)
def test_pickle_and_json_interop(self):
# Write a file with a pickled OAuth2Credentials.
credentials = self._create_test_credentials()
credentials_file = open(FILENAME, 'wb')
pickle.dump(credentials, credentials_file)
credentials_file.close()
# Storage should be not be able to read that object, as the capability
# to read and write credentials as pickled objects has been removed.
storage = file_module.Storage(FILENAME)
read_credentials = storage.get()
self.assertIsNone(read_credentials)
# Now write it back out and confirm it has been rewritten as JSON
storage.put(credentials)
with open(FILENAME) as credentials_file:
data = json.load(credentials_file)
self.assertEquals(data['access_token'], 'foo')
self.assertEquals(data['_class'], 'OAuth2Credentials')
self.assertEquals(data['_module'], client.OAuth2Credentials.__module__)
def test_token_refresh_store_expired(self):
expiration = (datetime.datetime.utcnow() -
datetime.timedelta(minutes=15))
credentials = self._create_test_credentials(expiration=expiration)
storage = file_module.Storage(FILENAME)
storage.put(credentials)
credentials = storage.get()
new_cred = copy.copy(credentials)
new_cred.access_token = 'bar'
storage.put(new_cred)
access_token = '1/3w'
token_response = {'access_token': access_token, 'expires_in': 3600}
response_content = json.dumps(token_response).encode('utf-8')
http = http_mock.HttpMock(data=response_content)
credentials._refresh(http)
self.assertEquals(credentials.access_token, access_token)
# Verify mocks.
self.assertEqual(http.requests, 1)
self.assertEqual(http.uri, credentials.token_uri)
self.assertEqual(http.method, 'POST')
expected_body = {
'grant_type': ['refresh_token'],
'client_id': [credentials.client_id],
'client_secret': [credentials.client_secret],
'refresh_token': [credentials.refresh_token],
}
self.assertEqual(urllib_parse.parse_qs(http.body), expected_body)
expected_headers = {
'content-type': 'application/x-www-form-urlencoded',
'user-agent': credentials.user_agent,
}
self.assertEqual(http.headers, expected_headers)
def test_token_refresh_store_expires_soon(self):
# Tests the case where an access token that is valid when it is read
# from the store expires before the original request succeeds.
expiration = (datetime.datetime.utcnow() +
datetime.timedelta(minutes=15))
credentials = self._create_test_credentials(expiration=expiration)
storage = file_module.Storage(FILENAME)
storage.put(credentials)
credentials = storage.get()
new_cred = copy.copy(credentials)
new_cred.access_token = 'bar'
storage.put(new_cred)
access_token = '1/3w'
token_response = {'access_token': access_token, 'expires_in': 3600}
http = http_mock.HttpMockSequence([
({'status': http_client.UNAUTHORIZED},
b'Initial token expired'),
({'status': http_client.UNAUTHORIZED},
b'Store token expired'),
({'status': http_client.OK},
json.dumps(token_response).encode('utf-8')),
({'status': http_client.OK},
b'Valid response to original request')
])
credentials.authorize(http)
transport.request(http, 'https://example.com')
self.assertEqual(credentials.access_token, access_token)
def test_token_refresh_good_store(self):
expiration = (datetime.datetime.utcnow() +
datetime.timedelta(minutes=15))
credentials = self._create_test_credentials(expiration=expiration)
storage = file_module.Storage(FILENAME)
storage.put(credentials)
credentials = storage.get()
new_cred = copy.copy(credentials)
new_cred.access_token = 'bar'
storage.put(new_cred)
credentials._refresh(None)
self.assertEquals(credentials.access_token, 'bar')
def test_token_refresh_stream_body(self):
expiration = (datetime.datetime.utcnow() +
datetime.timedelta(minutes=15))
credentials = self._create_test_credentials(expiration=expiration)
storage = file_module.Storage(FILENAME)
storage.put(credentials)
credentials = storage.get()
new_cred = copy.copy(credentials)
new_cred.access_token = 'bar'
storage.put(new_cred)
valid_access_token = '1/3w'
token_response = {'access_token': valid_access_token,
'expires_in': 3600}
http = http_mock.HttpMockSequence([
({'status': http_client.UNAUTHORIZED},
b'Initial token expired'),
({'status': http_client.UNAUTHORIZED},
b'Store token expired'),
({'status': http_client.OK},
json.dumps(token_response).encode('utf-8')),
({'status': http_client.OK}, 'echo_request_body')
])
body = six.StringIO('streaming body')
credentials.authorize(http)
_, content = transport.request(http, 'https://example.com', body=body)
self.assertEqual(content, 'streaming body')
self.assertEqual(credentials.access_token, valid_access_token)
def test_credentials_delete(self):
credentials = self._create_test_credentials()
storage = file_module.Storage(FILENAME)
storage.put(credentials)
credentials = storage.get()
self.assertIsNotNone(credentials)
storage.delete()
credentials = storage.get()
self.assertIsNone(credentials)
def test_access_token_credentials(self):
access_token = 'foo'
user_agent = 'refresh_checker/1.0'
credentials = client.AccessTokenCredentials(access_token, user_agent)
storage = file_module.Storage(FILENAME)
credentials = storage.put(credentials)
credentials = storage.get()
self.assertIsNotNone(credentials)
self.assertEquals('foo', credentials.access_token)
self.assertTrue(os.path.exists(FILENAME))
if os.name == 'posix': # pragma: NO COVER
mode = os.stat(FILENAME).st_mode
self.assertEquals('0o600', oct(stat.S_IMODE(mode)))
|
GaetanCambier/CouchPotatoServer | refs/heads/develop | libs/requests/packages/chardet/compat.py | 2942 | ######################## BEGIN LICENSE BLOCK ########################
# Contributor(s):
# Ian Cordasco - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
import sys
if sys.version_info < (3, 0):
base_str = (str, unicode)
else:
base_str = (bytes, str)
def wrap_ord(a):
if sys.version_info < (3, 0) and isinstance(a, base_str):
return ord(a)
else:
return a
|
rjkerrison/ranking | refs/heads/master | classes/contest.py | 1 | import json
import hashlib
class Contest():
def __init__(self, *args, **kwargs):
self.contestants = []
self.outcome = ''
if len(args) >= 2:
self.contestants = frozenset(args[:2])
if len(args) >= 3:
self.outcome = args[2]
if 'contestants' in kwargs:
self.contestants = frozenset(kwargs['contestants'])
if 'outcome' in kwargs:
self.outcome = kwargs['outcome']
self._id = self._generate_unique_id()
def __eq__(self, a):
return (
isinstance(a, Contest)
and a.contestants == self.contestants
and a.outcome == self.outcome
)
def _generate_unique_id(self):
json_to_encode = json.dumps(list(self.contestants))
encoded_json = json_to_encode.encode('ascii')
return hashlib.sha1(encoded_json).hexdigest()
def as_dict(self):
return {
'_id': self._id,
'contestants': list(self.contestants),
'outcome': self.outcome
}
def as_json(self):
return json.dumps(self.as_dict())
@staticmethod
def from_json(json_contest):
return Contest(**json.loads(json_contest))
|
zsiciarz/django | refs/heads/master | tests/multiple_database/routers.py | 48 | from django.db import DEFAULT_DB_ALIAS
class TestRouter:
"""
Vaguely behave like primary/replica, but the databases aren't assumed to
propagate changes.
"""
def db_for_read(self, model, instance=None, **hints):
if instance:
return instance._state.db or 'other'
return 'other'
def db_for_write(self, model, **hints):
return DEFAULT_DB_ALIAS
def allow_relation(self, obj1, obj2, **hints):
return obj1._state.db in ('default', 'other') and obj2._state.db in ('default', 'other')
def allow_migrate(self, db, app_label, **hints):
return True
class AuthRouter:
"""
Control all database operations on models in the contrib.auth application.
"""
def db_for_read(self, model, **hints):
"Point all read operations on auth models to 'default'"
if model._meta.app_label == 'auth':
# We use default here to ensure we can tell the difference
# between a read request and a write request for Auth objects
return 'default'
return None
def db_for_write(self, model, **hints):
"Point all operations on auth models to 'other'"
if model._meta.app_label == 'auth':
return 'other'
return None
def allow_relation(self, obj1, obj2, **hints):
"Allow any relation if a model in Auth is involved"
if obj1._meta.app_label == 'auth' or obj2._meta.app_label == 'auth':
return True
return None
def allow_migrate(self, db, app_label, **hints):
"Make sure the auth app only appears on the 'other' db"
if app_label == 'auth':
return db == 'other'
return None
class WriteRouter:
# A router that only expresses an opinion on writes
def db_for_write(self, model, **hints):
return 'writer'
|
Anlim/decode-Django | refs/heads/master | Django-1.5.1/django/core/mail/backends/console.py | 137 | """
Email backend that writes messages to console instead of sending them.
"""
import sys
import threading
from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend):
def __init__(self, *args, **kwargs):
self.stream = kwargs.pop('stream', sys.stdout)
self._lock = threading.RLock()
super(EmailBackend, self).__init__(*args, **kwargs)
def send_messages(self, email_messages):
"""Write all messages to the stream in a thread-safe way."""
if not email_messages:
return
with self._lock:
try:
stream_created = self.open()
for message in email_messages:
self.stream.write('%s\n' % message.message().as_string())
self.stream.write('-' * 79)
self.stream.write('\n')
self.stream.flush() # flush after each message
if stream_created:
self.close()
except:
if not self.fail_silently:
raise
return len(email_messages)
|
aslamplr/shorts | refs/heads/master | lib/werkzeug/contrib/sessions.py | 315 | # -*- coding: utf-8 -*-
r"""
werkzeug.contrib.sessions
~~~~~~~~~~~~~~~~~~~~~~~~~
This module contains some helper classes that help one to add session
support to a python WSGI application. For full client-side session
storage see :mod:`~werkzeug.contrib.securecookie` which implements a
secure, client-side session storage.
Application Integration
=======================
::
from werkzeug.contrib.sessions import SessionMiddleware, \
FilesystemSessionStore
app = SessionMiddleware(app, FilesystemSessionStore())
The current session will then appear in the WSGI environment as
`werkzeug.session`. However it's recommended to not use the middleware
but the stores directly in the application. However for very simple
scripts a middleware for sessions could be sufficient.
This module does not implement methods or ways to check if a session is
expired. That should be done by a cronjob and storage specific. For
example to prune unused filesystem sessions one could check the modified
time of the files. It sessions are stored in the database the new()
method should add an expiration timestamp for the session.
For better flexibility it's recommended to not use the middleware but the
store and session object directly in the application dispatching::
session_store = FilesystemSessionStore()
def application(environ, start_response):
request = Request(environ)
sid = request.cookies.get('cookie_name')
if sid is None:
request.session = session_store.new()
else:
request.session = session_store.get(sid)
response = get_the_response_object(request)
if request.session.should_save:
session_store.save(request.session)
response.set_cookie('cookie_name', request.session.sid)
return response(environ, start_response)
:copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import re
import os
import sys
import tempfile
from os import path
from time import time
from random import random
from hashlib import sha1
from pickle import dump, load, HIGHEST_PROTOCOL
from werkzeug.datastructures import CallbackDict
from werkzeug.utils import dump_cookie, parse_cookie
from werkzeug.wsgi import ClosingIterator
from werkzeug.posixemulation import rename
from werkzeug._compat import PY2, text_type
_sha1_re = re.compile(r'^[a-f0-9]{40}$')
def _urandom():
if hasattr(os, 'urandom'):
return os.urandom(30)
return random()
def generate_key(salt=None):
if salt is None:
salt = repr(salt).encode('ascii')
return sha1(b''.join([
salt,
str(time()).encode('ascii'),
_urandom()
])).hexdigest()
class ModificationTrackingDict(CallbackDict):
__slots__ = ('modified',)
def __init__(self, *args, **kwargs):
def on_update(self):
self.modified = True
self.modified = False
CallbackDict.__init__(self, on_update=on_update)
dict.update(self, *args, **kwargs)
def copy(self):
"""Create a flat copy of the dict."""
missing = object()
result = object.__new__(self.__class__)
for name in self.__slots__:
val = getattr(self, name, missing)
if val is not missing:
setattr(result, name, val)
return result
def __copy__(self):
return self.copy()
class Session(ModificationTrackingDict):
"""Subclass of a dict that keeps track of direct object changes. Changes
in mutable structures are not tracked, for those you have to set
`modified` to `True` by hand.
"""
__slots__ = ModificationTrackingDict.__slots__ + ('sid', 'new')
def __init__(self, data, sid, new=False):
ModificationTrackingDict.__init__(self, data)
self.sid = sid
self.new = new
def __repr__(self):
return '<%s %s%s>' % (
self.__class__.__name__,
dict.__repr__(self),
self.should_save and '*' or ''
)
@property
def should_save(self):
"""True if the session should be saved.
.. versionchanged:: 0.6
By default the session is now only saved if the session is
modified, not if it is new like it was before.
"""
return self.modified
class SessionStore(object):
"""Baseclass for all session stores. The Werkzeug contrib module does not
implement any useful stores besides the filesystem store, application
developers are encouraged to create their own stores.
:param session_class: The session class to use. Defaults to
:class:`Session`.
"""
def __init__(self, session_class=None):
if session_class is None:
session_class = Session
self.session_class = session_class
def is_valid_key(self, key):
"""Check if a key has the correct format."""
return _sha1_re.match(key) is not None
def generate_key(self, salt=None):
"""Simple function that generates a new session key."""
return generate_key(salt)
def new(self):
"""Generate a new session."""
return self.session_class({}, self.generate_key(), True)
def save(self, session):
"""Save a session."""
def save_if_modified(self, session):
"""Save if a session class wants an update."""
if session.should_save:
self.save(session)
def delete(self, session):
"""Delete a session."""
def get(self, sid):
"""Get a session for this sid or a new session object. This method
has to check if the session key is valid and create a new session if
that wasn't the case.
"""
return self.session_class({}, sid, True)
#: used for temporary files by the filesystem session store
_fs_transaction_suffix = '.__wz_sess'
class FilesystemSessionStore(SessionStore):
"""Simple example session store that saves sessions on the filesystem.
This store works best on POSIX systems and Windows Vista / Windows
Server 2008 and newer.
.. versionchanged:: 0.6
`renew_missing` was added. Previously this was considered `True`,
now the default changed to `False` and it can be explicitly
deactivated.
:param path: the path to the folder used for storing the sessions.
If not provided the default temporary directory is used.
:param filename_template: a string template used to give the session
a filename. ``%s`` is replaced with the
session id.
:param session_class: The session class to use. Defaults to
:class:`Session`.
:param renew_missing: set to `True` if you want the store to
give the user a new sid if the session was
not yet saved.
"""
def __init__(self, path=None, filename_template='werkzeug_%s.sess',
session_class=None, renew_missing=False, mode=0o644):
SessionStore.__init__(self, session_class)
if path is None:
path = tempfile.gettempdir()
self.path = path
if isinstance(filename_template, text_type) and PY2:
filename_template = filename_template.encode(
sys.getfilesystemencoding() or 'utf-8')
assert not filename_template.endswith(_fs_transaction_suffix), \
'filename templates may not end with %s' % _fs_transaction_suffix
self.filename_template = filename_template
self.renew_missing = renew_missing
self.mode = mode
def get_session_filename(self, sid):
# out of the box, this should be a strict ASCII subset but
# you might reconfigure the session object to have a more
# arbitrary string.
if isinstance(sid, text_type) and PY2:
sid = sid.encode(sys.getfilesystemencoding() or 'utf-8')
return path.join(self.path, self.filename_template % sid)
def save(self, session):
fn = self.get_session_filename(session.sid)
fd, tmp = tempfile.mkstemp(suffix=_fs_transaction_suffix,
dir=self.path)
f = os.fdopen(fd, 'wb')
try:
dump(dict(session), f, HIGHEST_PROTOCOL)
finally:
f.close()
try:
rename(tmp, fn)
os.chmod(fn, self.mode)
except (IOError, OSError):
pass
def delete(self, session):
fn = self.get_session_filename(session.sid)
try:
os.unlink(fn)
except OSError:
pass
def get(self, sid):
if not self.is_valid_key(sid):
return self.new()
try:
f = open(self.get_session_filename(sid), 'rb')
except IOError:
if self.renew_missing:
return self.new()
data = {}
else:
try:
try:
data = load(f)
except Exception:
data = {}
finally:
f.close()
return self.session_class(data, sid, False)
def list(self):
"""Lists all sessions in the store.
.. versionadded:: 0.6
"""
before, after = self.filename_template.split('%s', 1)
filename_re = re.compile(r'%s(.{5,})%s$' % (re.escape(before),
re.escape(after)))
result = []
for filename in os.listdir(self.path):
#: this is a session that is still being saved.
if filename.endswith(_fs_transaction_suffix):
continue
match = filename_re.match(filename)
if match is not None:
result.append(match.group(1))
return result
class SessionMiddleware(object):
"""A simple middleware that puts the session object of a store provided
into the WSGI environ. It automatically sets cookies and restores
sessions.
However a middleware is not the preferred solution because it won't be as
fast as sessions managed by the application itself and will put a key into
the WSGI environment only relevant for the application which is against
the concept of WSGI.
The cookie parameters are the same as for the :func:`~dump_cookie`
function just prefixed with ``cookie_``. Additionally `max_age` is
called `cookie_age` and not `cookie_max_age` because of backwards
compatibility.
"""
def __init__(self, app, store, cookie_name='session_id',
cookie_age=None, cookie_expires=None, cookie_path='/',
cookie_domain=None, cookie_secure=None,
cookie_httponly=False, environ_key='werkzeug.session'):
self.app = app
self.store = store
self.cookie_name = cookie_name
self.cookie_age = cookie_age
self.cookie_expires = cookie_expires
self.cookie_path = cookie_path
self.cookie_domain = cookie_domain
self.cookie_secure = cookie_secure
self.cookie_httponly = cookie_httponly
self.environ_key = environ_key
def __call__(self, environ, start_response):
cookie = parse_cookie(environ.get('HTTP_COOKIE', ''))
sid = cookie.get(self.cookie_name, None)
if sid is None:
session = self.store.new()
else:
session = self.store.get(sid)
environ[self.environ_key] = session
def injecting_start_response(status, headers, exc_info=None):
if session.should_save:
self.store.save(session)
headers.append(('Set-Cookie', dump_cookie(self.cookie_name,
session.sid, self.cookie_age,
self.cookie_expires, self.cookie_path,
self.cookie_domain, self.cookie_secure,
self.cookie_httponly)))
return start_response(status, headers, exc_info)
return ClosingIterator(self.app(environ, injecting_start_response),
lambda: self.store.save_if_modified(session))
|
iradul/phantomjs-clone | refs/heads/master | src/qt/qtwebkit/Tools/Scripts/webkitpy/tool/steps/build.py | 119 | # Copyright (C) 2010 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import logging
from webkitpy.tool.steps.abstractstep import AbstractStep
from webkitpy.tool.steps.options import Options
_log = logging.getLogger(__name__)
class Build(AbstractStep):
@classmethod
def options(cls):
return AbstractStep.options() + [
Options.build,
Options.quiet,
Options.build_style,
]
def build(self, build_style):
environment = self._tool.copy_current_environment()
environment.disable_gcc_smartquotes()
env = environment.to_dictionary()
build_webkit_command = self._tool.deprecated_port().build_webkit_command(build_style=build_style)
self._tool.executive.run_and_throw_if_fail(build_webkit_command, self._options.quiet,
cwd=self._tool.scm().checkout_root, env=env)
def run(self, state):
if not self._options.build:
return
_log.info("Building WebKit")
if self._options.build_style == "both":
self.build("debug")
self.build("release")
else:
self.build(self._options.build_style)
|
naousse/odoo | refs/heads/8.0 | addons/crm/__init__.py | 329 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import crm
import crm_segmentation
import crm_lead
import sales_team
import calendar_event
import ir_http
import crm_phonecall
import report
import wizard
import res_partner
import res_config
import base_partner_merge
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
marratj/ansible | refs/heads/devel | lib/ansible/modules/network/panos/panos_import.py | 29 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Ansible module to manage PaloAltoNetworks Firewall
# (c) 2016, techbizdev <techbizdev@paloaltonetworks.com>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: panos_import
short_description: import file on PAN-OS devices
description:
- Import file on PAN-OS device
author: "Luigi Mori (@jtschichold), Ivan Bojer (@ivanbojer)"
version_added: "2.3"
requirements:
- pan-python
- requests
- requests_toolbelt
options:
ip_address:
description:
- IP address (or hostname) of PAN-OS device.
required: true
password:
description:
- Password for device authentication.
required: true
username:
description:
- Username for device authentication.
required: false
default: "admin"
category:
description:
- Category of file uploaded. The default is software.
required: false
default: software
file:
description:
- Location of the file to import into device.
required: false
default: None
url:
description:
- URL of the file that will be imported to device.
required: false
default: None
'''
EXAMPLES = '''
# import software image PanOS_vm-6.1.1 on 192.168.1.1
- name: import software image into PAN-OS
panos_import:
ip_address: 192.168.1.1
username: admin
password: admin
file: /tmp/PanOS_vm-6.1.1
category: software
'''
RETURN='''
# Default return values
'''
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import get_exception
import os.path
import xml.etree
import tempfile
import shutil
import os
try:
import pan.xapi
import requests
import requests_toolbelt
HAS_LIB = True
except ImportError:
HAS_LIB = False
def import_file(xapi, module, ip_address, file_, category):
xapi.keygen()
params = {
'type': 'import',
'category': category,
'key': xapi.api_key
}
filename = os.path.basename(file_)
mef = requests_toolbelt.MultipartEncoder(
fields={
'file': (filename, open(file_, 'rb'), 'application/octet-stream')
}
)
r = requests.post(
'https://'+ip_address+'/api/',
verify=False,
params=params,
headers={'Content-Type': mef.content_type},
data=mef
)
# if something goes wrong just raise an exception
r.raise_for_status()
resp = xml.etree.ElementTree.fromstring(r.content)
if resp.attrib['status'] == 'error':
module.fail_json(msg=r.content)
return True, filename
def download_file(url):
r = requests.get(url, stream=True)
fo = tempfile.NamedTemporaryFile(prefix='ai', delete=False)
shutil.copyfileobj(r.raw, fo)
fo.close()
return fo.name
def delete_file(path):
os.remove(path)
def main():
argument_spec = dict(
ip_address=dict(required=True),
password=dict(required=True, no_log=True),
username=dict(default='admin'),
category=dict(default='software'),
file=dict(),
url=dict()
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_one_of=[['file', 'url']])
if not HAS_LIB:
module.fail_json(msg='pan-python, requests, and requests_toolbelt are required for this module')
ip_address = module.params["ip_address"]
password = module.params["password"]
username = module.params['username']
xapi = pan.xapi.PanXapi(
hostname=ip_address,
api_username=username,
api_password=password
)
file_ = module.params['file']
url = module.params['url']
category = module.params['category']
# we can get file from URL or local storage
if url is not None:
file_ = download_file(url)
try:
changed, filename = import_file(xapi, module, ip_address, file_, category)
except Exception:
exc = get_exception()
module.fail_json(msg=exc.message)
# cleanup and delete file if local
if url is not None:
delete_file(file_)
module.exit_json(changed=changed, filename=filename, msg="okey dokey")
if __name__ == '__main__':
main()
|
kurli/blink-crosswalk | refs/heads/master | Tools/Scripts/webkitpy/tool/__init__.py | 6014 | # Required for Python to search this directory for module files
|
fgend31/SoCo | refs/heads/master | soco/__init__.py | 10 | # -*- coding: utf-8 -*-
"""SoCo (Sonos Controller) is a simple library to control Sonos speakers."""
# There is no need for all strings here to be unicode, and Py2 cannot import
# modules with unicode names so do not use from __future__ import
# unicode_literals
# https://github.com/SoCo/SoCo/issues/98
#
import logging
from .compat import NullHandler
from .core import SoCo
from .discovery import discover
from .exceptions import SoCoException, UnknownSoCoException
# Will be parsed by setup.py to determine package metadata
__author__ = 'The SoCo-Team <python-soco@googlegroups.com>'
__version__ = '0.11.1'
__website__ = 'https://github.com/SoCo/SoCo'
__license__ = 'MIT License'
# You really should not `import *` - it is poor practice
# but if you do, here is what you get:
__all__ = [
'discover',
'SoCo',
'SoCoException',
'UnknownSoCoException',
]
# http://docs.python.org/2/howto/logging.html#library-config
# Avoids spurious error messages if no logger is configured by the user
logging.getLogger(__name__).addHandler(NullHandler())
|
code4futuredotorg/reeborg_tw | refs/heads/master | src/libraries/Brython3.2.3/Lib/site-packages/reeborg_common_old.py | 2 | from browser import window
class ReeborgError(Exception):
def __init__(self, value):
self.reeborg_shouts = value
def __str__(self):
return repr(self.reeborg_shouts)
window['ReeborgError'] = ReeborgError
# simple help replacement as it is not working correctly imo
def Help(obj=None):
'''Usage: help(obj)'''
if obj is None:
print(Help.__doc__)
return
out = []
try:
out.append("<h2>{}</h2>".format(obj.__name__))
if hasattr(obj, "__doc__"):
out.append("<p>{}</p>".format(obj.__doc__))
else:
out.append("<p>No docstring found.</p>")
except:
pass
for attr in dir(obj):
if attr == "__class__":
continue
if hasattr(getattr(obj, attr), "__doc__"):
if getattr(obj, attr).__doc__:
out.append("<h3>{}</h3>".format(attr))
doc = "<p>{}</p>".format(getattr(obj, attr).__doc__)
out.append(doc.replace("\n", "<br>"))
if not out:
raise ReeborgError("This object has no docstring.")
else:
window.narration("".join(out))
window['Help'] = Help
def dir_py(obj):
'''Prints all "public" attributes of an object, one per line, identifying
which ones are callable by appending parentheses to their name.'''
out = []
for attr in dir(obj):
try:
if not attr.startswith("__"):
if callable(getattr(obj, attr)):
out.append(attr+"()")
else:
out.append(attr)
except AttributeError: # javascript extension, as in supplant()
pass # string prototype extension, can cause problems
print("\n".join(out))
window['dir_py'] = dir_py
|
clumsy/intellij-community | refs/heads/master | python/testData/buildout/site.py | 83 | """Append module search paths for third-party packages to sys.path.
****************************************************************
* This module is automatically imported during initialization. *
****************************************************************
In earlier versions of Python (up to 1.5a3), scripts or modules that
needed to use site-specific modules would place ``import site''
somewhere near the top of their code. Because of the automatic
import, this is no longer necessary (but code that does it still
works).
This will append site-specific paths to the module search path. On
Unix (including Mac OSX), it starts with sys.prefix and
sys.exec_prefix (if different) and appends
lib/python<version>/site-packages as well as lib/site-python.
On other platforms (such as Windows), it tries each of the
prefixes directly, as well as with lib/site-packages appended. The
resulting directories, if they exist, are appended to sys.path, and
also inspected for path configuration files.
A path configuration file is a file whose name has the form
<package>.pth; its contents are additional directories (one per line)
to be added to sys.path. Non-existing directories (or
non-directories) are never added to sys.path; no directory is added to
sys.path more than once. Blank lines and lines beginning with
'#' are skipped. Lines starting with 'import' are executed.
For example, suppose sys.prefix and sys.exec_prefix are set to
/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
with three subdirectories, foo, bar and spam, and two path
configuration files, foo.pth and bar.pth. Assume foo.pth contains the
following:
# foo package configuration
foo
bar
bletch
and bar.pth contains:
# bar package configuration
bar
Then the following directories are added to sys.path, in this order:
/usr/local/lib/python2.5/site-packages/bar
/usr/local/lib/python2.5/site-packages/foo
Note that bletch is omitted because it doesn't exist; bar precedes foo
because bar.pth comes alphabetically before foo.pth; and spam is
omitted because it is not mentioned in either path configuration file.
After these path manipulations, an attempt is made to import a module
named sitecustomize, which can perform arbitrary additional
site-specific customizations. If this import fails with an
ImportError exception, it is silently ignored.
"""
import sys
import os
import __builtin__
# Prefixes for site-packages; add additional prefixes like /usr/local here
PREFIXES = [sys.prefix, sys.exec_prefix]
# Enable per user site-packages directory
# set it to False to disable the feature or True to force the feature
ENABLE_USER_SITE = False # buildout does not support user sites.
# for distutils.commands.install
USER_SITE = None
USER_BASE = None
def makepath(*paths):
dir = os.path.abspath(os.path.join(*paths))
return dir, os.path.normcase(dir)
def abs__file__():
"""Set all module' __file__ attribute to an absolute path"""
for m in sys.modules.values():
if hasattr(m, '__loader__'):
continue # don't mess with a PEP 302-supplied __file__
try:
m.__file__ = os.path.abspath(m.__file__)
except AttributeError:
continue
def removeduppaths():
""" Remove duplicate entries from sys.path along with making them
absolute"""
# This ensures that the initial path provided by the interpreter contains
# only absolute pathnames, even if we're running from the build directory.
L = []
known_paths = set()
for dir in sys.path:
# Filter out duplicate paths (on case-insensitive file systems also
# if they only differ in case); turn relative paths into absolute
# paths.
dir, dircase = makepath(dir)
if not dircase in known_paths:
L.append(dir)
known_paths.add(dircase)
sys.path[:] = L
return known_paths
# XXX This should not be part of site.py, since it is needed even when
# using the -S option for Python. See http://www.python.org/sf/586680
def addbuilddir():
"""Append ./build/lib.<platform> in case we're running in the build dir
(especially for Guido :-)"""
from distutils.util import get_platform
s = "build/lib.%s-%.3s" % (get_platform(), sys.version)
if hasattr(sys, 'gettotalrefcount'):
s += '-pydebug'
s = os.path.join(os.path.dirname(sys.path[-1]), s)
sys.path.append(s)
def _init_pathinfo():
"""Return a set containing all existing directory entries from sys.path"""
d = set()
for dir in sys.path:
try:
if os.path.isdir(dir):
dir, dircase = makepath(dir)
d.add(dircase)
except TypeError:
continue
return d
def addpackage(sitedir, name, known_paths):
"""Process a .pth file within the site-packages directory:
For each line in the file, either combine it with sitedir to a path
and add that to known_paths, or execute it if it starts with 'import '.
"""
if known_paths is None:
_init_pathinfo()
reset = 1
else:
reset = 0
fullname = os.path.join(sitedir, name)
try:
f = open(fullname, "rU")
except IOError:
return
with f:
for line in f:
if line.startswith("#"):
continue
if line.startswith(("import ", "import\t")):
exec line
continue
line = line.rstrip()
dir, dircase = makepath(sitedir, line)
if not dircase in known_paths and os.path.exists(dir):
sys.path.append(dir)
known_paths.add(dircase)
if reset:
known_paths = None
return known_paths
def addsitedir(sitedir, known_paths=None):
"""Add 'sitedir' argument to sys.path if missing and handle .pth files in
'sitedir'"""
if known_paths is None:
known_paths = _init_pathinfo()
reset = 1
else:
reset = 0
sitedir, sitedircase = makepath(sitedir)
if not sitedircase in known_paths:
sys.path.append(sitedir) # Add path component
try:
names = os.listdir(sitedir)
except os.error:
return
dotpth = os.extsep + "pth"
names = [name for name in names if name.endswith(dotpth)]
for name in sorted(names):
addpackage(sitedir, name, known_paths)
if reset:
known_paths = None
return known_paths
def check_enableusersite():
"""Check if user site directory is safe for inclusion
The function tests for the command line flag (including environment var),
process uid/gid equal to effective uid/gid.
None: Disabled for security reasons
False: Disabled by user (command line option)
True: Safe and enabled
"""
if sys.flags.no_user_site:
return False
if hasattr(os, "getuid") and hasattr(os, "geteuid"):
# check process uid == effective uid
if os.geteuid() != os.getuid():
return None
if hasattr(os, "getgid") and hasattr(os, "getegid"):
# check process gid == effective gid
if os.getegid() != os.getgid():
return None
return True
def addusersitepackages(known_paths):
"""Add a per user site-package to sys.path
Each user has its own python directory with site-packages in the
home directory.
USER_BASE is the root directory for all Python versions
USER_SITE is the user specific site-packages directory
USER_SITE/.. can be used for data.
"""
global USER_BASE, USER_SITE, ENABLE_USER_SITE
env_base = os.environ.get("PYTHONUSERBASE", None)
def joinuser(*args):
return os.path.expanduser(os.path.join(*args))
#if sys.platform in ('os2emx', 'riscos'):
# # Don't know what to put here
# USER_BASE = ''
# USER_SITE = ''
if os.name == "nt":
base = os.environ.get("APPDATA") or "~"
USER_BASE = env_base if env_base else joinuser(base, "Python")
USER_SITE = os.path.join(USER_BASE,
"Python" + sys.version[0] + sys.version[2],
"site-packages")
else:
USER_BASE = env_base if env_base else joinuser("~", ".local")
USER_SITE = os.path.join(USER_BASE, "lib",
"python" + sys.version[:3],
"site-packages")
if ENABLE_USER_SITE and os.path.isdir(USER_SITE):
addsitedir(USER_SITE, known_paths)
return known_paths
def addsitepackages(known_paths):
"""Add site packages, as determined by zc.buildout.
See original_addsitepackages, below, for the original version."""
setuptools_path = 'c:\\src\\django\\buildout15\\eggs\\setuptools-0.6c12dev_r88124-py2.6.egg'
sys.path.append(setuptools_path)
known_paths.add(os.path.normcase(setuptools_path))
import pkg_resources
buildout_paths = [
'c:\\src\\django\\buildout15\\src',
'c:\\src\\django\\buildout15\\eggs\\setuptools-0.6c12dev_r88124-py2.6.egg'
]
for path in buildout_paths:
sitedir, sitedircase = makepath(path)
if not sitedircase in known_paths and os.path.exists(sitedir):
sys.path.append(sitedir)
known_paths.add(sitedircase)
pkg_resources.working_set.add_entry(sitedir)
sys.__egginsert = len(buildout_paths) # Support distribute.
original_paths = [
'C:\\Python26\\lib\\site-packages'
]
for path in original_paths:
if path == setuptools_path or path not in known_paths:
addsitedir(path, known_paths)
return known_paths
def original_addsitepackages(known_paths):
"""Add site-packages (and possibly site-python) to sys.path"""
sitedirs = []
seen = []
for prefix in PREFIXES:
if not prefix or prefix in seen:
continue
seen.append(prefix)
if sys.platform in ('os2emx', 'riscos'):
sitedirs.append(os.path.join(prefix, "Lib", "site-packages"))
elif os.sep == '/':
sitedirs.append(os.path.join(prefix, "lib",
"python" + sys.version[:3],
"site-packages"))
sitedirs.append(os.path.join(prefix, "lib", "site-python"))
else:
sitedirs.append(prefix)
sitedirs.append(os.path.join(prefix, "lib", "site-packages"))
if sys.platform == "darwin":
# for framework builds *only* we add the standard Apple
# locations. Currently only per-user, but /Library and
# /Network/Library could be added too
if 'Python.framework' in prefix:
sitedirs.append(
os.path.expanduser(
os.path.join("~", "Library", "Python",
sys.version[:3], "site-packages")))
for sitedir in sitedirs:
if os.path.isdir(sitedir):
addsitedir(sitedir, known_paths)
return known_paths
def setBEGINLIBPATH():
"""The OS/2 EMX port has optional extension modules that do double duty
as DLLs (and must use the .DLL file extension) for other extensions.
The library search path needs to be amended so these will be found
during module import. Use BEGINLIBPATH so that these are at the start
of the library search path.
"""
dllpath = os.path.join(sys.prefix, "Lib", "lib-dynload")
libpath = os.environ['BEGINLIBPATH'].split(';')
if libpath[-1]:
libpath.append(dllpath)
else:
libpath[-1] = dllpath
os.environ['BEGINLIBPATH'] = ';'.join(libpath)
def setquit():
"""Define new built-ins 'quit' and 'exit'.
These are simply strings that display a hint on how to exit.
"""
if os.sep == ':':
eof = 'Cmd-Q'
elif os.sep == '\\':
eof = 'Ctrl-Z plus Return'
else:
eof = 'Ctrl-D (i.e. EOF)'
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
class _Printer(object):
"""interactive prompt objects for printing the license text, a list of
contributors and the copyright notice."""
MAXLINES = 23
def __init__(self, name, data, files=(), dirs=()):
self.__name = name
self.__data = data
self.__files = files
self.__dirs = dirs
self.__lines = None
def __setup(self):
if self.__lines:
return
data = None
for dir in self.__dirs:
for filename in self.__files:
filename = os.path.join(dir, filename)
try:
fp = file(filename, "rU")
data = fp.read()
fp.close()
break
except IOError:
pass
if data:
break
if not data:
data = self.__data
self.__lines = data.split('\n')
self.__linecnt = len(self.__lines)
def __repr__(self):
self.__setup()
if len(self.__lines) <= self.MAXLINES:
return "\n".join(self.__lines)
else:
return "Type %s() to see the full %s text" % ((self.__name,)*2)
def __call__(self):
self.__setup()
prompt = 'Hit Return for more, or q (and Return) to quit: '
lineno = 0
while 1:
try:
for i in range(lineno, lineno + self.MAXLINES):
print self.__lines[i]
except IndexError:
break
else:
lineno += self.MAXLINES
key = None
while key is None:
key = raw_input(prompt)
if key not in ('', 'q'):
key = None
if key == 'q':
break
def setcopyright():
"""Set 'copyright' and 'credits' in __builtin__"""
__builtin__.copyright = _Printer("copyright", sys.copyright)
if sys.platform[:4] == 'java':
__builtin__.credits = _Printer(
"credits",
"Jython is maintained by the Jython developers (www.jython.org).")
else:
__builtin__.credits = _Printer("credits", """\
Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands
for supporting Python development. See www.python.org for more information.""")
here = os.path.dirname(os.__file__)
__builtin__.license = _Printer(
"license", "See http://www.python.org/%.3s/license.html" % sys.version,
["LICENSE.txt", "LICENSE"],
[os.path.join(here, os.pardir), here, os.curdir])
class _Helper(object):
"""Define the built-in 'help'.
This is a wrapper around pydoc.help (with a twist).
"""
def __repr__(self):
return "Type help() for interactive help, " \
"or help(object) for help about object."
def __call__(self, *args, **kwds):
import pydoc
return pydoc.help(*args, **kwds)
def sethelper():
__builtin__.help = _Helper()
def aliasmbcs():
"""On Windows, some default encodings are not provided by Python,
while they are always available as "mbcs" in each locale. Make
them usable by aliasing to "mbcs" in such a case."""
if sys.platform == 'win32':
import locale, codecs
enc = locale.getdefaultlocale()[1]
if enc.startswith('cp'): # "cp***" ?
try:
codecs.lookup(enc)
except LookupError:
import encodings
encodings._cache[enc] = encodings._unknown
encodings.aliases.aliases[enc] = 'mbcs'
def setencoding():
"""Set the string encoding used by the Unicode implementation. The
default is 'ascii', but if you're willing to experiment, you can
change this."""
encoding = "ascii" # Default value set by _PyUnicode_Init()
if 0:
# Enable to support locale aware default string encodings.
import locale
loc = locale.getdefaultlocale()
if loc[1]:
encoding = loc[1]
if 0:
# Enable to switch off string to Unicode coercion and implicit
# Unicode to string conversion.
encoding = "undefined"
if encoding != "ascii":
# On Non-Unicode builds this will raise an AttributeError...
sys.setdefaultencoding(encoding) # Needs Python Unicode build !
def execsitecustomize():
"""Run custom site specific code, if available."""
try:
import sitecustomize
except ImportError:
pass
except Exception:
if sys.flags.verbose:
sys.excepthook(*sys.exc_info())
else:
print >>sys.stderr, \
"'import sitecustomize' failed; use -v for traceback"
def execusercustomize():
"""Run custom user specific code, if available."""
try:
import usercustomize
except ImportError:
pass
except Exception:
if sys.flags.verbose:
sys.excepthook(*sys.exc_info())
else:
print>>sys.stderr, \
"'import usercustomize' failed; use -v for traceback"
def main():
global ENABLE_USER_SITE
abs__file__()
known_paths = removeduppaths()
if (os.name == "posix" and sys.path and
os.path.basename(sys.path[-1]) == "Modules"):
addbuilddir()
if ENABLE_USER_SITE is None:
ENABLE_USER_SITE = check_enableusersite()
known_paths = addusersitepackages(known_paths)
known_paths = addsitepackages(known_paths)
if sys.platform == 'os2emx':
setBEGINLIBPATH()
setquit()
setcopyright()
sethelper()
aliasmbcs()
setencoding()
execsitecustomize()
if ENABLE_USER_SITE:
execusercustomize()
# Remove sys.setdefaultencoding() so that users cannot change the
# encoding after initialization. The test for presence is needed when
# this module is run as a script, because this code is executed twice.
if hasattr(sys, "setdefaultencoding"):
del sys.setdefaultencoding
main()
def _script():
help = """\
%s [--user-base] [--user-site]
Without arguments print some useful information
With arguments print the value of USER_BASE and/or USER_SITE separated
by '%s'.
Exit codes with --user-base or --user-site:
0 - user site directory is enabled
1 - user site directory is disabled by user
2 - uses site directory is disabled by super user
or for security reasons
>2 - unknown error
"""
args = sys.argv[1:]
if not args:
print "sys.path = ["
for dir in sys.path:
print " %r," % (dir,)
print "]"
print "USER_BASE: %r (%s)" % (USER_BASE,
"exists" if os.path.isdir(USER_BASE) else "doesn't exist")
print "USER_SITE: %r (%s)" % (USER_SITE,
"exists" if os.path.isdir(USER_SITE) else "doesn't exist")
print "ENABLE_USER_SITE: %r" % ENABLE_USER_SITE
sys.exit(0)
buffer = []
if '--user-base' in args:
buffer.append(USER_BASE)
if '--user-site' in args:
buffer.append(USER_SITE)
if buffer:
print os.pathsep.join(buffer)
if ENABLE_USER_SITE:
sys.exit(0)
elif ENABLE_USER_SITE is False:
sys.exit(1)
elif ENABLE_USER_SITE is None:
sys.exit(2)
else:
sys.exit(3)
else:
import textwrap
print textwrap.dedent(help % (sys.argv[0], os.pathsep))
sys.exit(10)
if __name__ == '__main__':
_script()
|
arpitar/osf.io | refs/heads/develop | website/addons/dropbox/tests/test_webtests.py | 31 | # -*- coding: utf-8 -*-
from nose.tools import * # noqa (PEP8 asserts)
from website.util import api_url_for, web_url_for
from tests.base import OsfTestCase
from tests.factories import AuthUserFactory
class TestDropboxIntegration(OsfTestCase):
def setUp(self):
super(TestDropboxIntegration, self).setUp()
self.user = AuthUserFactory()
# User is logged in
self.app.authenticate(*self.user.auth)
def test_cant_start_oauth_if_already_authorized(self):
# User already has dropbox authorized
self.user.add_addon('dropbox')
self.user.save()
settings = self.user.get_addon('dropbox')
settings.access_token = 'abc123foobarbaz'
settings.save()
assert_true(self.user.get_addon('dropbox').has_auth)
# Tries to start oauth again
url = api_url_for('dropbox_oauth_start_user')
res = self.app.get(url).follow()
# Is redirected back to settings page
assert_equal(
res.request.path,
web_url_for('user_addons')
)
|
nbeaver/numpy | refs/heads/master | numpy/distutils/ccompiler.py | 22 | from __future__ import division, absolute_import, print_function
import os
import re
import sys
import types
from copy import copy
from distutils import ccompiler
from distutils.ccompiler import *
from distutils.errors import DistutilsExecError, DistutilsModuleError, \
DistutilsPlatformError
from distutils.sysconfig import customize_compiler
from distutils.version import LooseVersion
from numpy.distutils import log
from numpy.distutils.compat import get_exception
from numpy.distutils.exec_command import exec_command
from numpy.distutils.misc_util import cyg2win32, is_sequence, mingw32, \
quote_args, get_num_build_jobs
def replace_method(klass, method_name, func):
if sys.version_info[0] < 3:
m = types.MethodType(func, None, klass)
else:
# Py3k does not have unbound method anymore, MethodType does not work
m = lambda self, *args, **kw: func(self, *args, **kw)
setattr(klass, method_name, m)
# Using customized CCompiler.spawn.
def CCompiler_spawn(self, cmd, display=None):
"""
Execute a command in a sub-process.
Parameters
----------
cmd : str
The command to execute.
display : str or sequence of str, optional
The text to add to the log file kept by `numpy.distutils`.
If not given, `display` is equal to `cmd`.
Returns
-------
None
Raises
------
DistutilsExecError
If the command failed, i.e. the exit status was not 0.
"""
if display is None:
display = cmd
if is_sequence(display):
display = ' '.join(list(display))
log.info(display)
s, o = exec_command(cmd)
if s:
if is_sequence(cmd):
cmd = ' '.join(list(cmd))
try:
print(o)
except UnicodeError:
# When installing through pip, `o` can contain non-ascii chars
pass
if re.search('Too many open files', o):
msg = '\nTry rerunning setup command until build succeeds.'
else:
msg = ''
raise DistutilsExecError('Command "%s" failed with exit status %d%s' % (cmd, s, msg))
replace_method(CCompiler, 'spawn', CCompiler_spawn)
def CCompiler_object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
"""
Return the name of the object files for the given source files.
Parameters
----------
source_filenames : list of str
The list of paths to source files. Paths can be either relative or
absolute, this is handled transparently.
strip_dir : bool, optional
Whether to strip the directory from the returned paths. If True,
the file name prepended by `output_dir` is returned. Default is False.
output_dir : str, optional
If given, this path is prepended to the returned paths to the
object files.
Returns
-------
obj_names : list of str
The list of paths to the object files corresponding to the source
files in `source_filenames`.
"""
if output_dir is None:
output_dir = ''
obj_names = []
for src_name in source_filenames:
base, ext = os.path.splitext(os.path.normpath(src_name))
base = os.path.splitdrive(base)[1] # Chop off the drive
base = base[os.path.isabs(base):] # If abs, chop off leading /
if base.startswith('..'):
# Resolve starting relative path components, middle ones
# (if any) have been handled by os.path.normpath above.
i = base.rfind('..')+2
d = base[:i]
d = os.path.basename(os.path.abspath(d))
base = d + base[i:]
if ext not in self.src_extensions:
raise UnknownFileError("unknown file type '%s' (from '%s')" % (ext, src_name))
if strip_dir:
base = os.path.basename(base)
obj_name = os.path.join(output_dir, base + self.obj_extension)
obj_names.append(obj_name)
return obj_names
replace_method(CCompiler, 'object_filenames', CCompiler_object_filenames)
def CCompiler_compile(self, sources, output_dir=None, macros=None,
include_dirs=None, debug=0, extra_preargs=None,
extra_postargs=None, depends=None):
"""
Compile one or more source files.
Please refer to the Python distutils API reference for more details.
Parameters
----------
sources : list of str
A list of filenames
output_dir : str, optional
Path to the output directory.
macros : list of tuples
A list of macro definitions.
include_dirs : list of str, optional
The directories to add to the default include file search path for
this compilation only.
debug : bool, optional
Whether or not to output debug symbols in or alongside the object
file(s).
extra_preargs, extra_postargs : ?
Extra pre- and post-arguments.
depends : list of str, optional
A list of file names that all targets depend on.
Returns
-------
objects : list of str
A list of object file names, one per source file `sources`.
Raises
------
CompileError
If compilation fails.
"""
# This method is effective only with Python >=2.3 distutils.
# Any changes here should be applied also to fcompiler.compile
# method to support pre Python 2.3 distutils.
if not sources:
return []
# FIXME:RELATIVE_IMPORT
if sys.version_info[0] < 3:
from .fcompiler import FCompiler, is_f_file, has_f90_header
else:
from numpy.distutils.fcompiler import (FCompiler, is_f_file,
has_f90_header)
if isinstance(self, FCompiler):
display = []
for fc in ['f77', 'f90', 'fix']:
fcomp = getattr(self, 'compiler_'+fc)
if fcomp is None:
continue
display.append("Fortran %s compiler: %s" % (fc, ' '.join(fcomp)))
display = '\n'.join(display)
else:
ccomp = self.compiler_so
display = "C compiler: %s\n" % (' '.join(ccomp),)
log.info(display)
macros, objects, extra_postargs, pp_opts, build = \
self._setup_compile(output_dir, macros, include_dirs, sources,
depends, extra_postargs)
cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
display = "compile options: '%s'" % (' '.join(cc_args))
if extra_postargs:
display += "\nextra options: '%s'" % (' '.join(extra_postargs))
log.info(display)
def single_compile(args):
obj, (src, ext) = args
self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
if isinstance(self, FCompiler):
objects_to_build = list(build.keys())
f77_objects, other_objects = [], []
for obj in objects:
if obj in objects_to_build:
src, ext = build[obj]
if self.compiler_type=='absoft':
obj = cyg2win32(obj)
src = cyg2win32(src)
if is_f_file(src) and not has_f90_header(src):
f77_objects.append((obj, (src, ext)))
else:
other_objects.append((obj, (src, ext)))
# f77 objects can be built in parallel
build_items = f77_objects
# build f90 modules serial, module files are generated during
# compilation and may be used by files later in the list so the
# ordering is important
for o in other_objects:
single_compile(o)
else:
build_items = build.items()
jobs = get_num_build_jobs()
if len(build) > 1 and jobs > 1:
# build parallel
import multiprocessing.pool
pool = multiprocessing.pool.ThreadPool(jobs)
pool.map(single_compile, build_items)
pool.close()
else:
# build serial
for o in build_items:
single_compile(o)
# Return *all* object filenames, not just the ones we just built.
return objects
replace_method(CCompiler, 'compile', CCompiler_compile)
def CCompiler_customize_cmd(self, cmd, ignore=()):
"""
Customize compiler using distutils command.
Parameters
----------
cmd : class instance
An instance inheriting from `distutils.cmd.Command`.
ignore : sequence of str, optional
List of `CCompiler` commands (without ``'set_'``) that should not be
altered. Strings that are checked for are:
``('include_dirs', 'define', 'undef', 'libraries', 'library_dirs',
'rpath', 'link_objects')``.
Returns
-------
None
"""
log.info('customize %s using %s' % (self.__class__.__name__,
cmd.__class__.__name__))
def allow(attr):
return getattr(cmd, attr, None) is not None and attr not in ignore
if allow('include_dirs'):
self.set_include_dirs(cmd.include_dirs)
if allow('define'):
for (name, value) in cmd.define:
self.define_macro(name, value)
if allow('undef'):
for macro in cmd.undef:
self.undefine_macro(macro)
if allow('libraries'):
self.set_libraries(self.libraries + cmd.libraries)
if allow('library_dirs'):
self.set_library_dirs(self.library_dirs + cmd.library_dirs)
if allow('rpath'):
self.set_runtime_library_dirs(cmd.rpath)
if allow('link_objects'):
self.set_link_objects(cmd.link_objects)
replace_method(CCompiler, 'customize_cmd', CCompiler_customize_cmd)
def _compiler_to_string(compiler):
props = []
mx = 0
keys = list(compiler.executables.keys())
for key in ['version', 'libraries', 'library_dirs',
'object_switch', 'compile_switch',
'include_dirs', 'define', 'undef', 'rpath', 'link_objects']:
if key not in keys:
keys.append(key)
for key in keys:
if hasattr(compiler, key):
v = getattr(compiler, key)
mx = max(mx, len(key))
props.append((key, repr(v)))
lines = []
format = '%-' + repr(mx+1) + 's = %s'
for prop in props:
lines.append(format % prop)
return '\n'.join(lines)
def CCompiler_show_customization(self):
"""
Print the compiler customizations to stdout.
Parameters
----------
None
Returns
-------
None
Notes
-----
Printing is only done if the distutils log threshold is < 2.
"""
if 0:
for attrname in ['include_dirs', 'define', 'undef',
'libraries', 'library_dirs',
'rpath', 'link_objects']:
attr = getattr(self, attrname, None)
if not attr:
continue
log.info("compiler '%s' is set to %s" % (attrname, attr))
try:
self.get_version()
except:
pass
if log._global_log.threshold<2:
print('*'*80)
print(self.__class__)
print(_compiler_to_string(self))
print('*'*80)
replace_method(CCompiler, 'show_customization', CCompiler_show_customization)
def CCompiler_customize(self, dist, need_cxx=0):
"""
Do any platform-specific customization of a compiler instance.
This method calls `distutils.sysconfig.customize_compiler` for
platform-specific customization, as well as optionally remove a flag
to suppress spurious warnings in case C++ code is being compiled.
Parameters
----------
dist : object
This parameter is not used for anything.
need_cxx : bool, optional
Whether or not C++ has to be compiled. If so (True), the
``"-Wstrict-prototypes"`` option is removed to prevent spurious
warnings. Default is False.
Returns
-------
None
Notes
-----
All the default options used by distutils can be extracted with::
from distutils import sysconfig
sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS',
'CCSHARED', 'LDSHARED', 'SO')
"""
# See FCompiler.customize for suggested usage.
log.info('customize %s' % (self.__class__.__name__))
customize_compiler(self)
if need_cxx:
# In general, distutils uses -Wstrict-prototypes, but this option is
# not valid for C++ code, only for C. Remove it if it's there to
# avoid a spurious warning on every compilation.
try:
self.compiler_so.remove('-Wstrict-prototypes')
except (AttributeError, ValueError):
pass
if hasattr(self, 'compiler') and 'cc' in self.compiler[0]:
if not self.compiler_cxx:
if self.compiler[0].startswith('gcc'):
a, b = 'gcc', 'g++'
else:
a, b = 'cc', 'c++'
self.compiler_cxx = [self.compiler[0].replace(a, b)]\
+ self.compiler[1:]
else:
if hasattr(self, 'compiler'):
log.warn("#### %s #######" % (self.compiler,))
if not hasattr(self, 'compiler_cxx'):
log.warn('Missing compiler_cxx fix for ' + self.__class__.__name__)
return
replace_method(CCompiler, 'customize', CCompiler_customize)
def simple_version_match(pat=r'[-.\d]+', ignore='', start=''):
"""
Simple matching of version numbers, for use in CCompiler and FCompiler.
Parameters
----------
pat : str, optional
A regular expression matching version numbers.
Default is ``r'[-.\\d]+'``.
ignore : str, optional
A regular expression matching patterns to skip.
Default is ``''``, in which case nothing is skipped.
start : str, optional
A regular expression matching the start of where to start looking
for version numbers.
Default is ``''``, in which case searching is started at the
beginning of the version string given to `matcher`.
Returns
-------
matcher : callable
A function that is appropriate to use as the ``.version_match``
attribute of a `CCompiler` class. `matcher` takes a single parameter,
a version string.
"""
def matcher(self, version_string):
# version string may appear in the second line, so getting rid
# of new lines:
version_string = version_string.replace('\n', ' ')
pos = 0
if start:
m = re.match(start, version_string)
if not m:
return None
pos = m.end()
while True:
m = re.search(pat, version_string[pos:])
if not m:
return None
if ignore and re.match(ignore, m.group(0)):
pos = m.end()
continue
break
return m.group(0)
return matcher
def CCompiler_get_version(self, force=False, ok_status=[0]):
"""
Return compiler version, or None if compiler is not available.
Parameters
----------
force : bool, optional
If True, force a new determination of the version, even if the
compiler already has a version attribute. Default is False.
ok_status : list of int, optional
The list of status values returned by the version look-up process
for which a version string is returned. If the status value is not
in `ok_status`, None is returned. Default is ``[0]``.
Returns
-------
version : str or None
Version string, in the format of `distutils.version.LooseVersion`.
"""
if not force and hasattr(self, 'version'):
return self.version
self.find_executables()
try:
version_cmd = self.version_cmd
except AttributeError:
return None
if not version_cmd or not version_cmd[0]:
return None
try:
matcher = self.version_match
except AttributeError:
try:
pat = self.version_pattern
except AttributeError:
return None
def matcher(version_string):
m = re.match(pat, version_string)
if not m:
return None
version = m.group('version')
return version
status, output = exec_command(version_cmd, use_tee=0)
version = None
if status in ok_status:
version = matcher(output)
if version:
version = LooseVersion(version)
self.version = version
return version
replace_method(CCompiler, 'get_version', CCompiler_get_version)
def CCompiler_cxx_compiler(self):
"""
Return the C++ compiler.
Parameters
----------
None
Returns
-------
cxx : class instance
The C++ compiler, as a `CCompiler` instance.
"""
if self.compiler_type in ('msvc', 'intelw', 'intelemw'):
return self
cxx = copy(self)
cxx.compiler_so = [cxx.compiler_cxx[0]] + cxx.compiler_so[1:]
if sys.platform.startswith('aix') and 'ld_so_aix' in cxx.linker_so[0]:
# AIX needs the ld_so_aix script included with Python
cxx.linker_so = [cxx.linker_so[0], cxx.compiler_cxx[0]] \
+ cxx.linker_so[2:]
else:
cxx.linker_so = [cxx.compiler_cxx[0]] + cxx.linker_so[1:]
return cxx
replace_method(CCompiler, 'cxx_compiler', CCompiler_cxx_compiler)
compiler_class['intel'] = ('intelccompiler', 'IntelCCompiler',
"Intel C Compiler for 32-bit applications")
compiler_class['intele'] = ('intelccompiler', 'IntelItaniumCCompiler',
"Intel C Itanium Compiler for Itanium-based applications")
compiler_class['intelem'] = ('intelccompiler', 'IntelEM64TCCompiler',
"Intel C Compiler for 64-bit applications")
compiler_class['intelw'] = ('intelccompiler', 'IntelCCompilerW',
"Intel C Compiler for 32-bit applications on Windows")
compiler_class['intelemw'] = ('intelccompiler', 'IntelEM64TCCompilerW',
"Intel C Compiler for 64-bit applications on Windows")
compiler_class['pathcc'] = ('pathccompiler', 'PathScaleCCompiler',
"PathScale Compiler for SiCortex-based applications")
ccompiler._default_compilers += (('linux.*', 'intel'),
('linux.*', 'intele'),
('linux.*', 'intelem'),
('linux.*', 'pathcc'),
('nt', 'intelw'),
('nt', 'intelemw'))
if sys.platform == 'win32':
compiler_class['mingw32'] = ('mingw32ccompiler', 'Mingw32CCompiler',
"Mingw32 port of GNU C Compiler for Win32"\
"(for MSC built Python)")
if mingw32():
# On windows platforms, we want to default to mingw32 (gcc)
# because msvc can't build blitz stuff.
log.info('Setting mingw32 as default compiler for nt.')
ccompiler._default_compilers = (('nt', 'mingw32'),) \
+ ccompiler._default_compilers
_distutils_new_compiler = new_compiler
def new_compiler (plat=None,
compiler=None,
verbose=0,
dry_run=0,
force=0):
# Try first C compilers from numpy.distutils.
if plat is None:
plat = os.name
try:
if compiler is None:
compiler = get_default_compiler(plat)
(module_name, class_name, long_description) = compiler_class[compiler]
except KeyError:
msg = "don't know how to compile C/C++ code on platform '%s'" % plat
if compiler is not None:
msg = msg + " with '%s' compiler" % compiler
raise DistutilsPlatformError(msg)
module_name = "numpy.distutils." + module_name
try:
__import__ (module_name)
except ImportError:
msg = str(get_exception())
log.info('%s in numpy.distutils; trying from distutils',
str(msg))
module_name = module_name[6:]
try:
__import__(module_name)
except ImportError:
msg = str(get_exception())
raise DistutilsModuleError("can't compile C/C++ code: unable to load module '%s'" % \
module_name)
try:
module = sys.modules[module_name]
klass = vars(module)[class_name]
except KeyError:
raise DistutilsModuleError(("can't compile C/C++ code: unable to find class '%s' " +
"in module '%s'") % (class_name, module_name))
compiler = klass(None, dry_run, force)
log.debug('new_compiler returns %s' % (klass))
return compiler
ccompiler.new_compiler = new_compiler
_distutils_gen_lib_options = gen_lib_options
def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
library_dirs = quote_args(library_dirs)
runtime_library_dirs = quote_args(runtime_library_dirs)
r = _distutils_gen_lib_options(compiler, library_dirs,
runtime_library_dirs, libraries)
lib_opts = []
for i in r:
if is_sequence(i):
lib_opts.extend(list(i))
else:
lib_opts.append(i)
return lib_opts
ccompiler.gen_lib_options = gen_lib_options
# Also fix up the various compiler modules, which do
# from distutils.ccompiler import gen_lib_options
# Don't bother with mwerks, as we don't support Classic Mac.
for _cc in ['msvc9', 'msvc', 'bcpp', 'cygwinc', 'emxc', 'unixc']:
_m = sys.modules.get('distutils.' + _cc + 'compiler')
if _m is not None:
setattr(_m, 'gen_lib_options', gen_lib_options)
_distutils_gen_preprocess_options = gen_preprocess_options
def gen_preprocess_options (macros, include_dirs):
include_dirs = quote_args(include_dirs)
return _distutils_gen_preprocess_options(macros, include_dirs)
ccompiler.gen_preprocess_options = gen_preprocess_options
##Fix distutils.util.split_quoted:
# NOTE: I removed this fix in revision 4481 (see ticket #619), but it appears
# that removing this fix causes f2py problems on Windows XP (see ticket #723).
# Specifically, on WinXP when gfortran is installed in a directory path, which
# contains spaces, then f2py is unable to find it.
import string
_wordchars_re = re.compile(r'[^\\\'\"%s ]*' % string.whitespace)
_squote_re = re.compile(r"'(?:[^'\\]|\\.)*'")
_dquote_re = re.compile(r'"(?:[^"\\]|\\.)*"')
_has_white_re = re.compile(r'\s')
def split_quoted(s):
s = s.strip()
words = []
pos = 0
while s:
m = _wordchars_re.match(s, pos)
end = m.end()
if end == len(s):
words.append(s[:end])
break
if s[end] in string.whitespace: # unescaped, unquoted whitespace: now
words.append(s[:end]) # we definitely have a word delimiter
s = s[end:].lstrip()
pos = 0
elif s[end] == '\\': # preserve whatever is being escaped;
# will become part of the current word
s = s[:end] + s[end+1:]
pos = end+1
else:
if s[end] == "'": # slurp singly-quoted string
m = _squote_re.match(s, end)
elif s[end] == '"': # slurp doubly-quoted string
m = _dquote_re.match(s, end)
else:
raise RuntimeError("this can't happen (bad char '%c')" % s[end])
if m is None:
raise ValueError("bad string (mismatched %s quotes?)" % s[end])
(beg, end) = m.span()
if _has_white_re.search(s[beg+1:end-1]):
s = s[:beg] + s[beg+1:end-1] + s[end:]
pos = m.end() - 2
else:
# Keeping quotes when a quoted word does not contain
# white-space. XXX: send a patch to distutils
pos = m.end()
if pos >= len(s):
words.append(s)
break
return words
ccompiler.split_quoted = split_quoted
##Fix distutils.util.split_quoted:
|
venusource/python-neutronclient | refs/heads/master | neutronclient/tests/unit/test_cli20_port.py | 3 | # Copyright 2012 OpenStack Foundation.
# All Rights Reserved
#
# 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 itertools
import sys
from mox3 import mox
from neutronclient.neutron.v2_0 import port
from neutronclient import shell
from neutronclient.tests.unit import test_cli20
class CLITestV20PortJSON(test_cli20.CLITestV20Base):
def setUp(self):
super(CLITestV20PortJSON, self).setUp(plurals={'tags': 'tag'})
def test_create_port(self):
"""Create port: netid."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = [netid]
position_names = ['network_id']
position_values = []
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_extra_dhcp_opts_args(self):
"""Create port: netid --extra_dhcp_opt."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
extra_dhcp_opts = [{'opt_name': 'bootfile-name',
'opt_value': 'pxelinux.0'},
{'opt_name': 'tftp-server',
'opt_value': '123.123.123.123'},
{'opt_name': 'server-ip-address',
'opt_value': '123.123.123.45'}]
args = [netid]
for dhcp_opt in extra_dhcp_opts:
args += ['--extra-dhcp-opt',
('opt_name=%(opt_name)s,opt_value=%(opt_value)s' %
dhcp_opt)]
position_names = ['network_id', 'extra_dhcp_opts']
position_values = [netid, extra_dhcp_opts]
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_extra_dhcp_opts_args_ip_version(self):
"""Create port: netid --extra_dhcp_opt."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
extra_dhcp_opts = [{'opt_name': 'bootfile-name',
'opt_value': 'pxelinux.0',
'ip_version': "4"},
{'opt_name': 'tftp-server',
'opt_value': '2001:192:168::1',
'ip_version': "6"},
{'opt_name': 'server-ip-address',
'opt_value': '123.123.123.45',
'ip_version': "4"}]
args = [netid]
for dhcp_opt in extra_dhcp_opts:
args += ['--extra-dhcp-opt',
('opt_name=%(opt_name)s,opt_value=%(opt_value)s,'
'ip_version=%(ip_version)s' %
dhcp_opt)]
position_names = ['network_id', 'extra_dhcp_opts']
position_values = [netid, extra_dhcp_opts]
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_full(self):
"""Create port: --mac_address mac --device_id deviceid netid."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--mac_address', 'mac', '--device_id', 'deviceid', netid]
position_names = ['network_id', 'mac_address', 'device_id']
position_values = [netid, 'mac', 'deviceid']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--mac-address', 'mac', '--device-id', 'deviceid', netid]
position_names = ['network_id', 'mac_address', 'device_id']
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_vnic_type_normal(self):
"""Create port: --vnic_type normal netid."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--vnic_type', 'normal', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['normal', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--vnic-type', 'normal', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['normal', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_vnic_type_direct(self):
"""Create port: --vnic_type direct netid."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--vnic_type', 'direct', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['direct', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--vnic-type', 'direct', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['direct', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_vnic_type_macvtap(self):
"""Create port: --vnic_type macvtap netid."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--vnic_type', 'macvtap', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['macvtap', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--vnic-type', 'macvtap', netid]
position_names = ['binding:vnic_type', 'network_id']
position_values = ['macvtap', netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_with_binding_profile(self):
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--binding_profile', '{"foo":"bar"}', netid]
position_names = ['binding:profile', 'network_id']
position_values = [{'foo': 'bar'}, netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
# Test dashed options
args = ['--binding-profile', '{"foo":"bar"}', netid]
position_names = ['binding:profile', 'network_id']
position_values = [{'foo': 'bar'}, netid]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_tenant(self):
"""Create port: --tenant_id tenantid netid."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--tenant_id', 'tenantid', netid, ]
position_names = ['network_id']
position_values = []
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
# Test dashed options
args = ['--tenant-id', 'tenantid', netid, ]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tenant_id='tenantid')
def test_create_port_tags(self):
"""Create port: netid mac_address device_id --tags a b."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = [netid, '--tags', 'a', 'b']
position_names = ['network_id']
position_values = []
position_values.extend([netid])
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values,
tags=['a', 'b'])
def test_create_port_secgroup(self):
"""Create port: --security-group sg1_id netid."""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--security-group', 'sg1_id', netid]
position_names = ['network_id', 'security_groups']
position_values = [netid, ['sg1_id']]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_secgroups(self):
"""Create port: <security_groups> netid
The <security_groups> are
--security-group sg1_id --security-group sg2_id
"""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--security-group', 'sg1_id',
'--security-group', 'sg2_id',
netid]
position_names = ['network_id', 'security_groups']
position_values = [netid, ['sg1_id', 'sg2_id']]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_secgroup_off(self):
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = ['--no-security-group', netid]
position_names = ['network_id', 'security_groups']
position_values = [netid, []]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_create_port_secgroups_list(self):
"""Create port: netid <security_groups>
The <security_groups> are
--security-groups list=true sg_id1 sg_id2
"""
resource = 'port'
cmd = port.CreatePort(test_cli20.MyApp(sys.stdout), None)
name = 'myname'
myid = 'myid'
netid = 'netid'
args = [netid, '--security-groups', 'list=true', 'sg_id1', 'sg_id2']
position_names = ['network_id', 'security_groups']
position_values = [netid, ['sg_id1', 'sg_id2']]
self._test_create_resource(resource, cmd, name, myid, args,
position_names, position_values)
def test_list_ports(self):
"""List ports: -D."""
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, True)
def test_list_ports_pagination(self):
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources_with_pagination(resources, cmd)
def test_list_ports_sort(self):
"""list ports: --sort-key name --sort-key id --sort-key asc
--sort-key desc
"""
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
sort_key=["name", "id"],
sort_dir=["asc", "desc"])
def test_list_ports_limit(self):
"""list ports: -P."""
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, page_size=1000)
def test_list_ports_tags(self):
"""List ports: -- --tags a b."""
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, tags=['a', 'b'])
def test_list_ports_detail_tags(self):
"""List ports: -D -- --tags a b."""
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd, detail=True, tags=['a', 'b'])
def test_list_ports_fields(self):
"""List ports: --fields a --fields b -- --fields c d."""
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_resources(resources, cmd,
fields_1=['a', 'b'], fields_2=['c', 'd'])
def test_list_ports_with_fixed_ips_in_csv(self):
"""List ports: -f csv."""
resources = "ports"
cmd = port.ListPort(test_cli20.MyApp(sys.stdout), None)
fixed_ips = [{"subnet_id": "30422057-d6df-4c90-8314-aefb5e326666",
"ip_address": "10.0.0.12"},
{"subnet_id": "30422057-d6df-4c90-8314-aefb5e326666",
"ip_address": "10.0.0.4"}]
contents = [{'name': 'name1', 'fixed_ips': fixed_ips}]
self._test_list_resources(resources, cmd, True,
response_contents=contents,
output_format='csv')
def _test_list_router_port(self, resources, cmd,
myid, detail=False, tags=(),
fields_1=(), fields_2=()):
self.mox.StubOutWithMock(cmd, "get_client")
self.mox.StubOutWithMock(self.client.httpclient, "request")
cmd.get_client().MultipleTimes().AndReturn(self.client)
reses = {resources: [{'id': 'myid1', },
{'id': 'myid2', }, ], }
resstr = self.client.serialize(reses)
# url method body
query = ""
args = detail and ['-D', ] or []
if fields_1:
for field in fields_1:
args.append('--fields')
args.append(field)
args.append(myid)
if tags:
args.append('--')
args.append("--tag")
for tag in tags:
args.append(tag)
if (not tags) and fields_2:
args.append('--')
if fields_2:
args.append("--fields")
for field in fields_2:
args.append(field)
for field in itertools.chain(fields_1, fields_2):
if query:
query += "&fields=" + field
else:
query = "fields=" + field
for tag in tags:
if query:
query += "&tag=" + tag
else:
query = "tag=" + tag
if detail:
query = query and query + '&verbose=True' or 'verbose=True'
query = query and query + '&device_id=%s' or 'device_id=%s'
path = getattr(self.client, resources + "_path")
self.client.httpclient.request(
test_cli20.MyUrlComparator(
test_cli20.end_url(path, query % myid),
self.client),
'GET',
body=None,
headers=mox.ContainsKeyValue('X-Auth-Token', test_cli20.TOKEN)
).AndReturn((test_cli20.MyResp(200), resstr))
self.mox.ReplayAll()
cmd_parser = cmd.get_parser("list_" + resources)
shell.run_command(cmd, cmd_parser, args)
self.mox.VerifyAll()
self.mox.UnsetStubs()
_str = self.fake_stdout.make_string()
self.assertIn('myid1', _str)
def test_list_router_ports(self):
"""List router ports: -D."""
resources = "ports"
cmd = port.ListRouterPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_router_port(resources, cmd,
self.test_id, True)
def test_list_router_ports_tags(self):
"""List router ports: -- --tags a b."""
resources = "ports"
cmd = port.ListRouterPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_router_port(resources, cmd,
self.test_id, tags=['a', 'b'])
def test_list_router_ports_detail_tags(self):
"""List router ports: -D -- --tags a b."""
resources = "ports"
cmd = port.ListRouterPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_router_port(resources, cmd, self.test_id,
detail=True, tags=['a', 'b'])
def test_list_router_ports_fields(self):
"""List ports: --fields a --fields b -- --fields c d."""
resources = "ports"
cmd = port.ListRouterPort(test_cli20.MyApp(sys.stdout), None)
self._test_list_router_port(resources, cmd, self.test_id,
fields_1=['a', 'b'],
fields_2=['c', 'd'])
def test_update_port(self):
"""Update port: myid --name myname --admin-state-up False
--tags a b.
"""
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['myid', '--name', 'myname',
'--admin-state-up', 'False',
'--tags', 'a', 'b'],
{'name': 'myname',
'admin_state_up': 'False',
'tags': ['a', 'b'], })
def test_update_port_secgroup(self):
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = ['--security-group', 'sg1_id', myid]
updatefields = {'security_groups': ['sg1_id']}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_port_secgroups(self):
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = ['--security-group', 'sg1_id',
'--security-group', 'sg2_id',
myid]
updatefields = {'security_groups': ['sg1_id', 'sg2_id']}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_port_extra_dhcp_opts(self):
"""Update port: myid --extra_dhcp_opt."""
resource = 'port'
myid = 'myid'
args = [myid,
'--extra-dhcp-opt',
"opt_name=bootfile-name,opt_value=pxelinux.0",
'--extra-dhcp-opt',
"opt_name=tftp-server,opt_value=123.123.123.123",
'--extra-dhcp-opt',
"opt_name=server-ip-address,opt_value=123.123.123.45"
]
updatedfields = {'extra_dhcp_opts': [{'opt_name': 'bootfile-name',
'opt_value': 'pxelinux.0'},
{'opt_name': 'tftp-server',
'opt_value': '123.123.123.123'},
{'opt_name': 'server-ip-address',
'opt_value': '123.123.123.45'}]}
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, myid, args, updatedfields)
def test_update_port_fixed_ip(self):
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
net_id = 'net_id'
ip_addr = '123.123.123.123'
args = [myid,
'--fixed-ip', "network_id=%(net_id)s,ip_address=%(ip_addr)s" %
{'net_id': net_id,
'ip_addr': ip_addr}]
updated_fields = {"fixed_ips": [{'network_id': net_id,
'ip_address': ip_addr}]}
self._test_update_resource(resource, cmd, myid, args, updated_fields)
def test_update_port_device_id_device_owner(self):
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = ['--device-id', 'dev_id', '--device-owner', 'fake', myid]
updatefields = {'device_id': 'dev_id',
'device_owner': 'fake'}
self._test_update_resource(resource, cmd, myid, args, updatefields)
def test_update_port_extra_dhcp_opts_ip_version(self):
"""Update port: myid --extra_dhcp_opt."""
resource = 'port'
myid = 'myid'
args = [myid,
'--extra-dhcp-opt',
"opt_name=bootfile-name,opt_value=pxelinux.0,ip_version=4",
'--extra-dhcp-opt',
"opt_name=tftp-server,opt_value=2001:192:168::1,ip_version=6",
'--extra-dhcp-opt',
"opt_name=server-ip-address,opt_value=null,ip_version=4"
]
updatedfields = {'extra_dhcp_opts': [{'opt_name': 'bootfile-name',
'opt_value': 'pxelinux.0',
'ip_version': '4'},
{'opt_name': 'tftp-server',
'opt_value': '2001:192:168::1',
'ip_version': '6'},
{'opt_name': 'server-ip-address',
'opt_value': None,
'ip_version': '4'}]}
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, myid, args, updatedfields)
def test_delete_extra_dhcp_opts_from_port(self):
resource = 'port'
myid = 'myid'
args = [myid,
'--extra-dhcp-opt',
"opt_name=bootfile-name,opt_value=null",
'--extra-dhcp-opt',
"opt_name=tftp-server,opt_value=123.123.123.123",
'--extra-dhcp-opt',
"opt_name=server-ip-address,opt_value=123.123.123.45"
]
# the client code will change the null to None and send to server,
# where its interpreted as delete the DHCP option on the port.
updatedfields = {'extra_dhcp_opts': [{'opt_name': 'bootfile-name',
'opt_value': None},
{'opt_name': 'tftp-server',
'opt_value': '123.123.123.123'},
{'opt_name': 'server-ip-address',
'opt_value': '123.123.123.45'}]}
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, myid, args, updatedfields)
def test_update_port_security_group_off(self):
"""Update port: --no-security-groups myid."""
resource = 'port'
cmd = port.UpdatePort(test_cli20.MyApp(sys.stdout), None)
self._test_update_resource(resource, cmd, 'myid',
['--no-security-groups', 'myid'],
{'security_groups': []})
def test_show_port(self):
"""Show port: --fields id --fields name myid."""
resource = 'port'
cmd = port.ShowPort(test_cli20.MyApp(sys.stdout), None)
args = ['--fields', 'id', '--fields', 'name', self.test_id]
self._test_show_resource(resource, cmd, self.test_id,
args, ['id', 'name'])
def test_delete_port(self):
"""Delete port: myid."""
resource = 'port'
cmd = port.DeletePort(test_cli20.MyApp(sys.stdout), None)
myid = 'myid'
args = [myid]
self._test_delete_resource(resource, cmd, myid, args)
class CLITestV20PortXML(CLITestV20PortJSON):
format = 'xml'
|
aferr/LatticeMemCtl | refs/heads/master | tests/configs/simple-atomic.py | 19 | # Copyright (c) 2006-2007 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Steve Reinhardt
import m5
from m5.objects import *
system = System(cpu = AtomicSimpleCPU(cpu_id=0),
physmem = SimpleMemory(),
membus = CoherentBus())
system.system_port = system.membus.slave
system.physmem.port = system.membus.master
# create the interrupt controller
system.cpu.createInterruptController()
system.cpu.connectAllPorts(system.membus)
system.cpu.clock = '2GHz'
root = Root(full_system = False, system = system)
|
gquirozbogner/contentbox-master | refs/heads/master | third_party/django/contrib/gis/geoip/tests.py | 76 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.conf import settings
from django.contrib.gis.geos import HAS_GEOS
from django.contrib.gis.geoip import HAS_GEOIP
from django.utils import unittest
from django.utils.unittest import skipUnless
from django.utils import six
if HAS_GEOIP:
from . import GeoIP, GeoIPException
if HAS_GEOS:
from ..geos import GEOSGeometry
# Note: Requires use of both the GeoIP country and city datasets.
# The GEOIP_DATA path should be the only setting set (the directory
# should contain links or the actual database files 'GeoIP.dat' and
# 'GeoLiteCity.dat'.
@skipUnless(HAS_GEOIP and getattr(settings, "GEOIP_PATH", None),
"GeoIP is required along with the GEOIP_PATH setting.")
class GeoIPTest(unittest.TestCase):
def test01_init(self):
"Testing GeoIP initialization."
g1 = GeoIP() # Everything inferred from GeoIP path
path = settings.GEOIP_PATH
g2 = GeoIP(path, 0) # Passing in data path explicitly.
g3 = GeoIP.open(path, 0) # MaxMind Python API syntax.
for g in (g1, g2, g3):
self.assertEqual(True, bool(g._country))
self.assertEqual(True, bool(g._city))
# Only passing in the location of one database.
city = os.path.join(path, 'GeoLiteCity.dat')
cntry = os.path.join(path, 'GeoIP.dat')
g4 = GeoIP(city, country='')
self.assertEqual(None, g4._country)
g5 = GeoIP(cntry, city='')
self.assertEqual(None, g5._city)
# Improper parameters.
bad_params = (23, 'foo', 15.23)
for bad in bad_params:
self.assertRaises(GeoIPException, GeoIP, cache=bad)
if isinstance(bad, six.string_types):
e = GeoIPException
else:
e = TypeError
self.assertRaises(e, GeoIP, bad, 0)
def test02_bad_query(self):
"Testing GeoIP query parameter checking."
cntry_g = GeoIP(city='<foo>')
# No city database available, these calls should fail.
self.assertRaises(GeoIPException, cntry_g.city, 'google.com')
self.assertRaises(GeoIPException, cntry_g.coords, 'yahoo.com')
# Non-string query should raise TypeError
self.assertRaises(TypeError, cntry_g.country_code, 17)
self.assertRaises(TypeError, cntry_g.country_name, GeoIP)
def test03_country(self):
"Testing GeoIP country querying methods."
g = GeoIP(city='<foo>')
fqdn = 'www.google.com'
addr = '12.215.42.19'
for query in (fqdn, addr):
for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name):
self.assertEqual('US', func(query))
for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name):
self.assertEqual('United States', func(query))
self.assertEqual({'country_code' : 'US', 'country_name' : 'United States'},
g.country(query))
@skipUnless(HAS_GEOS, "Geos is required")
def test04_city(self):
"Testing GeoIP city querying methods."
g = GeoIP(country='<foo>')
addr = '128.249.1.1'
fqdn = 'tmc.edu'
for query in (fqdn, addr):
# Country queries should still work.
for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name):
self.assertEqual('US', func(query))
for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name):
self.assertEqual('United States', func(query))
self.assertEqual({'country_code' : 'US', 'country_name' : 'United States'},
g.country(query))
# City information dictionary.
d = g.city(query)
self.assertEqual('USA', d['country_code3'])
self.assertEqual('Houston', d['city'])
self.assertEqual('TX', d['region'])
self.assertEqual(713, d['area_code'])
geom = g.geos(query)
self.assertTrue(isinstance(geom, GEOSGeometry))
lon, lat = (-95.4010, 29.7079)
lat_lon = g.lat_lon(query)
lat_lon = (lat_lon[1], lat_lon[0])
for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon):
self.assertAlmostEqual(lon, tup[0], 4)
self.assertAlmostEqual(lat, tup[1], 4)
def test05_unicode_response(self):
"Testing that GeoIP strings are properly encoded, see #16553."
g = GeoIP()
d = g.city("www.osnabrueck.de")
self.assertEqual('Osnabrück', d['city'])
d = g.country('200.7.49.81')
self.assertEqual('Curaçao', d['country_name'])
|
zhuhangyu/jumpserver | refs/heads/master | docs/__init__.py | 41 | __author__ = 'Hudie'
|
aerickson/ansible | refs/heads/devel | lib/ansible/modules/monitoring/pingdom.py | 77 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: pingdom
short_description: Pause/unpause Pingdom alerts
description:
- This module will let you pause/unpause Pingdom alerts
version_added: "1.2"
author:
- "Dylan Silva (@thaumos)"
- "Justin Johns"
requirements:
- "This pingdom python library: https://github.com/mbabineau/pingdom-python"
options:
state:
description:
- Define whether or not the check should be running or paused.
required: true
default: null
choices: [ "running", "paused" ]
aliases: []
checkid:
description:
- Pingdom ID of the check.
required: true
default: null
choices: []
aliases: []
uid:
description:
- Pingdom user ID.
required: true
default: null
choices: []
aliases: []
passwd:
description:
- Pingdom user password.
required: true
default: null
choices: []
aliases: []
key:
description:
- Pingdom API key.
required: true
default: null
choices: []
aliases: []
notes:
- This module does not yet have support to add/remove checks.
'''
EXAMPLES = '''
# Pause the check with the ID of 12345.
- pingdom:
uid: example@example.com
passwd: password123
key: apipassword123
checkid: 12345
state: paused
# Unpause the check with the ID of 12345.
- pingdom:
uid: example@example.com
passwd: password123
key: apipassword123
checkid: 12345
state: running
'''
try:
import pingdom
HAS_PINGDOM = True
except:
HAS_PINGDOM = False
def pause(checkid, uid, passwd, key):
c = pingdom.PingdomConnection(uid, passwd, key)
c.modify_check(checkid, paused=True)
check = c.get_check(checkid)
name = check.name
result = check.status
#if result != "paused": # api output buggy - accept raw exception for now
# return (True, name, result)
return (False, name, result)
def unpause(checkid, uid, passwd, key):
c = pingdom.PingdomConnection(uid, passwd, key)
c.modify_check(checkid, paused=False)
check = c.get_check(checkid)
name = check.name
result = check.status
#if result != "up": # api output buggy - accept raw exception for now
# return (True, name, result)
return (False, name, result)
def main():
module = AnsibleModule(
argument_spec=dict(
state=dict(required=True, choices=['running', 'paused', 'started', 'stopped']),
checkid=dict(required=True),
uid=dict(required=True),
passwd=dict(required=True, no_log=True),
key=dict(required=True)
)
)
if not HAS_PINGDOM:
module.fail_json(msg="Missing required pingdom module (check docs)")
checkid = module.params['checkid']
state = module.params['state']
uid = module.params['uid']
passwd = module.params['passwd']
key = module.params['key']
if (state == "paused" or state == "stopped"):
(rc, name, result) = pause(checkid, uid, passwd, key)
if (state == "running" or state == "started"):
(rc, name, result) = unpause(checkid, uid, passwd, key)
if rc != 0:
module.fail_json(checkid=checkid, name=name, status=result)
module.exit_json(checkid=checkid, name=name, status=result)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
|
bacontext/mopidy | refs/heads/develop | mopidy/mpd/protocol/stickers.py | 19 | from __future__ import absolute_import, unicode_literals
from mopidy.mpd import exceptions, protocol
@protocol.commands.add('sticker', list_command=False)
def sticker(context, action, field, uri, name=None, value=None):
"""
*musicpd.org, sticker section:*
``sticker list {TYPE} {URI}``
Lists the stickers for the specified object.
``sticker find {TYPE} {URI} {NAME}``
Searches the sticker database for stickers with the specified name,
below the specified directory (``URI``). For each matching song, it
prints the ``URI`` and that one sticker's value.
``sticker get {TYPE} {URI} {NAME}``
Reads a sticker value for the specified object.
``sticker set {TYPE} {URI} {NAME} {VALUE}``
Adds a sticker value to the specified object. If a sticker item
with that name already exists, it is replaced.
``sticker delete {TYPE} {URI} [NAME]``
Deletes a sticker value from the specified object. If you do not
specify a sticker name, all sticker values are deleted.
"""
# TODO: check that action in ('list', 'find', 'get', 'set', 'delete')
# TODO: check name/value matches with action
raise exceptions.MpdNotImplemented # TODO
|
andyfaff/scipy | refs/heads/master | scipy/sparse/linalg/isolve/tests/test_gcrotmk.py | 12 | #!/usr/bin/env python
"""Tests for the linalg.isolve.gcrotmk module
"""
from numpy.testing import (assert_, assert_allclose, assert_equal,
suppress_warnings)
import numpy as np
from numpy import zeros, array, allclose
from scipy.linalg import norm
from scipy.sparse import csr_matrix, eye, rand
from scipy.sparse.linalg.interface import LinearOperator
from scipy.sparse.linalg import splu
from scipy.sparse.linalg.isolve import gcrotmk, gmres
Am = csr_matrix(array([[-2,1,0,0,0,9],
[1,-2,1,0,5,0],
[0,1,-2,1,0,0],
[0,0,1,-2,1,0],
[0,3,0,1,-2,1],
[1,0,0,0,1,-2]]))
b = array([1,2,3,4,5,6])
count = [0]
def matvec(v):
count[0] += 1
return Am*v
A = LinearOperator(matvec=matvec, shape=Am.shape, dtype=Am.dtype)
def do_solve(**kw):
count[0] = 0
with suppress_warnings() as sup:
sup.filter(DeprecationWarning, ".*called without specifying.*")
x0, flag = gcrotmk(A, b, x0=zeros(A.shape[0]), tol=1e-14, **kw)
count_0 = count[0]
assert_(allclose(A*x0, b, rtol=1e-12, atol=1e-12), norm(A*x0-b))
return x0, count_0
class TestGCROTMK:
def test_preconditioner(self):
# Check that preconditioning works
pc = splu(Am.tocsc())
M = LinearOperator(matvec=pc.solve, shape=A.shape, dtype=A.dtype)
x0, count_0 = do_solve()
x1, count_1 = do_solve(M=M)
assert_equal(count_1, 3)
assert_(count_1 < count_0/2)
assert_(allclose(x1, x0, rtol=1e-14))
def test_arnoldi(self):
np.random.seed(1)
A = eye(2000) + rand(2000, 2000, density=5e-4)
b = np.random.rand(2000)
# The inner arnoldi should be equivalent to gmres
with suppress_warnings() as sup:
sup.filter(DeprecationWarning, ".*called without specifying.*")
x0, flag0 = gcrotmk(A, b, x0=zeros(A.shape[0]), m=15, k=0, maxiter=1)
x1, flag1 = gmres(A, b, x0=zeros(A.shape[0]), restart=15, maxiter=1)
assert_equal(flag0, 1)
assert_equal(flag1, 1)
assert np.linalg.norm(A.dot(x0) - b) > 1e-3
assert_allclose(x0, x1)
def test_cornercase(self):
np.random.seed(1234)
# Rounding error may prevent convergence with tol=0 --- ensure
# that the return values in this case are correct, and no
# exceptions are raised
for n in [3, 5, 10, 100]:
A = 2*eye(n)
with suppress_warnings() as sup:
sup.filter(DeprecationWarning, ".*called without specifying.*")
b = np.ones(n)
x, info = gcrotmk(A, b, maxiter=10)
assert_equal(info, 0)
assert_allclose(A.dot(x) - b, 0, atol=1e-14)
x, info = gcrotmk(A, b, tol=0, maxiter=10)
if info == 0:
assert_allclose(A.dot(x) - b, 0, atol=1e-14)
b = np.random.rand(n)
x, info = gcrotmk(A, b, maxiter=10)
assert_equal(info, 0)
assert_allclose(A.dot(x) - b, 0, atol=1e-14)
x, info = gcrotmk(A, b, tol=0, maxiter=10)
if info == 0:
assert_allclose(A.dot(x) - b, 0, atol=1e-14)
def test_nans(self):
A = eye(3, format='lil')
A[1,1] = np.nan
b = np.ones(3)
with suppress_warnings() as sup:
sup.filter(DeprecationWarning, ".*called without specifying.*")
x, info = gcrotmk(A, b, tol=0, maxiter=10)
assert_equal(info, 1)
def test_truncate(self):
np.random.seed(1234)
A = np.random.rand(30, 30) + np.eye(30)
b = np.random.rand(30)
for truncate in ['oldest', 'smallest']:
with suppress_warnings() as sup:
sup.filter(DeprecationWarning, ".*called without specifying.*")
x, info = gcrotmk(A, b, m=10, k=10, truncate=truncate, tol=1e-4,
maxiter=200)
assert_equal(info, 0)
assert_allclose(A.dot(x) - b, 0, atol=1e-3)
def test_CU(self):
for discard_C in (True, False):
# Check that C,U behave as expected
CU = []
x0, count_0 = do_solve(CU=CU, discard_C=discard_C)
assert_(len(CU) > 0)
assert_(len(CU) <= 6)
if discard_C:
for c, u in CU:
assert_(c is None)
# should converge immediately
x1, count_1 = do_solve(CU=CU, discard_C=discard_C)
if discard_C:
assert_equal(count_1, 2 + len(CU))
else:
assert_equal(count_1, 3)
assert_(count_1 <= count_0/2)
assert_allclose(x1, x0, atol=1e-14)
def test_denormals(self):
# Check that no warnings are emitted if the matrix contains
# numbers for which 1/x has no float representation, and that
# the solver behaves properly.
A = np.array([[1, 2], [3, 4]], dtype=float)
A *= 100 * np.nextafter(0, 1)
b = np.array([1, 1])
with suppress_warnings() as sup:
sup.filter(DeprecationWarning, ".*called without specifying.*")
xp, info = gcrotmk(A, b)
if info == 0:
assert_allclose(A.dot(xp), b)
|
sebgoa/client-python | refs/heads/master | kubernetes/client/models/v1_node_condition.py | 2 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V1NodeCondition(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
def __init__(self, last_heartbeat_time=None, last_transition_time=None, message=None, reason=None, status=None, type=None):
"""
V1NodeCondition - a model defined in Swagger
:param dict swaggerTypes: The key is attribute name
and the value is attribute type.
:param dict attributeMap: The key is attribute name
and the value is json key in definition.
"""
self.swagger_types = {
'last_heartbeat_time': 'datetime',
'last_transition_time': 'datetime',
'message': 'str',
'reason': 'str',
'status': 'str',
'type': 'str'
}
self.attribute_map = {
'last_heartbeat_time': 'lastHeartbeatTime',
'last_transition_time': 'lastTransitionTime',
'message': 'message',
'reason': 'reason',
'status': 'status',
'type': 'type'
}
self._last_heartbeat_time = last_heartbeat_time
self._last_transition_time = last_transition_time
self._message = message
self._reason = reason
self._status = status
self._type = type
@property
def last_heartbeat_time(self):
"""
Gets the last_heartbeat_time of this V1NodeCondition.
Last time we got an update on a given condition.
:return: The last_heartbeat_time of this V1NodeCondition.
:rtype: datetime
"""
return self._last_heartbeat_time
@last_heartbeat_time.setter
def last_heartbeat_time(self, last_heartbeat_time):
"""
Sets the last_heartbeat_time of this V1NodeCondition.
Last time we got an update on a given condition.
:param last_heartbeat_time: The last_heartbeat_time of this V1NodeCondition.
:type: datetime
"""
self._last_heartbeat_time = last_heartbeat_time
@property
def last_transition_time(self):
"""
Gets the last_transition_time of this V1NodeCondition.
Last time the condition transit from one status to another.
:return: The last_transition_time of this V1NodeCondition.
:rtype: datetime
"""
return self._last_transition_time
@last_transition_time.setter
def last_transition_time(self, last_transition_time):
"""
Sets the last_transition_time of this V1NodeCondition.
Last time the condition transit from one status to another.
:param last_transition_time: The last_transition_time of this V1NodeCondition.
:type: datetime
"""
self._last_transition_time = last_transition_time
@property
def message(self):
"""
Gets the message of this V1NodeCondition.
Human readable message indicating details about last transition.
:return: The message of this V1NodeCondition.
:rtype: str
"""
return self._message
@message.setter
def message(self, message):
"""
Sets the message of this V1NodeCondition.
Human readable message indicating details about last transition.
:param message: The message of this V1NodeCondition.
:type: str
"""
self._message = message
@property
def reason(self):
"""
Gets the reason of this V1NodeCondition.
(brief) reason for the condition's last transition.
:return: The reason of this V1NodeCondition.
:rtype: str
"""
return self._reason
@reason.setter
def reason(self, reason):
"""
Sets the reason of this V1NodeCondition.
(brief) reason for the condition's last transition.
:param reason: The reason of this V1NodeCondition.
:type: str
"""
self._reason = reason
@property
def status(self):
"""
Gets the status of this V1NodeCondition.
Status of the condition, one of True, False, Unknown.
:return: The status of this V1NodeCondition.
:rtype: str
"""
return self._status
@status.setter
def status(self, status):
"""
Sets the status of this V1NodeCondition.
Status of the condition, one of True, False, Unknown.
:param status: The status of this V1NodeCondition.
:type: str
"""
if status is None:
raise ValueError("Invalid value for `status`, must not be `None`")
self._status = status
@property
def type(self):
"""
Gets the type of this V1NodeCondition.
Type of node condition.
:return: The type of this V1NodeCondition.
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""
Sets the type of this V1NodeCondition.
Type of node condition.
:param type: The type of this V1NodeCondition.
:type: str
"""
if type is None:
raise ValueError("Invalid value for `type`, must not be `None`")
self._type = type
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in iteritems(self.swagger_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 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, V1NodeCondition):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.