repo_name stringlengths 5 100 | path stringlengths 4 375 | copies stringclasses 991
values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15
values |
|---|---|---|---|---|---|
eahneahn/free | lib/python2.7/site-packages/openid/extension.py | 157 | 1686 | from openid import message as message_module
class Extension(object):
"""An interface for OpenID extensions.
@ivar ns_uri: The namespace to which to add the arguments for this
extension
"""
ns_uri = None
ns_alias = None
def getExtensionArgs(self):
"""Get the string arguments that should be added to an OpenID
message for this extension.
@returns: A dictionary of completely non-namespaced arguments
to be added. For example, if the extension's alias is
'uncle', and this method returns {'meat':'Hot Rats'}, the
final message will contain {'openid.uncle.meat':'Hot Rats'}
"""
raise NotImplementedError
def toMessage(self, message=None):
"""Add the arguments from this extension to the provided
message, or create a new message containing only those
arguments.
@returns: The message with the extension arguments added
"""
if message is None:
warnings.warn('Passing None to Extension.toMessage is deprecated. '
'Creating a message assuming you want OpenID 2.',
DeprecationWarning, stacklevel=2)
message = message_module.Message(message_module.OPENID2_NS)
implicit = message.isOpenID1()
try:
message.namespaces.addAlias(self.ns_uri, self.ns_alias,
implicit=implicit)
except KeyError:
if message.namespaces.getAlias(self.ns_uri) != self.ns_alias:
raise
message.updateArgs(self.ns_uri, self.getExtensionArgs())
return message
| agpl-3.0 |
suyashphadtare/vestasi-update-erp | erpnext/stock/report/stock_balance/stock_balance.py | 28 | 3568 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt
def execute(filters=None):
if not filters: filters = {}
columns = get_columns(filters)
item_map = get_item_details(filters)
iwb_map = get_item_warehouse_map(filters)
data = []
for company in sorted(iwb_map):
for item in sorted(iwb_map[company]):
for wh in sorted(iwb_map[company][item]):
qty_dict = iwb_map[company][item][wh]
data.append([item, item_map[item]["item_name"],
item_map[item]["item_group"],
item_map[item]["brand"],
item_map[item]["description"], wh,
qty_dict.uom, qty_dict.opening_qty,
qty_dict.opening_val, qty_dict.in_qty,
qty_dict.in_val, qty_dict.out_qty,
qty_dict.out_val, qty_dict.bal_qty,
qty_dict.bal_val, qty_dict.val_rate,
company
])
return columns, data
def get_columns(filters):
"""return columns based on filters"""
columns = ["Item:Link/Item:100", "Item Name::150", "Item Group::100", "Brand::90", \
"Description::140", "Warehouse:Link/Warehouse:100", "Stock UOM::90", "Opening Qty:Float:100", \
"Opening Value:Float:110", "In Qty:Float:80", "In Value:Float:80", "Out Qty:Float:80", \
"Out Value:Float:80", "Balance Qty:Float:100", "Balance Value:Float:100", \
"Valuation Rate:Float:90", "Company:Link/Company:100"]
return columns
def get_conditions(filters):
conditions = ""
if not filters.get("from_date"):
frappe.throw(_("'From Date' is required"))
if filters.get("to_date"):
conditions += " and posting_date <= '%s'" % filters["to_date"]
else:
frappe.throw(_("'To Date' is required"))
return conditions
#get all details
def get_stock_ledger_entries(filters):
conditions = get_conditions(filters)
return frappe.db.sql("""select item_code, warehouse, posting_date, actual_qty, valuation_rate,
stock_uom, company, voucher_type, qty_after_transaction, stock_value_difference
from `tabStock Ledger Entry`
where docstatus < 2 %s order by posting_date, posting_time, name""" %
conditions, as_dict=1)
def get_item_warehouse_map(filters):
sle = get_stock_ledger_entries(filters)
iwb_map = {}
for d in sle:
iwb_map.setdefault(d.company, {}).setdefault(d.item_code, {}).\
setdefault(d.warehouse, frappe._dict({\
"opening_qty": 0.0, "opening_val": 0.0,
"in_qty": 0.0, "in_val": 0.0,
"out_qty": 0.0, "out_val": 0.0,
"bal_qty": 0.0, "bal_val": 0.0,
"val_rate": 0.0, "uom": None
}))
qty_dict = iwb_map[d.company][d.item_code][d.warehouse]
qty_dict.uom = d.stock_uom
if d.voucher_type == "Stock Reconciliation":
qty_diff = flt(d.qty_after_transaction) - qty_dict.bal_qty
else:
qty_diff = flt(d.actual_qty)
value_diff = flt(d.stock_value_difference)
if d.posting_date < filters["from_date"]:
qty_dict.opening_qty += qty_diff
qty_dict.opening_val += value_diff
elif d.posting_date >= filters["from_date"] and d.posting_date <= filters["to_date"]:
qty_dict.val_rate = d.valuation_rate
if qty_diff > 0:
qty_dict.in_qty += qty_diff
qty_dict.in_val += value_diff
else:
qty_dict.out_qty += abs(qty_diff)
qty_dict.out_val += abs(value_diff)
qty_dict.bal_qty += qty_diff
qty_dict.bal_val += value_diff
return iwb_map
def get_item_details(filters):
item_map = {}
for d in frappe.db.sql("select name, item_name, item_group, brand, \
description from tabItem", as_dict=1):
item_map.setdefault(d.name, d)
return item_map
| agpl-3.0 |
dreamsxin/kbengine | kbe/res/scripts/common/Lib/encodings/uu_codec.py | 77 | 2725 | """Python 'uu_codec' Codec - UU content transfer encoding.
This codec de/encodes from bytes to bytes.
Written by Marc-Andre Lemburg (mal@lemburg.com). Some details were
adapted from uu.py which was written by Lance Ellinghouse and
modified by Jack Jansen and Fredrik Lundh.
"""
import codecs
import binascii
from io import BytesIO
### Codec APIs
def uu_encode(input, errors='strict', filename='<data>', mode=0o666):
assert errors == 'strict'
infile = BytesIO(input)
outfile = BytesIO()
read = infile.read
write = outfile.write
# Encode
write(('begin %o %s\n' % (mode & 0o777, filename)).encode('ascii'))
chunk = read(45)
while chunk:
write(binascii.b2a_uu(chunk))
chunk = read(45)
write(b' \nend\n')
return (outfile.getvalue(), len(input))
def uu_decode(input, errors='strict'):
assert errors == 'strict'
infile = BytesIO(input)
outfile = BytesIO()
readline = infile.readline
write = outfile.write
# Find start of encoded data
while 1:
s = readline()
if not s:
raise ValueError('Missing "begin" line in input data')
if s[:5] == b'begin':
break
# Decode
while True:
s = readline()
if not s or s == b'end\n':
break
try:
data = binascii.a2b_uu(s)
except binascii.Error as v:
# Workaround for broken uuencoders by /Fredrik Lundh
nbytes = (((ord(s[0])-32) & 63) * 4 + 5) / 3
data = binascii.a2b_uu(s[:nbytes])
#sys.stderr.write("Warning: %s\n" % str(v))
write(data)
if not s:
raise ValueError('Truncated input data')
return (outfile.getvalue(), len(input))
class Codec(codecs.Codec):
def encode(self, input, errors='strict'):
return uu_encode(input, errors)
def decode(self, input, errors='strict'):
return uu_decode(input, errors)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return uu_encode(input, self.errors)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return uu_decode(input, self.errors)[0]
class StreamWriter(Codec, codecs.StreamWriter):
charbuffertype = bytes
class StreamReader(Codec, codecs.StreamReader):
charbuffertype = bytes
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='uu',
encode=uu_encode,
decode=uu_decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
_is_text_encoding=False,
)
| lgpl-3.0 |
Rocky5/XBMC-Emustation | Mod Files/emustation/scripts/not used/DLC Hash stuff/DLC Hash calculator.py | 2 | 1046 | import hashlib, hmac, os, struct, xbmc, xbmcgui, time
# Had to use this while loop to get the HDD key as it will be Busy for a second or two.
dialog = xbmcgui.Dialog()
hashlibsha1 = hashlib.sha1
Select_Folder = dialog.browse( 3,"Select folder to hash",'files','' )
contextmetafile = os.path.join( Select_Folder,'contentmeta.xbx' )
filesize = os.path.getsize(contextmetafile)
readxbx = open(contextmetafile, 'r+b')
filedata = readxbx.read(filesize)
while True:
key = xbmc.getInfoLabel('system.hddlockkey')
time.sleep(1)
if key != 'Busy':
break
hddkey = key.decode('hex')
# Check the header fields.
headersize = struct.unpack('I', filedata[24:28])[0]
titleid = filedata[36:40]
# Compute the HMAC key using the title id and HDD key.
hmacKey = hmac.new(hddkey, titleid, hashlib.sha1).digest()[0:20]
# Compute the content signature.
contentSignature = hmac.new(hmacKey, filedata[20:headersize], hashlibsha1).digest()[0:20]
readxbx.seek(0,0)
readxbx.write(contentSignature)
xbmcgui.Dialog().ok("Hashed","Hashed content.") | gpl-3.0 |
Partoo/scrapy | scrapy/xlib/pydispatch/dispatcher.py | 23 | 16963 | """Multiple-producer-multiple-consumer signal-dispatching
dispatcher is the core of the PyDispatcher system,
providing the primary API and the core logic for the
system.
Module attributes of note:
Any -- Singleton used to signal either "Any Sender" or
"Any Signal". See documentation of the _Any class.
Anonymous -- Singleton used to signal "Anonymous Sender"
See documentation of the _Anonymous class.
Internal attributes:
WEAKREF_TYPES -- tuple of types/classes which represent
weak references to receivers, and thus must be de-
referenced on retrieval to retrieve the callable
object
connections -- { senderkey (id) : { signal : [receivers...]}}
senders -- { senderkey (id) : weakref(sender) }
used for cleaning up sender references on sender
deletion
sendersBack -- { receiverkey (id) : [senderkey (id)...] }
used for cleaning up receiver references on receiver
deletion, (considerably speeds up the cleanup process
vs. the original code.)
"""
from __future__ import generators
import types, weakref, six
from scrapy.xlib.pydispatch import saferef, robustapply, errors
__author__ = "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id: dispatcher.py,v 1.1.1.1 2006/07/07 15:59:38 mcfletch Exp $"
__version__ = "$Revision: 1.1.1.1 $"[11:-2]
class _Parameter:
"""Used to represent default parameter values."""
def __repr__(self):
return self.__class__.__name__
class _Any(_Parameter):
"""Singleton used to signal either "Any Sender" or "Any Signal"
The Any object can be used with connect, disconnect,
send, or sendExact to signal that the parameter given
Any should react to all senders/signals, not just
a particular sender/signal.
"""
Any = _Any()
class _Anonymous(_Parameter):
"""Singleton used to signal "Anonymous Sender"
The Anonymous object is used to signal that the sender
of a message is not specified (as distinct from being
"any sender"). Registering callbacks for Anonymous
will only receive messages sent without senders. Sending
with anonymous will only send messages to those receivers
registered for Any or Anonymous.
Note:
The default sender for connect is Any, while the
default sender for send is Anonymous. This has
the effect that if you do not specify any senders
in either function then all messages are routed
as though there was a single sender (Anonymous)
being used everywhere.
"""
Anonymous = _Anonymous()
WEAKREF_TYPES = (weakref.ReferenceType, saferef.BoundMethodWeakref)
connections = {}
senders = {}
sendersBack = {}
def connect(receiver, signal=Any, sender=Any, weak=True):
"""Connect receiver to sender for signal
receiver -- a callable Python object which is to receive
messages/signals/events. Receivers must be hashable
objects.
if weak is True, then receiver must be weak-referencable
(more precisely saferef.safeRef() must be able to create
a reference to the receiver).
Receivers are fairly flexible in their specification,
as the machinery in the robustApply module takes care
of most of the details regarding figuring out appropriate
subsets of the sent arguments to apply to a given
receiver.
Note:
if receiver is itself a weak reference (a callable),
it will be de-referenced by the system's machinery,
so *generally* weak references are not suitable as
receivers, though some use might be found for the
facility whereby a higher-level library passes in
pre-weakrefed receiver references.
signal -- the signal to which the receiver should respond
if Any, receiver will receive any signal from the
indicated sender (which might also be Any, but is not
necessarily Any).
Otherwise must be a hashable Python object other than
None (DispatcherError raised on None).
sender -- the sender to which the receiver should respond
if Any, receiver will receive the indicated signals
from any sender.
if Anonymous, receiver will only receive indicated
signals from send/sendExact which do not specify a
sender, or specify Anonymous explicitly as the sender.
Otherwise can be any python object.
weak -- whether to use weak references to the receiver
By default, the module will attempt to use weak
references to the receiver objects. If this parameter
is false, then strong references will be used.
returns None, may raise DispatcherTypeError
"""
if signal is None:
raise errors.DispatcherTypeError(
'Signal cannot be None (receiver=%r sender=%r)' % (
receiver, sender)
)
if weak:
receiver = saferef.safeRef(receiver, onDelete=_removeReceiver)
senderkey = id(sender)
if senderkey in connections:
signals = connections[senderkey]
else:
connections[senderkey] = signals = {}
# Keep track of senders for cleanup.
# Is Anonymous something we want to clean up?
if sender not in (None, Anonymous, Any):
def remove(object, senderkey=senderkey):
_removeSender(senderkey=senderkey)
# Skip objects that can not be weakly referenced, which means
# they won't be automatically cleaned up, but that's too bad.
try:
weakSender = weakref.ref(sender, remove)
senders[senderkey] = weakSender
except:
pass
receiverID = id(receiver)
# get current set, remove any current references to
# this receiver in the set, including back-references
if signal in signals:
receivers = signals[signal]
_removeOldBackRefs(senderkey, signal, receiver, receivers)
else:
receivers = signals[signal] = []
try:
current = sendersBack.get(receiverID)
if current is None:
sendersBack[receiverID] = current = []
if senderkey not in current:
current.append(senderkey)
except:
pass
receivers.append(receiver)
def disconnect(receiver, signal=Any, sender=Any, weak=True):
"""Disconnect receiver from sender for signal
receiver -- the registered receiver to disconnect
signal -- the registered signal to disconnect
sender -- the registered sender to disconnect
weak -- the weakref state to disconnect
disconnect reverses the process of connect,
the semantics for the individual elements are
logically equivalent to a tuple of
(receiver, signal, sender, weak) used as a key
to be deleted from the internal routing tables.
(The actual process is slightly more complex
but the semantics are basically the same).
Note:
Using disconnect is not required to cleanup
routing when an object is deleted, the framework
will remove routes for deleted objects
automatically. It's only necessary to disconnect
if you want to stop routing to a live object.
returns None, may raise DispatcherTypeError or
DispatcherKeyError
"""
if signal is None:
raise errors.DispatcherTypeError(
'Signal cannot be None (receiver=%r sender=%r)' % (
receiver, sender)
)
if weak: receiver = saferef.safeRef(receiver)
senderkey = id(sender)
try:
signals = connections[senderkey]
receivers = signals[signal]
except KeyError:
raise errors.DispatcherKeyError(
"""No receivers found for signal %r from sender %r""" % (
signal,
sender
)
)
try:
# also removes from receivers
_removeOldBackRefs(senderkey, signal, receiver, receivers)
except ValueError:
raise errors.DispatcherKeyError(
"""No connection to receiver %s for signal %s from sender %s""" % (
receiver,
signal,
sender
)
)
_cleanupConnections(senderkey, signal)
def getReceivers(sender=Any, signal=Any):
"""Get list of receivers from global tables
This utility function allows you to retrieve the
raw list of receivers from the connections table
for the given sender and signal pair.
Note:
there is no guarantee that this is the actual list
stored in the connections table, so the value
should be treated as a simple iterable/truth value
rather than, for instance a list to which you
might append new records.
Normally you would use liveReceivers( getReceivers( ...))
to retrieve the actual receiver objects as an iterable
object.
"""
try:
return connections[id(sender)][signal]
except KeyError:
return []
def liveReceivers(receivers):
"""Filter sequence of receivers to get resolved, live receivers
This is a generator which will iterate over
the passed sequence, checking for weak references
and resolving them, then returning all live
receivers.
"""
for receiver in receivers:
if isinstance(receiver, WEAKREF_TYPES):
# Dereference the weak reference.
receiver = receiver()
if receiver is not None:
yield receiver
else:
yield receiver
def getAllReceivers(sender=Any, signal=Any):
"""Get list of all receivers from global tables
This gets all receivers which should receive
the given signal from sender, each receiver should
be produced only once by the resulting generator
"""
receivers = {}
for set in (
# Get receivers that receive *this* signal from *this* sender.
getReceivers(sender, signal),
# Add receivers that receive *any* signal from *this* sender.
getReceivers(sender, Any),
# Add receivers that receive *this* signal from *any* sender.
getReceivers(Any, signal),
# Add receivers that receive *any* signal from *any* sender.
getReceivers(Any, Any),
):
for receiver in set:
if receiver: # filter out dead instance-method weakrefs
try:
if receiver not in receivers:
receivers[receiver] = 1
yield receiver
except TypeError:
# dead weakrefs raise TypeError on hash...
pass
def send(signal=Any, sender=Anonymous, *arguments, **named):
"""Send signal from sender to all connected receivers.
signal -- (hashable) signal value, see connect for details
sender -- the sender of the signal
if Any, only receivers registered for Any will receive
the message.
if Anonymous, only receivers registered to receive
messages from Anonymous or Any will receive the message
Otherwise can be any python object (normally one
registered with a connect if you actually want
something to occur).
arguments -- positional arguments which will be passed to
*all* receivers. Note that this may raise TypeErrors
if the receivers do not allow the particular arguments.
Note also that arguments are applied before named
arguments, so they should be used with care.
named -- named arguments which will be filtered according
to the parameters of the receivers to only provide those
acceptable to the receiver.
Return a list of tuple pairs [(receiver, response), ... ]
if any receiver raises an error, the error propagates back
through send, terminating the dispatch loop, so it is quite
possible to not have all receivers called if a raises an
error.
"""
# Call each receiver with whatever arguments it can accept.
# Return a list of tuple pairs [(receiver, response), ... ].
responses = []
for receiver in liveReceivers(getAllReceivers(sender, signal)):
response = robustapply.robustApply(
receiver,
signal=signal,
sender=sender,
*arguments,
**named
)
responses.append((receiver, response))
return responses
def sendExact(signal=Any, sender=Anonymous, *arguments, **named):
"""Send signal only to those receivers registered for exact message
sendExact allows for avoiding Any/Anonymous registered
handlers, sending only to those receivers explicitly
registered for a particular signal on a particular
sender.
"""
responses = []
for receiver in liveReceivers(getReceivers(sender, signal)):
response = robustapply.robustApply(
receiver,
signal=signal,
sender=sender,
*arguments,
**named
)
responses.append((receiver, response))
return responses
def _removeReceiver(receiver):
"""Remove receiver from connections."""
if not sendersBack:
# During module cleanup the mapping will be replaced with None
return False
backKey = id(receiver)
try:
backSet = sendersBack.pop(backKey)
except KeyError as err:
return False
else:
for senderkey in backSet:
try:
signals = connections[senderkey].keys()
except KeyError as err:
pass
else:
for signal in signals:
try:
receivers = connections[senderkey][signal]
except KeyError:
pass
else:
try:
receivers.remove(receiver)
except Exception as err:
pass
_cleanupConnections(senderkey, signal)
def _cleanupConnections(senderkey, signal):
"""Delete any empty signals for senderkey. Delete senderkey if empty."""
try:
receivers = connections[senderkey][signal]
except:
pass
else:
if not receivers:
# No more connected receivers. Therefore, remove the signal.
try:
signals = connections[senderkey]
except KeyError:
pass
else:
del signals[signal]
if not signals:
# No more signal connections. Therefore, remove the sender.
_removeSender(senderkey)
def _removeSender(senderkey):
"""Remove senderkey from connections."""
_removeBackrefs(senderkey)
try:
del connections[senderkey]
except KeyError:
pass
# Senderkey will only be in senders dictionary if sender
# could be weakly referenced.
try:
del senders[senderkey]
except:
pass
def _removeBackrefs(senderkey):
"""Remove all back-references to this senderkey"""
try:
signals = connections[senderkey]
except KeyError:
signals = None
else:
items = signals.items()
def allReceivers():
for signal, set in items:
for item in set:
yield item
for receiver in allReceivers():
_killBackref(receiver, senderkey)
def _removeOldBackRefs(senderkey, signal, receiver, receivers):
"""Kill old sendersBack references from receiver
This guards against multiple registration of the same
receiver for a given signal and sender leaking memory
as old back reference records build up.
Also removes old receiver instance from receivers
"""
try:
index = receivers.index(receiver)
# need to scan back references here and remove senderkey
except ValueError:
return False
else:
oldReceiver = receivers[index]
del receivers[index]
found = 0
signals = connections.get(signal)
if signals is not None:
for sig, recs in six.iteritems(connections.get(signal, {})):
if sig != signal:
for rec in recs:
if rec is oldReceiver:
found = 1
break
if not found:
_killBackref(oldReceiver, senderkey)
return True
return False
def _killBackref(receiver, senderkey):
"""Do the actual removal of back reference from receiver to senderkey"""
receiverkey = id(receiver)
set = sendersBack.get(receiverkey, ())
while senderkey in set:
try:
set.remove(senderkey)
except:
break
if not set:
try:
del sendersBack[receiverkey]
except KeyError:
pass
return True
| bsd-3-clause |
beni55/django | django/contrib/sessions/backends/cache.py | 61 | 2497 | from django.conf import settings
from django.contrib.sessions.backends.base import CreateError, SessionBase
from django.core.cache import caches
from django.utils.six.moves import range
KEY_PREFIX = "django.contrib.sessions.cache"
class SessionStore(SessionBase):
"""
A cache-based session store.
"""
def __init__(self, session_key=None):
self._cache = caches[settings.SESSION_CACHE_ALIAS]
super(SessionStore, self).__init__(session_key)
@property
def cache_key(self):
return KEY_PREFIX + self._get_or_create_session_key()
def load(self):
try:
session_data = self._cache.get(self.cache_key, None)
except Exception:
# Some backends (e.g. memcache) raise an exception on invalid
# cache keys. If this happens, reset the session. See #17810.
session_data = None
if session_data is not None:
return session_data
self.create()
return {}
def create(self):
# Because a cache can fail silently (e.g. memcache), we don't know if
# we are failing to create a new session because of a key collision or
# because the cache is missing. So we try for a (large) number of times
# and then raise an exception. That's the risk you shoulder if using
# cache backing.
for i in range(10000):
self._session_key = self._get_new_session_key()
try:
self.save(must_create=True)
except CreateError:
continue
self.modified = True
return
raise RuntimeError(
"Unable to create a new session key. "
"It is likely that the cache is unavailable.")
def save(self, must_create=False):
if must_create:
func = self._cache.add
else:
func = self._cache.set
result = func(self.cache_key,
self._get_session(no_load=must_create),
self.get_expiry_age())
if must_create and not result:
raise CreateError
def exists(self, session_key):
return (KEY_PREFIX + session_key) in self._cache
def delete(self, session_key=None):
if session_key is None:
if self.session_key is None:
return
session_key = self.session_key
self._cache.delete(KEY_PREFIX + session_key)
@classmethod
def clear_expired(cls):
pass
| bsd-3-clause |
abaditsegay/arangodb | 3rdParty/V8-4.3.61/third_party/python_26/Lib/encodings/iso8859_9.py | 593 | 13412 | """ Python Character Mapping Codec iso8859_9 generated from 'MAPPINGS/ISO8859/8859-9.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='iso8859-9',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> NULL
u'\x01' # 0x01 -> START OF HEADING
u'\x02' # 0x02 -> START OF TEXT
u'\x03' # 0x03 -> END OF TEXT
u'\x04' # 0x04 -> END OF TRANSMISSION
u'\x05' # 0x05 -> ENQUIRY
u'\x06' # 0x06 -> ACKNOWLEDGE
u'\x07' # 0x07 -> BELL
u'\x08' # 0x08 -> BACKSPACE
u'\t' # 0x09 -> HORIZONTAL TABULATION
u'\n' # 0x0A -> LINE FEED
u'\x0b' # 0x0B -> VERTICAL TABULATION
u'\x0c' # 0x0C -> FORM FEED
u'\r' # 0x0D -> CARRIAGE RETURN
u'\x0e' # 0x0E -> SHIFT OUT
u'\x0f' # 0x0F -> SHIFT IN
u'\x10' # 0x10 -> DATA LINK ESCAPE
u'\x11' # 0x11 -> DEVICE CONTROL ONE
u'\x12' # 0x12 -> DEVICE CONTROL TWO
u'\x13' # 0x13 -> DEVICE CONTROL THREE
u'\x14' # 0x14 -> DEVICE CONTROL FOUR
u'\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x16 -> SYNCHRONOUS IDLE
u'\x17' # 0x17 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x18 -> CANCEL
u'\x19' # 0x19 -> END OF MEDIUM
u'\x1a' # 0x1A -> SUBSTITUTE
u'\x1b' # 0x1B -> ESCAPE
u'\x1c' # 0x1C -> FILE SEPARATOR
u'\x1d' # 0x1D -> GROUP SEPARATOR
u'\x1e' # 0x1E -> RECORD SEPARATOR
u'\x1f' # 0x1F -> UNIT SEPARATOR
u' ' # 0x20 -> SPACE
u'!' # 0x21 -> EXCLAMATION MARK
u'"' # 0x22 -> QUOTATION MARK
u'#' # 0x23 -> NUMBER SIGN
u'$' # 0x24 -> DOLLAR SIGN
u'%' # 0x25 -> PERCENT SIGN
u'&' # 0x26 -> AMPERSAND
u"'" # 0x27 -> APOSTROPHE
u'(' # 0x28 -> LEFT PARENTHESIS
u')' # 0x29 -> RIGHT PARENTHESIS
u'*' # 0x2A -> ASTERISK
u'+' # 0x2B -> PLUS SIGN
u',' # 0x2C -> COMMA
u'-' # 0x2D -> HYPHEN-MINUS
u'.' # 0x2E -> FULL STOP
u'/' # 0x2F -> SOLIDUS
u'0' # 0x30 -> DIGIT ZERO
u'1' # 0x31 -> DIGIT ONE
u'2' # 0x32 -> DIGIT TWO
u'3' # 0x33 -> DIGIT THREE
u'4' # 0x34 -> DIGIT FOUR
u'5' # 0x35 -> DIGIT FIVE
u'6' # 0x36 -> DIGIT SIX
u'7' # 0x37 -> DIGIT SEVEN
u'8' # 0x38 -> DIGIT EIGHT
u'9' # 0x39 -> DIGIT NINE
u':' # 0x3A -> COLON
u';' # 0x3B -> SEMICOLON
u'<' # 0x3C -> LESS-THAN SIGN
u'=' # 0x3D -> EQUALS SIGN
u'>' # 0x3E -> GREATER-THAN SIGN
u'?' # 0x3F -> QUESTION MARK
u'@' # 0x40 -> COMMERCIAL AT
u'A' # 0x41 -> LATIN CAPITAL LETTER A
u'B' # 0x42 -> LATIN CAPITAL LETTER B
u'C' # 0x43 -> LATIN CAPITAL LETTER C
u'D' # 0x44 -> LATIN CAPITAL LETTER D
u'E' # 0x45 -> LATIN CAPITAL LETTER E
u'F' # 0x46 -> LATIN CAPITAL LETTER F
u'G' # 0x47 -> LATIN CAPITAL LETTER G
u'H' # 0x48 -> LATIN CAPITAL LETTER H
u'I' # 0x49 -> LATIN CAPITAL LETTER I
u'J' # 0x4A -> LATIN CAPITAL LETTER J
u'K' # 0x4B -> LATIN CAPITAL LETTER K
u'L' # 0x4C -> LATIN CAPITAL LETTER L
u'M' # 0x4D -> LATIN CAPITAL LETTER M
u'N' # 0x4E -> LATIN CAPITAL LETTER N
u'O' # 0x4F -> LATIN CAPITAL LETTER O
u'P' # 0x50 -> LATIN CAPITAL LETTER P
u'Q' # 0x51 -> LATIN CAPITAL LETTER Q
u'R' # 0x52 -> LATIN CAPITAL LETTER R
u'S' # 0x53 -> LATIN CAPITAL LETTER S
u'T' # 0x54 -> LATIN CAPITAL LETTER T
u'U' # 0x55 -> LATIN CAPITAL LETTER U
u'V' # 0x56 -> LATIN CAPITAL LETTER V
u'W' # 0x57 -> LATIN CAPITAL LETTER W
u'X' # 0x58 -> LATIN CAPITAL LETTER X
u'Y' # 0x59 -> LATIN CAPITAL LETTER Y
u'Z' # 0x5A -> LATIN CAPITAL LETTER Z
u'[' # 0x5B -> LEFT SQUARE BRACKET
u'\\' # 0x5C -> REVERSE SOLIDUS
u']' # 0x5D -> RIGHT SQUARE BRACKET
u'^' # 0x5E -> CIRCUMFLEX ACCENT
u'_' # 0x5F -> LOW LINE
u'`' # 0x60 -> GRAVE ACCENT
u'a' # 0x61 -> LATIN SMALL LETTER A
u'b' # 0x62 -> LATIN SMALL LETTER B
u'c' # 0x63 -> LATIN SMALL LETTER C
u'd' # 0x64 -> LATIN SMALL LETTER D
u'e' # 0x65 -> LATIN SMALL LETTER E
u'f' # 0x66 -> LATIN SMALL LETTER F
u'g' # 0x67 -> LATIN SMALL LETTER G
u'h' # 0x68 -> LATIN SMALL LETTER H
u'i' # 0x69 -> LATIN SMALL LETTER I
u'j' # 0x6A -> LATIN SMALL LETTER J
u'k' # 0x6B -> LATIN SMALL LETTER K
u'l' # 0x6C -> LATIN SMALL LETTER L
u'm' # 0x6D -> LATIN SMALL LETTER M
u'n' # 0x6E -> LATIN SMALL LETTER N
u'o' # 0x6F -> LATIN SMALL LETTER O
u'p' # 0x70 -> LATIN SMALL LETTER P
u'q' # 0x71 -> LATIN SMALL LETTER Q
u'r' # 0x72 -> LATIN SMALL LETTER R
u's' # 0x73 -> LATIN SMALL LETTER S
u't' # 0x74 -> LATIN SMALL LETTER T
u'u' # 0x75 -> LATIN SMALL LETTER U
u'v' # 0x76 -> LATIN SMALL LETTER V
u'w' # 0x77 -> LATIN SMALL LETTER W
u'x' # 0x78 -> LATIN SMALL LETTER X
u'y' # 0x79 -> LATIN SMALL LETTER Y
u'z' # 0x7A -> LATIN SMALL LETTER Z
u'{' # 0x7B -> LEFT CURLY BRACKET
u'|' # 0x7C -> VERTICAL LINE
u'}' # 0x7D -> RIGHT CURLY BRACKET
u'~' # 0x7E -> TILDE
u'\x7f' # 0x7F -> DELETE
u'\x80' # 0x80 -> <control>
u'\x81' # 0x81 -> <control>
u'\x82' # 0x82 -> <control>
u'\x83' # 0x83 -> <control>
u'\x84' # 0x84 -> <control>
u'\x85' # 0x85 -> <control>
u'\x86' # 0x86 -> <control>
u'\x87' # 0x87 -> <control>
u'\x88' # 0x88 -> <control>
u'\x89' # 0x89 -> <control>
u'\x8a' # 0x8A -> <control>
u'\x8b' # 0x8B -> <control>
u'\x8c' # 0x8C -> <control>
u'\x8d' # 0x8D -> <control>
u'\x8e' # 0x8E -> <control>
u'\x8f' # 0x8F -> <control>
u'\x90' # 0x90 -> <control>
u'\x91' # 0x91 -> <control>
u'\x92' # 0x92 -> <control>
u'\x93' # 0x93 -> <control>
u'\x94' # 0x94 -> <control>
u'\x95' # 0x95 -> <control>
u'\x96' # 0x96 -> <control>
u'\x97' # 0x97 -> <control>
u'\x98' # 0x98 -> <control>
u'\x99' # 0x99 -> <control>
u'\x9a' # 0x9A -> <control>
u'\x9b' # 0x9B -> <control>
u'\x9c' # 0x9C -> <control>
u'\x9d' # 0x9D -> <control>
u'\x9e' # 0x9E -> <control>
u'\x9f' # 0x9F -> <control>
u'\xa0' # 0xA0 -> NO-BREAK SPACE
u'\xa1' # 0xA1 -> INVERTED EXCLAMATION MARK
u'\xa2' # 0xA2 -> CENT SIGN
u'\xa3' # 0xA3 -> POUND SIGN
u'\xa4' # 0xA4 -> CURRENCY SIGN
u'\xa5' # 0xA5 -> YEN SIGN
u'\xa6' # 0xA6 -> BROKEN BAR
u'\xa7' # 0xA7 -> SECTION SIGN
u'\xa8' # 0xA8 -> DIAERESIS
u'\xa9' # 0xA9 -> COPYRIGHT SIGN
u'\xaa' # 0xAA -> FEMININE ORDINAL INDICATOR
u'\xab' # 0xAB -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xac' # 0xAC -> NOT SIGN
u'\xad' # 0xAD -> SOFT HYPHEN
u'\xae' # 0xAE -> REGISTERED SIGN
u'\xaf' # 0xAF -> MACRON
u'\xb0' # 0xB0 -> DEGREE SIGN
u'\xb1' # 0xB1 -> PLUS-MINUS SIGN
u'\xb2' # 0xB2 -> SUPERSCRIPT TWO
u'\xb3' # 0xB3 -> SUPERSCRIPT THREE
u'\xb4' # 0xB4 -> ACUTE ACCENT
u'\xb5' # 0xB5 -> MICRO SIGN
u'\xb6' # 0xB6 -> PILCROW SIGN
u'\xb7' # 0xB7 -> MIDDLE DOT
u'\xb8' # 0xB8 -> CEDILLA
u'\xb9' # 0xB9 -> SUPERSCRIPT ONE
u'\xba' # 0xBA -> MASCULINE ORDINAL INDICATOR
u'\xbb' # 0xBB -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbc' # 0xBC -> VULGAR FRACTION ONE QUARTER
u'\xbd' # 0xBD -> VULGAR FRACTION ONE HALF
u'\xbe' # 0xBE -> VULGAR FRACTION THREE QUARTERS
u'\xbf' # 0xBF -> INVERTED QUESTION MARK
u'\xc0' # 0xC0 -> LATIN CAPITAL LETTER A WITH GRAVE
u'\xc1' # 0xC1 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xc2' # 0xC2 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
u'\xc3' # 0xC3 -> LATIN CAPITAL LETTER A WITH TILDE
u'\xc4' # 0xC4 -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc5' # 0xC5 -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc6' # 0xC6 -> LATIN CAPITAL LETTER AE
u'\xc7' # 0xC7 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xc8' # 0xC8 -> LATIN CAPITAL LETTER E WITH GRAVE
u'\xc9' # 0xC9 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xca' # 0xCA -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
u'\xcb' # 0xCB -> LATIN CAPITAL LETTER E WITH DIAERESIS
u'\xcc' # 0xCC -> LATIN CAPITAL LETTER I WITH GRAVE
u'\xcd' # 0xCD -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xce' # 0xCE -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
u'\xcf' # 0xCF -> LATIN CAPITAL LETTER I WITH DIAERESIS
u'\u011e' # 0xD0 -> LATIN CAPITAL LETTER G WITH BREVE
u'\xd1' # 0xD1 -> LATIN CAPITAL LETTER N WITH TILDE
u'\xd2' # 0xD2 -> LATIN CAPITAL LETTER O WITH GRAVE
u'\xd3' # 0xD3 -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xd4' # 0xD4 -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
u'\xd5' # 0xD5 -> LATIN CAPITAL LETTER O WITH TILDE
u'\xd6' # 0xD6 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xd7' # 0xD7 -> MULTIPLICATION SIGN
u'\xd8' # 0xD8 -> LATIN CAPITAL LETTER O WITH STROKE
u'\xd9' # 0xD9 -> LATIN CAPITAL LETTER U WITH GRAVE
u'\xda' # 0xDA -> LATIN CAPITAL LETTER U WITH ACUTE
u'\xdb' # 0xDB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX
u'\xdc' # 0xDC -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\u0130' # 0xDD -> LATIN CAPITAL LETTER I WITH DOT ABOVE
u'\u015e' # 0xDE -> LATIN CAPITAL LETTER S WITH CEDILLA
u'\xdf' # 0xDF -> LATIN SMALL LETTER SHARP S
u'\xe0' # 0xE0 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe1' # 0xE1 -> LATIN SMALL LETTER A WITH ACUTE
u'\xe2' # 0xE2 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe3' # 0xE3 -> LATIN SMALL LETTER A WITH TILDE
u'\xe4' # 0xE4 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe5' # 0xE5 -> LATIN SMALL LETTER A WITH RING ABOVE
u'\xe6' # 0xE6 -> LATIN SMALL LETTER AE
u'\xe7' # 0xE7 -> LATIN SMALL LETTER C WITH CEDILLA
u'\xe8' # 0xE8 -> LATIN SMALL LETTER E WITH GRAVE
u'\xe9' # 0xE9 -> LATIN SMALL LETTER E WITH ACUTE
u'\xea' # 0xEA -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0xEB -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xec' # 0xEC -> LATIN SMALL LETTER I WITH GRAVE
u'\xed' # 0xED -> LATIN SMALL LETTER I WITH ACUTE
u'\xee' # 0xEE -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\xef' # 0xEF -> LATIN SMALL LETTER I WITH DIAERESIS
u'\u011f' # 0xF0 -> LATIN SMALL LETTER G WITH BREVE
u'\xf1' # 0xF1 -> LATIN SMALL LETTER N WITH TILDE
u'\xf2' # 0xF2 -> LATIN SMALL LETTER O WITH GRAVE
u'\xf3' # 0xF3 -> LATIN SMALL LETTER O WITH ACUTE
u'\xf4' # 0xF4 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf5' # 0xF5 -> LATIN SMALL LETTER O WITH TILDE
u'\xf6' # 0xF6 -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xf7' # 0xF7 -> DIVISION SIGN
u'\xf8' # 0xF8 -> LATIN SMALL LETTER O WITH STROKE
u'\xf9' # 0xF9 -> LATIN SMALL LETTER U WITH GRAVE
u'\xfa' # 0xFA -> LATIN SMALL LETTER U WITH ACUTE
u'\xfb' # 0xFB -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\xfc' # 0xFC -> LATIN SMALL LETTER U WITH DIAERESIS
u'\u0131' # 0xFD -> LATIN SMALL LETTER DOTLESS I
u'\u015f' # 0xFE -> LATIN SMALL LETTER S WITH CEDILLA
u'\xff' # 0xFF -> LATIN SMALL LETTER Y WITH DIAERESIS
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
| apache-2.0 |
MaisonLogicielLibre/TableauDeBord | app/floorMap/urls.py | 2 | 1068 | # coding: utf-8
from django.conf.urls import patterns, url
from app.floorMap import views
urlpatterns = patterns(
'',
# Floor map page
url(r'^$', views.FloorMapIndex.as_view(), name='index'),
# Settings page
url(r'^settings$', views.SettingsUpdate.as_view(), name='settings'),
# Forms for room details
url(
r'^room/(?P<pk>\d+)/$',
views.RoomDetails.as_view(),
name='room_details'
),
url(
r'^room/update/(?P<pk>\d+)/',
views.RoomUpdate.as_view(),
name='room_update'
),
# Forms for rentals
url(
r'^rental/add$',
views.RentalCreate.as_view(),
name='rental_create'
),
url(
r'^rental/add/(?P<pk>\d+)/$',
views.RentalCreate.as_view(),
name='rental_create'
),
url(
r'^rental/update/(?P<pk>\d+)/$',
views.RentalUpdate.as_view(),
name='rental_update'
),
url(
r'^rental/delete/(?P<pk>\d+)/$',
views.RentalDelete.as_view(),
name='rental_delete'
),
)
| gpl-3.0 |
PaloAltoNetworks/minemeld-core | minemeld/flask/prototypeapi.py | 1 | 10925 | # Copyright 2015-2016 Palo Alto Networks, 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.
import sys
import os
import os.path
import json
import yaml
import filelock
from flask import jsonify, request
import minemeld.loader
from . import config
from .utils import running_config, committed_config
from .aaa import MMBlueprint
from .logger import LOG
__all__ = ['BLUEPRINT']
PROTOTYPE_ENV = 'MINEMELD_PROTOTYPE_PATH'
LOCAL_PROTOTYPE_PATH = 'MINEMELD_LOCAL_PROTOTYPE_PATH'
BLUEPRINT = MMBlueprint('prototype', __name__, url_prefix='')
PROTOTYPE_PATHS = None
def _prototype_paths():
global PROTOTYPE_PATHS
if PROTOTYPE_PATHS is not None:
return PROTOTYPE_PATHS
paths = config.get(PROTOTYPE_ENV, None)
if paths is None:
raise RuntimeError('{} environment variable not set'.format(PROTOTYPE_ENV))
paths = paths.split(':')
prototype_eps = minemeld.loader.map(minemeld.loader.MM_PROTOTYPES_ENTRYPOINT)
for pname, mmep in prototype_eps.iteritems():
if not mmep.loadable:
LOG.info('Prototype entry point {} not loadable, ignored'.format(pname))
continue
try:
# even if old dist is no longer available, old module could be cached
cmodule = sys.modules.get(mmep.ep.module_name, None)
cmodule_path = getattr(cmodule, '__path__', None)
if cmodule is not None and cmodule_path is not None:
if not cmodule_path[0].startswith(mmep.ep.dist.location):
LOG.info('Invalidating cache for {}'.format(mmep.ep.module_name))
sys.modules.pop(mmep.ep.module_name)
ep = mmep.ep.load()
# we add prototype paths in front, to let extensions override default protos
paths.insert(0, ep())
except:
LOG.exception('Exception loading paths from {}'.format(pname))
PROTOTYPE_PATHS = paths
return paths
def _local_library_path(prototypename):
toks = prototypename.split('.', 1)
if len(toks) != 2:
raise ValueError('bad prototype name')
library, prototype = toks
if os.path.basename(library) != library:
raise ValueError('bad library name, nice try')
if library != 'minemeldlocal':
raise ValueError('invalid library')
library_filename = library+'.yml'
local_path = config.get(LOCAL_PROTOTYPE_PATH)
if local_path is None:
paths = os.getenv(PROTOTYPE_ENV, None)
if paths is None:
raise RuntimeError(
'%s environment variable not set' %
(PROTOTYPE_ENV)
)
paths = paths.split(':')
for p in paths:
if '/local/' in p:
local_path = p
break
if local_path is None:
raise RuntimeError(
'No local path in %s' % PROTOTYPE_ENV
)
library_path = os.path.join(local_path, library_filename)
return library_path, prototype
@BLUEPRINT.route('/prototype', methods=['GET'], read_write=False)
def list_prototypes():
paths = _prototype_paths()
prototypes = {}
for p in paths:
try:
for plibrary in os.listdir(p):
if not plibrary.endswith('.yml'):
continue
plibraryname, _ = plibrary.rsplit('.', 1)
with open(os.path.join(p, plibrary), 'r') as f:
pcontents = yaml.safe_load(f)
if plibraryname not in prototypes:
prototypes[plibraryname] = pcontents
continue
# oldest has precedence
newprotos = pcontents.get('prototypes', {})
currprotos = prototypes[plibraryname].get('prototypes', {})
newprotos.update(currprotos)
prototypes[plibraryname]['prototypes'] = newprotos
except:
LOG.exception('Error loading libraries from %s', p)
return jsonify(result=prototypes)
@BLUEPRINT.route('/prototype/<prototypename>', methods=['GET'], read_write=False)
def get_prototype(prototypename):
toks = prototypename.split('.', 1)
if len(toks) != 2:
return jsonify(error={'message': 'bad prototype name'}), 400
library, prototype = toks
if os.path.basename(library) != library:
return jsonify(error={'message': 'bad library name, nice try'}), 400
library_filename = library+'.yml'
paths = _prototype_paths()
for path in paths:
full_library_name = os.path.join(path, library_filename)
if not os.path.isfile(full_library_name):
continue
with open(full_library_name, 'r') as f:
library_contents = yaml.safe_load(f)
prototypes = library_contents.get('prototypes', None)
if prototypes is None:
continue
if prototype not in prototypes:
continue
curr_prototype = prototypes[prototype]
result = {
'class': curr_prototype['class'],
'developmentStatus': None,
'config': None,
'nodeType': None,
'description': None,
'indicatorTypes': None,
'tags': None
}
if 'config' in curr_prototype:
result['config'] = yaml.dump(
curr_prototype['config'],
indent=4,
default_flow_style=False
)
if 'development_status' in curr_prototype:
result['developmentStatus'] = curr_prototype['development_status']
if 'node_type' in curr_prototype:
result['nodeType'] = curr_prototype['node_type']
if 'description' in curr_prototype:
result['description'] = curr_prototype['description']
if 'indicator_types' in curr_prototype:
result['indicatorTypes'] = curr_prototype['indicator_types']
if 'tags' in curr_prototype:
result['tags'] = curr_prototype['tags']
return jsonify(result=result), 200
@BLUEPRINT.route('/prototype/<prototypename>', methods=['POST'], read_write=True)
def add_local_prototype(prototypename):
AUTHOR_ = 'minemeld-web'
DESCRIPTION_ = 'Local prototype library managed via MineMeld WebUI'
try:
library_path, prototype = _local_library_path(prototypename)
except ValueError as e:
return jsonify(error={'message': str(e)}), 400
lock = filelock.FileLock('{}.lock'.format(library_path))
with lock.acquire(timeout=10):
if os.path.isfile(library_path):
with open(library_path, 'r') as f:
library_contents = yaml.safe_load(f)
if not isinstance(library_contents, dict):
library_contents = {}
if 'description' not in library_contents:
library_contents['description'] = DESCRIPTION_
if 'prototypes' not in library_contents:
library_contents['prototypes'] = {}
if 'author' not in library_contents:
library_contents['author'] = AUTHOR_
else:
library_contents = {
'author': AUTHOR_,
'description': DESCRIPTION_,
'prototypes': {}
}
try:
incoming_prototype = request.get_json()
except Exception as e:
return jsonify(error={'message': str(e)}), 400
new_prototype = {
'class': incoming_prototype['class'],
}
if 'config' in incoming_prototype:
try:
new_prototype['config'] = yaml.safe_load(
incoming_prototype['config']
)
except Exception as e:
return jsonify(error={'message': 'invalid YAML in config'}), 400
if 'developmentStatus' in incoming_prototype:
new_prototype['development_status'] = \
incoming_prototype['developmentStatus']
if 'nodeType' in incoming_prototype:
new_prototype['node_type'] = incoming_prototype['nodeType']
if 'description' in incoming_prototype:
new_prototype['description'] = incoming_prototype['description']
if 'indicatorTypes' in incoming_prototype:
new_prototype['indicator_types'] = incoming_prototype['indicatorTypes']
if 'tags' in incoming_prototype:
new_prototype['tags'] = incoming_prototype['tags']
library_contents['prototypes'][prototype] = new_prototype
with open(library_path, 'w') as f:
yaml.safe_dump(library_contents, f, indent=4, default_flow_style=False)
return jsonify(result='OK'), 200
@BLUEPRINT.route('/prototype/<prototypename>', methods=['DELETE'], read_write=True)
def delete_local_prototype(prototypename):
try:
library_path, prototype = _local_library_path(prototypename)
except ValueError as e:
return jsonify(error={'message': str(e)}), 400
if not os.path.isfile(library_path):
return jsonify(error={'message': 'missing local prototype library'}), 400
# check if the proto is in use in running or committed config
rcconfig = running_config()
for nodename, nodevalue in rcconfig.get('nodes', {}).iteritems():
if 'prototype' not in nodevalue:
continue
if nodevalue['prototype'] == prototypename:
return jsonify(error={'message': 'prototype in use in running config'}), 400
ccconfig = committed_config()
for nodename, nodevalue in ccconfig.get('nodes', {}).iteritems():
if 'prototype' not in nodevalue:
continue
if nodevalue['prototype'] == prototypename:
return jsonify(error={'message': 'prototype in use in committed config'}), 400
lock = filelock.FileLock('{}.lock'.format(library_path))
with lock.acquire(timeout=10):
with open(library_path, 'r') as f:
library_contents = yaml.safe_load(f)
if not isinstance(library_contents, dict):
return jsonify(error={'message': 'invalid local prototype library'}), 400
library_contents['prototypes'].pop(prototype, None)
with open(library_path, 'w') as f:
yaml.safe_dump(library_contents, f, indent=4, default_flow_style=False)
return jsonify(result='OK'), 200
def reset_prototype_paths():
global PROTOTYPE_PATHS
PROTOTYPE_PATHS = None
| apache-2.0 |
kaushik94/boto | tests/devpay/test_s3.py | 136 | 7410 | #!/usr/bin/env python
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
"""
Some unit tests for the S3Connection
"""
import time
import os
import urllib
from boto.s3.connection import S3Connection
from boto.exception import S3PermissionsError
# this test requires a devpay product and user token to run:
AMAZON_USER_TOKEN = '{UserToken}...your token here...'
DEVPAY_HEADERS = { 'x-amz-security-token': AMAZON_USER_TOKEN }
def test():
print '--- running S3Connection tests (DevPay) ---'
c = S3Connection()
# create a new, empty bucket
bucket_name = 'test-%d' % int(time.time())
bucket = c.create_bucket(bucket_name, headers=DEVPAY_HEADERS)
# now try a get_bucket call and see if it's really there
bucket = c.get_bucket(bucket_name, headers=DEVPAY_HEADERS)
# test logging
logging_bucket = c.create_bucket(bucket_name + '-log', headers=DEVPAY_HEADERS)
logging_bucket.set_as_logging_target(headers=DEVPAY_HEADERS)
bucket.enable_logging(target_bucket=logging_bucket, target_prefix=bucket.name, headers=DEVPAY_HEADERS)
bucket.disable_logging(headers=DEVPAY_HEADERS)
c.delete_bucket(logging_bucket, headers=DEVPAY_HEADERS)
# create a new key and store it's content from a string
k = bucket.new_key()
k.name = 'foobar'
s1 = 'This is a test of file upload and download'
s2 = 'This is a second string to test file upload and download'
k.set_contents_from_string(s1, headers=DEVPAY_HEADERS)
fp = open('foobar', 'wb')
# now get the contents from s3 to a local file
k.get_contents_to_file(fp, headers=DEVPAY_HEADERS)
fp.close()
fp = open('foobar')
# check to make sure content read from s3 is identical to original
assert s1 == fp.read(), 'corrupted file'
fp.close()
# test generated URLs
url = k.generate_url(3600, headers=DEVPAY_HEADERS)
file = urllib.urlopen(url)
assert s1 == file.read(), 'invalid URL %s' % url
url = k.generate_url(3600, force_http=True, headers=DEVPAY_HEADERS)
file = urllib.urlopen(url)
assert s1 == file.read(), 'invalid URL %s' % url
bucket.delete_key(k, headers=DEVPAY_HEADERS)
# test a few variations on get_all_keys - first load some data
# for the first one, let's override the content type
phony_mimetype = 'application/x-boto-test'
headers = {'Content-Type': phony_mimetype}
headers.update(DEVPAY_HEADERS)
k.name = 'foo/bar'
k.set_contents_from_string(s1, headers)
k.name = 'foo/bas'
k.set_contents_from_filename('foobar', headers=DEVPAY_HEADERS)
k.name = 'foo/bat'
k.set_contents_from_string(s1, headers=DEVPAY_HEADERS)
k.name = 'fie/bar'
k.set_contents_from_string(s1, headers=DEVPAY_HEADERS)
k.name = 'fie/bas'
k.set_contents_from_string(s1, headers=DEVPAY_HEADERS)
k.name = 'fie/bat'
k.set_contents_from_string(s1, headers=DEVPAY_HEADERS)
# try resetting the contents to another value
md5 = k.md5
k.set_contents_from_string(s2, headers=DEVPAY_HEADERS)
assert k.md5 != md5
os.unlink('foobar')
all = bucket.get_all_keys(headers=DEVPAY_HEADERS)
assert len(all) == 6
rs = bucket.get_all_keys(prefix='foo', headers=DEVPAY_HEADERS)
assert len(rs) == 3
rs = bucket.get_all_keys(prefix='', delimiter='/', headers=DEVPAY_HEADERS)
assert len(rs) == 2
rs = bucket.get_all_keys(maxkeys=5, headers=DEVPAY_HEADERS)
assert len(rs) == 5
# test the lookup method
k = bucket.lookup('foo/bar', headers=DEVPAY_HEADERS)
assert isinstance(k, bucket.key_class)
assert k.content_type == phony_mimetype
k = bucket.lookup('notthere', headers=DEVPAY_HEADERS)
assert k == None
# try some metadata stuff
k = bucket.new_key()
k.name = 'has_metadata'
mdkey1 = 'meta1'
mdval1 = 'This is the first metadata value'
k.set_metadata(mdkey1, mdval1)
mdkey2 = 'meta2'
mdval2 = 'This is the second metadata value'
k.set_metadata(mdkey2, mdval2)
k.set_contents_from_string(s1, headers=DEVPAY_HEADERS)
k = bucket.lookup('has_metadata', headers=DEVPAY_HEADERS)
assert k.get_metadata(mdkey1) == mdval1
assert k.get_metadata(mdkey2) == mdval2
k = bucket.new_key()
k.name = 'has_metadata'
k.get_contents_as_string(headers=DEVPAY_HEADERS)
assert k.get_metadata(mdkey1) == mdval1
assert k.get_metadata(mdkey2) == mdval2
bucket.delete_key(k, headers=DEVPAY_HEADERS)
# test list and iterator
rs1 = bucket.list(headers=DEVPAY_HEADERS)
num_iter = 0
for r in rs1:
num_iter = num_iter + 1
rs = bucket.get_all_keys(headers=DEVPAY_HEADERS)
num_keys = len(rs)
assert num_iter == num_keys
# try a key with a funny character
k = bucket.new_key()
k.name = 'testnewline\n'
k.set_contents_from_string('This is a test', headers=DEVPAY_HEADERS)
rs = bucket.get_all_keys(headers=DEVPAY_HEADERS)
assert len(rs) == num_keys + 1
bucket.delete_key(k, headers=DEVPAY_HEADERS)
rs = bucket.get_all_keys(headers=DEVPAY_HEADERS)
assert len(rs) == num_keys
# try some acl stuff
bucket.set_acl('public-read', headers=DEVPAY_HEADERS)
policy = bucket.get_acl(headers=DEVPAY_HEADERS)
assert len(policy.acl.grants) == 2
bucket.set_acl('private', headers=DEVPAY_HEADERS)
policy = bucket.get_acl(headers=DEVPAY_HEADERS)
assert len(policy.acl.grants) == 1
k = bucket.lookup('foo/bar', headers=DEVPAY_HEADERS)
k.set_acl('public-read', headers=DEVPAY_HEADERS)
policy = k.get_acl(headers=DEVPAY_HEADERS)
assert len(policy.acl.grants) == 2
k.set_acl('private', headers=DEVPAY_HEADERS)
policy = k.get_acl(headers=DEVPAY_HEADERS)
assert len(policy.acl.grants) == 1
# try the convenience methods for grants
# this doesn't work with devpay
#bucket.add_user_grant('FULL_CONTROL',
# 'c1e724fbfa0979a4448393c59a8c055011f739b6d102fb37a65f26414653cd67',
# headers=DEVPAY_HEADERS)
try:
bucket.add_email_grant('foobar', 'foo@bar.com', headers=DEVPAY_HEADERS)
except S3PermissionsError:
pass
# now delete all keys in bucket
for k in all:
bucket.delete_key(k, headers=DEVPAY_HEADERS)
# now delete bucket
c.delete_bucket(bucket, headers=DEVPAY_HEADERS)
print '--- tests completed ---'
if __name__ == '__main__':
test()
| mit |
axt/angr | angr/analyses/cfg/indirect_jump_resolvers/x86_elf_pic_plt.py | 2 | 2758 |
import logging
import archinfo
import cle
from ....engines import SimEngineVEX
from .resolver import IndirectJumpResolver
l = logging.getLogger("angr.analyses.cfg.indirect_jump_resolvers.x86_elf_pic_plt")
class X86ElfPicPltResolver(IndirectJumpResolver):
"""
In X86 ELF position-independent code, PLT stubs uses ebx to resolve library calls, where ebx stores the address to
the beginning of the GOT. We resolve the target by forcing ebx to be the beginning of the GOT and simulate the
execution in fast path mode.
"""
def __init__(self, arch=archinfo.ArchX86(), project=None): # pylint:disable=unused-argument
super(X86ElfPicPltResolver, self).__init__(arch, timeless=True)
self._got_addr_cache = { }
def _got_addr(self, obj):
if obj not in self._got_addr_cache:
if not isinstance(obj, cle.MetaELF):
self._got_addr_cache[obj] = None
else:
# ALERT: HACKS AHEAD
got_plt_section = obj.sections_map.get('.got.plt', None)
got_section = obj.sections_map.get('.got', None)
if got_plt_section is not None:
l.debug('Use address of .got.plt section as the GOT base for object %s.', obj)
self._got_addr_cache[obj] = got_plt_section.vaddr
elif got_section is not None:
l.debug('Use address of .got section as the GOT base for object %s.', obj)
self._got_addr_cache[obj] = got_section.vaddr
else:
l.debug('Cannot find GOT base for object %s.', obj)
self._got_addr_cache[obj] = None
return self._got_addr_cache[obj]
def filter(self, cfg, addr, func_addr, block, jumpkind):
section = cfg._addr_belongs_to_section(addr)
if section.name != '.plt':
return False
if block.size != 6:
return False
if block.instructions != 1:
return False
# TODO: check whether ebx/edx is used
return True
def resolve(self, cfg, addr, func_addr, block, jumpkind):
obj = cfg.project.loader.find_object_containing(addr)
if obj is None:
return False, [ ]
got_addr = self._got_addr(obj)
if got_addr is None:
# cannot get the base address of GOT
return False, [ ]
state = cfg._initial_state.copy()
state.regs.ebx = got_addr
successors = SimEngineVEX().process(state, block, force_addr=addr)
if len(successors.flat_successors) != 1:
return False, [ ]
target = state.se.eval_one(successors.flat_successors[0].ip)
return True, [ target ]
| bsd-2-clause |
mrroach/CentralServer | csrv/model/actions/install_upgrade.py | 1 | 1402 | """Base actions for the players to take."""
from csrv.model.actions import action
from csrv.model import cost
from csrv.model import errors
from csrv.model import events
from csrv.model import game_object
from csrv.model import parameters
class InstallUpgrade(action.Action):
DESCRIPTION = '[click]: Install an agenda, asset, upgrade, or piece of ice'
COST_CLASS = cost.InstallAgendaAssetUpgradeCost
REQUEST_CLASS = parameters.InstallUpgradeRequest
def __init__(self, game, player, card=None, cost=None, server=None):
action.Action.__init__(self, game, player, card=card, cost=cost)
self.server = server
def resolve(self, response=None, ignore_clicks=False, ignore_all_costs=False):
if self.server:
if not response or not response.server == self.server:
raise errors.InvalidResponse(
'Can only be installed in %s' % self.server)
action.Action.resolve(
self,
ignore_clicks=ignore_clicks,
ignore_all_costs=ignore_all_costs)
if response and response.server:
server = response.server
for card in response.cards_to_trash:
# This gets repeated a lot. move to player
server.uninstall(card)
self.player.archives.add(card)
else:
server = self.player.new_remote_server()
self.card.install(server)
@property
def description(self):
return 'Install %s' % self.card.NAME
| apache-2.0 |
nitin-cherian/LifeLongLearning | Python/PythonProgrammingLanguage/Encapsulation/encap_env/lib/python3.5/site-packages/webencodings/mklabels.py | 512 | 1305 | """
webencodings.mklabels
~~~~~~~~~~~~~~~~~~~~~
Regenarate the webencodings.labels module.
:copyright: Copyright 2012 by Simon Sapin
:license: BSD, see LICENSE for details.
"""
import json
try:
from urllib import urlopen
except ImportError:
from urllib.request import urlopen
def assert_lower(string):
assert string == string.lower()
return string
def generate(url):
parts = ['''\
"""
webencodings.labels
~~~~~~~~~~~~~~~~~~~
Map encoding labels to their name.
:copyright: Copyright 2012 by Simon Sapin
:license: BSD, see LICENSE for details.
"""
# XXX Do not edit!
# This file is automatically generated by mklabels.py
LABELS = {
''']
labels = [
(repr(assert_lower(label)).lstrip('u'),
repr(encoding['name']).lstrip('u'))
for category in json.loads(urlopen(url).read().decode('ascii'))
for encoding in category['encodings']
for label in encoding['labels']]
max_len = max(len(label) for label, name in labels)
parts.extend(
' %s:%s %s,\n' % (label, ' ' * (max_len - len(label)), name)
for label, name in labels)
parts.append('}')
return ''.join(parts)
if __name__ == '__main__':
print(generate('http://encoding.spec.whatwg.org/encodings.json'))
| mit |
jmmease/pandas | pandas/tests/frame/test_period.py | 18 | 5005 | import numpy as np
from numpy.random import randn
from datetime import timedelta
import pandas as pd
import pandas.util.testing as tm
from pandas import (PeriodIndex, period_range, DataFrame, date_range,
Index, to_datetime, DatetimeIndex)
def _permute(obj):
return obj.take(np.random.permutation(len(obj)))
class TestPeriodIndex(object):
def setup_method(self, method):
pass
def test_as_frame_columns(self):
rng = period_range('1/1/2000', periods=5)
df = DataFrame(randn(10, 5), columns=rng)
ts = df[rng[0]]
tm.assert_series_equal(ts, df.iloc[:, 0])
# GH # 1211
repr(df)
ts = df['1/1/2000']
tm.assert_series_equal(ts, df.iloc[:, 0])
def test_frame_setitem(self):
rng = period_range('1/1/2000', periods=5, name='index')
df = DataFrame(randn(5, 3), index=rng)
df['Index'] = rng
rs = Index(df['Index'])
tm.assert_index_equal(rs, rng, check_names=False)
assert rs.name == 'Index'
assert rng.name == 'index'
rs = df.reset_index().set_index('index')
assert isinstance(rs.index, PeriodIndex)
tm.assert_index_equal(rs.index, rng)
def test_frame_to_time_stamp(self):
K = 5
index = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
df = DataFrame(randn(len(index), K), index=index)
df['mix'] = 'a'
exp_index = date_range('1/1/2001', end='12/31/2009', freq='A-DEC')
result = df.to_timestamp('D', 'end')
tm.assert_index_equal(result.index, exp_index)
tm.assert_numpy_array_equal(result.values, df.values)
exp_index = date_range('1/1/2001', end='1/1/2009', freq='AS-JAN')
result = df.to_timestamp('D', 'start')
tm.assert_index_equal(result.index, exp_index)
def _get_with_delta(delta, freq='A-DEC'):
return date_range(to_datetime('1/1/2001') + delta,
to_datetime('12/31/2009') + delta, freq=freq)
delta = timedelta(hours=23)
result = df.to_timestamp('H', 'end')
exp_index = _get_with_delta(delta)
tm.assert_index_equal(result.index, exp_index)
delta = timedelta(hours=23, minutes=59)
result = df.to_timestamp('T', 'end')
exp_index = _get_with_delta(delta)
tm.assert_index_equal(result.index, exp_index)
result = df.to_timestamp('S', 'end')
delta = timedelta(hours=23, minutes=59, seconds=59)
exp_index = _get_with_delta(delta)
tm.assert_index_equal(result.index, exp_index)
# columns
df = df.T
exp_index = date_range('1/1/2001', end='12/31/2009', freq='A-DEC')
result = df.to_timestamp('D', 'end', axis=1)
tm.assert_index_equal(result.columns, exp_index)
tm.assert_numpy_array_equal(result.values, df.values)
exp_index = date_range('1/1/2001', end='1/1/2009', freq='AS-JAN')
result = df.to_timestamp('D', 'start', axis=1)
tm.assert_index_equal(result.columns, exp_index)
delta = timedelta(hours=23)
result = df.to_timestamp('H', 'end', axis=1)
exp_index = _get_with_delta(delta)
tm.assert_index_equal(result.columns, exp_index)
delta = timedelta(hours=23, minutes=59)
result = df.to_timestamp('T', 'end', axis=1)
exp_index = _get_with_delta(delta)
tm.assert_index_equal(result.columns, exp_index)
result = df.to_timestamp('S', 'end', axis=1)
delta = timedelta(hours=23, minutes=59, seconds=59)
exp_index = _get_with_delta(delta)
tm.assert_index_equal(result.columns, exp_index)
# invalid axis
tm.assert_raises_regex(
ValueError, 'axis', df.to_timestamp, axis=2)
result1 = df.to_timestamp('5t', axis=1)
result2 = df.to_timestamp('t', axis=1)
expected = pd.date_range('2001-01-01', '2009-01-01', freq='AS')
assert isinstance(result1.columns, DatetimeIndex)
assert isinstance(result2.columns, DatetimeIndex)
tm.assert_numpy_array_equal(result1.columns.asi8, expected.asi8)
tm.assert_numpy_array_equal(result2.columns.asi8, expected.asi8)
# PeriodIndex.to_timestamp always use 'infer'
assert result1.columns.freqstr == 'AS-JAN'
assert result2.columns.freqstr == 'AS-JAN'
def test_frame_index_to_string(self):
index = PeriodIndex(['2011-1', '2011-2', '2011-3'], freq='M')
frame = DataFrame(np.random.randn(3, 4), index=index)
# it works!
frame.to_string()
def test_align_frame(self):
rng = period_range('1/1/2000', '1/1/2010', freq='A')
ts = DataFrame(np.random.randn(len(rng), 3), index=rng)
result = ts + ts[::2]
expected = ts + ts
expected.values[1::2] = np.nan
tm.assert_frame_equal(result, expected)
result = ts + _permute(ts[::2])
tm.assert_frame_equal(result, expected)
| bsd-3-clause |
xkcd1253/SocialNetworkforTwo | flask/lib/python2.7/site-packages/sqlalchemy/orm/deprecated_interfaces.py | 17 | 21784 | # orm/deprecated_interfaces.py
# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from sqlalchemy import event, util
from interfaces import EXT_CONTINUE
class MapperExtension(object):
"""Base implementation for :class:`.Mapper` event hooks.
.. note::
:class:`.MapperExtension` is deprecated. Please
refer to :func:`.event.listen` as well as
:class:`.MapperEvents`.
New extension classes subclass :class:`.MapperExtension` and are specified
using the ``extension`` mapper() argument, which is a single
:class:`.MapperExtension` or a list of such::
from sqlalchemy.orm.interfaces import MapperExtension
class MyExtension(MapperExtension):
def before_insert(self, mapper, connection, instance):
print "instance %s before insert !" % instance
m = mapper(User, users_table, extension=MyExtension())
A single mapper can maintain a chain of ``MapperExtension``
objects. When a particular mapping event occurs, the
corresponding method on each ``MapperExtension`` is invoked
serially, and each method has the ability to halt the chain
from proceeding further::
m = mapper(User, users_table, extension=[ext1, ext2, ext3])
Each ``MapperExtension`` method returns the symbol
EXT_CONTINUE by default. This symbol generally means "move
to the next ``MapperExtension`` for processing". For methods
that return objects like translated rows or new object
instances, EXT_CONTINUE means the result of the method
should be ignored. In some cases it's required for a
default mapper activity to be performed, such as adding a
new instance to a result list.
The symbol EXT_STOP has significance within a chain
of ``MapperExtension`` objects that the chain will be stopped
when this symbol is returned. Like EXT_CONTINUE, it also
has additional significance in some cases that a default
mapper activity will not be performed.
"""
@classmethod
def _adapt_instrument_class(cls, self, listener):
cls._adapt_listener_methods(self, listener, ('instrument_class',))
@classmethod
def _adapt_listener(cls, self, listener):
cls._adapt_listener_methods(
self, listener,
(
'init_instance',
'init_failed',
'translate_row',
'create_instance',
'append_result',
'populate_instance',
'reconstruct_instance',
'before_insert',
'after_insert',
'before_update',
'after_update',
'before_delete',
'after_delete'
))
@classmethod
def _adapt_listener_methods(cls, self, listener, methods):
for meth in methods:
me_meth = getattr(MapperExtension, meth)
ls_meth = getattr(listener, meth)
if not util.methods_equivalent(me_meth, ls_meth):
if meth == 'reconstruct_instance':
def go(ls_meth):
def reconstruct(instance, ctx):
ls_meth(self, instance)
return reconstruct
event.listen(self.class_manager, 'load',
go(ls_meth), raw=False, propagate=True)
elif meth == 'init_instance':
def go(ls_meth):
def init_instance(instance, args, kwargs):
ls_meth(self, self.class_,
self.class_manager.original_init,
instance, args, kwargs)
return init_instance
event.listen(self.class_manager, 'init',
go(ls_meth), raw=False, propagate=True)
elif meth == 'init_failed':
def go(ls_meth):
def init_failed(instance, args, kwargs):
util.warn_exception(ls_meth, self, self.class_,
self.class_manager.original_init,
instance, args, kwargs)
return init_failed
event.listen(self.class_manager, 'init_failure',
go(ls_meth), raw=False, propagate=True)
else:
event.listen(self, "%s" % meth, ls_meth,
raw=False, retval=True, propagate=True)
def instrument_class(self, mapper, class_):
"""Receive a class when the mapper is first constructed, and has
applied instrumentation to the mapped class.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def init_instance(self, mapper, class_, oldinit, instance, args, kwargs):
"""Receive an instance when it's constructor is called.
This method is only called during a userland construction of
an object. It is not called when an object is loaded from the
database.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def init_failed(self, mapper, class_, oldinit, instance, args, kwargs):
"""Receive an instance when it's constructor has been called,
and raised an exception.
This method is only called during a userland construction of
an object. It is not called when an object is loaded from the
database.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def translate_row(self, mapper, context, row):
"""Perform pre-processing on the given result row and return a
new row instance.
This is called when the mapper first receives a row, before
the object identity or the instance itself has been derived
from that row. The given row may or may not be a
``RowProxy`` object - it will always be a dictionary-like
object which contains mapped columns as keys. The
returned object should also be a dictionary-like object
which recognizes mapped columns as keys.
If the ultimate return value is EXT_CONTINUE, the row
is not translated.
"""
return EXT_CONTINUE
def create_instance(self, mapper, selectcontext, row, class_):
"""Receive a row when a new object instance is about to be
created from that row.
The method can choose to create the instance itself, or it can return
EXT_CONTINUE to indicate normal object creation should take place.
mapper
The mapper doing the operation
selectcontext
The QueryContext generated from the Query.
row
The result row from the database
class\_
The class we are mapping.
return value
A new object instance, or EXT_CONTINUE
"""
return EXT_CONTINUE
def append_result(self, mapper, selectcontext, row, instance,
result, **flags):
"""Receive an object instance before that instance is appended
to a result list.
If this method returns EXT_CONTINUE, result appending will proceed
normally. if this method returns any other value or None,
result appending will not proceed for this instance, giving
this extension an opportunity to do the appending itself, if
desired.
mapper
The mapper doing the operation.
selectcontext
The QueryContext generated from the Query.
row
The result row from the database.
instance
The object instance to be appended to the result.
result
List to which results are being appended.
\**flags
extra information about the row, same as criterion in
``create_row_processor()`` method of
:class:`~sqlalchemy.orm.interfaces.MapperProperty`
"""
return EXT_CONTINUE
def populate_instance(self, mapper, selectcontext, row,
instance, **flags):
"""Receive an instance before that instance has
its attributes populated.
This usually corresponds to a newly loaded instance but may
also correspond to an already-loaded instance which has
unloaded attributes to be populated. The method may be called
many times for a single instance, as multiple result rows are
used to populate eagerly loaded collections.
If this method returns EXT_CONTINUE, instance population will
proceed normally. If any other value or None is returned,
instance population will not proceed, giving this extension an
opportunity to populate the instance itself, if desired.
.. deprecated:: 0.5
Most usages of this hook are obsolete. For a
generic "object has been newly created from a row" hook, use
``reconstruct_instance()``, or the ``@orm.reconstructor``
decorator.
"""
return EXT_CONTINUE
def reconstruct_instance(self, mapper, instance):
"""Receive an object instance after it has been created via
``__new__``, and after initial attribute population has
occurred.
This typically occurs when the instance is created based on
incoming result rows, and is only called once for that
instance's lifetime.
Note that during a result-row load, this method is called upon
the first row received for this instance. Note that some
attributes and collections may or may not be loaded or even
initialized, depending on what's present in the result rows.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def before_insert(self, mapper, connection, instance):
"""Receive an object instance before that instance is inserted
into its table.
This is a good place to set up primary key values and such
that aren't handled otherwise.
Column-based attributes can be modified within this method
which will result in the new value being inserted. However
*no* changes to the overall flush plan can be made, and
manipulation of the ``Session`` will not have the desired effect.
To manipulate the ``Session`` within an extension, use
``SessionExtension``.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def after_insert(self, mapper, connection, instance):
"""Receive an object instance after that instance is inserted.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def before_update(self, mapper, connection, instance):
"""Receive an object instance before that instance is updated.
Note that this method is called for all instances that are marked as
"dirty", even those which have no net changes to their column-based
attributes. An object is marked as dirty when any of its column-based
attributes have a "set attribute" operation called or when any of its
collections are modified. If, at update time, no column-based
attributes have any net changes, no UPDATE statement will be issued.
This means that an instance being sent to before_update is *not* a
guarantee that an UPDATE statement will be issued (although you can
affect the outcome here).
To detect if the column-based attributes on the object have net
changes, and will therefore generate an UPDATE statement, use
``object_session(instance).is_modified(instance,
include_collections=False)``.
Column-based attributes can be modified within this method
which will result in the new value being updated. However
*no* changes to the overall flush plan can be made, and
manipulation of the ``Session`` will not have the desired effect.
To manipulate the ``Session`` within an extension, use
``SessionExtension``.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def after_update(self, mapper, connection, instance):
"""Receive an object instance after that instance is updated.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def before_delete(self, mapper, connection, instance):
"""Receive an object instance before that instance is deleted.
Note that *no* changes to the overall flush plan can be made
here; and manipulation of the ``Session`` will not have the
desired effect. To manipulate the ``Session`` within an
extension, use ``SessionExtension``.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def after_delete(self, mapper, connection, instance):
"""Receive an object instance after that instance is deleted.
The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
class SessionExtension(object):
"""Base implementation for :class:`.Session` event hooks.
.. note::
:class:`.SessionExtension` is deprecated. Please
refer to :func:`.event.listen` as well as
:class:`.SessionEvents`.
Subclasses may be installed into a :class:`.Session` (or
:func:`.sessionmaker`) using the ``extension`` keyword
argument::
from sqlalchemy.orm.interfaces import SessionExtension
class MySessionExtension(SessionExtension):
def before_commit(self, session):
print "before commit!"
Session = sessionmaker(extension=MySessionExtension())
The same :class:`.SessionExtension` instance can be used
with any number of sessions.
"""
@classmethod
def _adapt_listener(cls, self, listener):
for meth in [
'before_commit',
'after_commit',
'after_rollback',
'before_flush',
'after_flush',
'after_flush_postexec',
'after_begin',
'after_attach',
'after_bulk_update',
'after_bulk_delete',
]:
me_meth = getattr(SessionExtension, meth)
ls_meth = getattr(listener, meth)
if not util.methods_equivalent(me_meth, ls_meth):
event.listen(self, meth, getattr(listener, meth))
def before_commit(self, session):
"""Execute right before commit is called.
Note that this may not be per-flush if a longer running
transaction is ongoing."""
def after_commit(self, session):
"""Execute after a commit has occurred.
Note that this may not be per-flush if a longer running
transaction is ongoing."""
def after_rollback(self, session):
"""Execute after a rollback has occurred.
Note that this may not be per-flush if a longer running
transaction is ongoing."""
def before_flush( self, session, flush_context, instances):
"""Execute before flush process has started.
`instances` is an optional list of objects which were passed to
the ``flush()`` method. """
def after_flush(self, session, flush_context):
"""Execute after flush has completed, but before commit has been
called.
Note that the session's state is still in pre-flush, i.e. 'new',
'dirty', and 'deleted' lists still show pre-flush state as well
as the history settings on instance attributes."""
def after_flush_postexec(self, session, flush_context):
"""Execute after flush has completed, and after the post-exec
state occurs.
This will be when the 'new', 'dirty', and 'deleted' lists are in
their final state. An actual commit() may or may not have
occurred, depending on whether or not the flush started its own
transaction or participated in a larger transaction. """
def after_begin( self, session, transaction, connection):
"""Execute after a transaction is begun on a connection
`transaction` is the SessionTransaction. This method is called
after an engine level transaction is begun on a connection. """
def after_attach(self, session, instance):
"""Execute after an instance is attached to a session.
This is called after an add, delete or merge. """
def after_bulk_update( self, session, query, query_context, result):
"""Execute after a bulk update operation to the session.
This is called after a session.query(...).update()
`query` is the query object that this update operation was
called on. `query_context` was the query context object.
`result` is the result object returned from the bulk operation.
"""
def after_bulk_delete( self, session, query, query_context, result):
"""Execute after a bulk delete operation to the session.
This is called after a session.query(...).delete()
`query` is the query object that this delete operation was
called on. `query_context` was the query context object.
`result` is the result object returned from the bulk operation.
"""
class AttributeExtension(object):
"""Base implementation for :class:`.AttributeImpl` event hooks, events
that fire upon attribute mutations in user code.
.. note::
:class:`.AttributeExtension` is deprecated. Please
refer to :func:`.event.listen` as well as
:class:`.AttributeEvents`.
:class:`.AttributeExtension` is used to listen for set,
remove, and append events on individual mapped attributes.
It is established on an individual mapped attribute using
the `extension` argument, available on
:func:`.column_property`, :func:`.relationship`, and
others::
from sqlalchemy.orm.interfaces import AttributeExtension
from sqlalchemy.orm import mapper, relationship, column_property
class MyAttrExt(AttributeExtension):
def append(self, state, value, initiator):
print "append event !"
return value
def set(self, state, value, oldvalue, initiator):
print "set event !"
return value
mapper(SomeClass, sometable, properties={
'foo':column_property(sometable.c.foo, extension=MyAttrExt()),
'bar':relationship(Bar, extension=MyAttrExt())
})
Note that the :class:`.AttributeExtension` methods
:meth:`~.AttributeExtension.append` and
:meth:`~.AttributeExtension.set` need to return the
``value`` parameter. The returned value is used as the
effective value, and allows the extension to change what is
ultimately persisted.
AttributeExtension is assembled within the descriptors associated
with a mapped class.
"""
active_history = True
"""indicates that the set() method would like to receive the 'old' value,
even if it means firing lazy callables.
Note that ``active_history`` can also be set directly via
:func:`.column_property` and :func:`.relationship`.
"""
@classmethod
def _adapt_listener(cls, self, listener):
event.listen(self, 'append', listener.append,
active_history=listener.active_history,
raw=True, retval=True)
event.listen(self, 'remove', listener.remove,
active_history=listener.active_history,
raw=True, retval=True)
event.listen(self, 'set', listener.set,
active_history=listener.active_history,
raw=True, retval=True)
def append(self, state, value, initiator):
"""Receive a collection append event.
The returned value will be used as the actual value to be
appended.
"""
return value
def remove(self, state, value, initiator):
"""Receive a remove event.
No return value is defined.
"""
pass
def set(self, state, value, oldvalue, initiator):
"""Receive a set event.
The returned value will be used as the actual value to be
set.
"""
return value
| gpl-2.0 |
fhaoquan/kbengine | kbe/res/scripts/common/Lib/ctypes/test/test_loading.py | 71 | 4396 | from ctypes import *
import os
import sys
import unittest
import test.support
from ctypes.util import find_library
libc_name = None
def setUpModule():
global libc_name
if os.name == "nt":
libc_name = find_library("c")
elif os.name == "ce":
libc_name = "coredll"
elif sys.platform == "cygwin":
libc_name = "cygwin1.dll"
else:
libc_name = find_library("c")
if test.support.verbose:
print("libc_name is", libc_name)
class LoaderTest(unittest.TestCase):
unknowndll = "xxrandomnamexx"
def test_load(self):
if libc_name is None:
self.skipTest('could not find libc')
CDLL(libc_name)
CDLL(os.path.basename(libc_name))
self.assertRaises(OSError, CDLL, self.unknowndll)
def test_load_version(self):
if libc_name is None:
self.skipTest('could not find libc')
if os.path.basename(libc_name) != 'libc.so.6':
self.skipTest('wrong libc path for test')
cdll.LoadLibrary("libc.so.6")
# linux uses version, libc 9 should not exist
self.assertRaises(OSError, cdll.LoadLibrary, "libc.so.9")
self.assertRaises(OSError, cdll.LoadLibrary, self.unknowndll)
def test_find(self):
for name in ("c", "m"):
lib = find_library(name)
if lib:
cdll.LoadLibrary(lib)
CDLL(lib)
@unittest.skipUnless(os.name in ("nt", "ce"),
'test specific to Windows (NT/CE)')
def test_load_library(self):
self.assertIsNotNone(libc_name)
if test.support.verbose:
print(find_library("kernel32"))
print(find_library("user32"))
if os.name == "nt":
windll.kernel32.GetModuleHandleW
windll["kernel32"].GetModuleHandleW
windll.LoadLibrary("kernel32").GetModuleHandleW
WinDLL("kernel32").GetModuleHandleW
elif os.name == "ce":
windll.coredll.GetModuleHandleW
windll["coredll"].GetModuleHandleW
windll.LoadLibrary("coredll").GetModuleHandleW
WinDLL("coredll").GetModuleHandleW
@unittest.skipUnless(os.name in ("nt", "ce"),
'test specific to Windows (NT/CE)')
def test_load_ordinal_functions(self):
import _ctypes_test
dll = WinDLL(_ctypes_test.__file__)
# We load the same function both via ordinal and name
func_ord = dll[2]
func_name = dll.GetString
# addressof gets the address where the function pointer is stored
a_ord = addressof(func_ord)
a_name = addressof(func_name)
f_ord_addr = c_void_p.from_address(a_ord).value
f_name_addr = c_void_p.from_address(a_name).value
self.assertEqual(hex(f_ord_addr), hex(f_name_addr))
self.assertRaises(AttributeError, dll.__getitem__, 1234)
@unittest.skipUnless(os.name == "nt", 'Windows-specific test')
def test_1703286_A(self):
from _ctypes import LoadLibrary, FreeLibrary
# On winXP 64-bit, advapi32 loads at an address that does
# NOT fit into a 32-bit integer. FreeLibrary must be able
# to accept this address.
# These are tests for http://www.python.org/sf/1703286
handle = LoadLibrary("advapi32")
FreeLibrary(handle)
@unittest.skipUnless(os.name == "nt", 'Windows-specific test')
def test_1703286_B(self):
# Since on winXP 64-bit advapi32 loads like described
# above, the (arbitrarily selected) CloseEventLog function
# also has a high address. 'call_function' should accept
# addresses so large.
from _ctypes import call_function
advapi32 = windll.advapi32
# Calling CloseEventLog with a NULL argument should fail,
# but the call should not segfault or so.
self.assertEqual(0, advapi32.CloseEventLog(None))
windll.kernel32.GetProcAddress.argtypes = c_void_p, c_char_p
windll.kernel32.GetProcAddress.restype = c_void_p
proc = windll.kernel32.GetProcAddress(advapi32._handle,
b"CloseEventLog")
self.assertTrue(proc)
# This is the real test: call the function via 'call_function'
self.assertEqual(0, call_function(proc, (None,)))
if __name__ == "__main__":
unittest.main()
| lgpl-3.0 |
CDSherrill/psi4 | psi4/driver/qcdb/options.py | 3 | 11046 | #
# @BEGIN LICENSE
#
# Psi4: an open-source quantum chemistry software package
#
# Copyright (c) 2007-2019 The Psi4 Developers.
#
# The copyrights for code used from other parties are included in
# the corresponding files.
#
# This file is part of Psi4.
#
# Psi4 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, version 3.
#
# Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# @END LICENSE
#
import math
from .exceptions import *
def format_option_for_cfour(opt, val):
"""Function to reformat value *val* for option *opt* from python
into cfour-speak. Arrays are the primary target.
"""
text = ''
# Transform list from [[3, 0, 1, 1], [2, 0, 1, 0]] --> 3-0-1-1/2-0-1-0
if isinstance(val, list):
if type(val[0]).__name__ == 'list':
if type(val[0][0]).__name__ == 'list':
raise ValidationError('Option has level of array nesting inconsistent with CFOUR.')
else:
# option is 2D array
for no in range(len(val)):
for ni in range(len(val[no])):
text += str(val[no][ni])
if ni < (len(val[no]) - 1):
text += '-'
if no < (len(val) - 1):
text += '/'
else:
# option is plain 1D array
if opt == 'CFOUR_ESTATE_SYM':
# [3, 1, 0, 2] --> 3/1/0/2
text += '/'.join(map(str, val))
elif opt == 'CFOUR_DROPMO':
text += '-'.join(map(str, val))
# NOTE: some versions of cfour (or maybe it's psi) need comma, not dash
#text += ','.join(map(str, val))
else:
# [3, 1, 0, 2] --> 3-1-0-2
text += '-'.join(map(str, val))
# Transform booleans into integers
elif str(val) == 'True':
text += '1'
elif str(val) == 'False':
text += '0'
# Transform the basis sets that *must* be lowercase (dratted c4 input)
elif (opt == 'CFOUR_BASIS') and (val.upper() in ['SVP', 'DZP', 'TZP', 'TZP2P', 'QZ2P', 'PZ3D2F', '13S9P4D3F']):
text += str(val.lower())
# No Transform
else:
text += str(val)
return opt[6:], text
def prepare_options_for_cfour(options):
"""Function to take the full snapshot of the liboptions object
encoded in dictionary *options*, find the options directable toward
Cfour (options['CFOUR']['CFOUR_**']) that aren't default, then write
a CFOUR deck with those options.
"""
text = ''
for opt, val in options['CFOUR'].items():
if opt.startswith('CFOUR_'):
if val['has_changed']:
if not text:
text += """*CFOUR("""
text += """%s=%s\n""" % (format_option_for_cfour(opt, val['value']))
if text:
text = text[:-1] + ')\n\n'
return text
def prepare_options_for_orca(options):
"""Function to take the full snapshot of the liboptions object
encoded in dictionary *options*, find the options directable toward
Orca (options['ORCA']['ORCA_**']) that aren't default, then write
an ORCA deck with those options.
"""
text = ''
for opt, val in options['ORCA'].items():
if opt.startswith('ORCA_'):
if val['has_changed']:
if not text:
text += """! """
text +="""%s """ % (val['value'])
#text += """%s=%s\n""" % (format_option_for_cfour(opt, val['value']))
if text:
#text = text[:-1] + ')\n\n'
text += '\n'
return text
def prepare_options_for_psi4(options):
"""Function to take the full snapshot of the liboptions object
encoded in dictionary *options*, find the options directable toward
Cfour (options['CFOUR']['CFOUR_**']) that aren't default, then write
a CFOUR deck with those options.
Note that unlike the cfour version, this uses complete options deck.
"""
text = ''
for mod, moddict in options.items():
for opt, val in moddict.items():
#print mod, opt, val['value']
if not text:
text += """\n"""
if mod == 'GLOBALS':
text += """set %s %s\n""" % (opt.lower(), val['value'])
else:
text += """set %s %s %s\n""" % (mod.lower(), opt.lower(), val['value'])
if text:
text += '\n'
return text
def prepare_options_for_qchem(options):
"""Function to take the full snapshot of the liboptions object
encoded in dictionary *options*, find the options directable toward
Q-Chem (options['QCHEM']['QCHEM_**']) that aren't default, then write
a Q-Chem deck with those options.
"""
text = ''
for opt, val in options['QCHEM'].items():
if opt.startswith('QCHEM_'):
if val['has_changed']:
if not text:
text += """$rem\n"""
text += """%-20s %s\n""" % (opt[6:], val['value'])
#text += """%s=%s\n""" % (format_option_for_cfour(opt, val['value']))
if text:
text += """$end\n\n"""
return text
def reconcile_options(full, partial):
"""Function to take the full snapshot of the liboptions object
encoded in dictionary *full* and reconcile it with proposed options
value changes in *partial*. Overwrites *full* with *partial* if
option untouched, touches *full* if *full* and *partial* are in
agreement, balks if *full* and *partial* conflict. Returns *full*.
"""
try:
for module, modopts in partial.items():
for kw, kwprop in modopts.items():
if full[module][kw]['has_changed']:
if full[module][kw]['value'] != kwprop['value']:
if 'clobber' in kwprop and kwprop['clobber']:
if 'superclobber' in kwprop and kwprop['superclobber']:
# kw in full is touched, conflicts with value in partial,
# but value in partial is paramount, overwrite full with
# value in partial
full[module][kw]['value'] = kwprop['value']
full[module][kw]['has_changed'] = True
#print '@P4C4 Overwriting %s with %s' % (kw, kwprop['value'])
else:
raise ValidationError("""
Option %s value `%s` set by options block incompatible with
value `%s` in memory/molecule/command/psi4options block.""" %
(kw, full[module][kw]['value'], kwprop['value']))
else:
# kw in full is touched, conflicts with value in partial,
# but value in partial is recommended, not required, no change
pass
else:
# kw in full is touched, but in agreement with value in partial, no change
pass
else:
# If kw in full is untouched, overwrite it with value in partial
full[module][kw]['value'] = kwprop['value']
full[module][kw]['has_changed'] = True
#print '@P4C4 Overwriting %s with %s' % (kw, kwprop['value'])
except KeyError as e: # not expected but want to trap
raise ValidationError("""Unexpected KeyError reconciling keywords: %s.""" % (repr(e)))
return full
def reconcile_options2(full, partial):
"""Function to take the full snapshot of the liboptions object
encoded in dictionary *full* and reconcile it with proposed options
value changes in *partial*. Overwrites *full* with *partial* if
option untouched, touches *full* if *full* and *partial* are in
agreement, balks if *full* and *partial* conflict. Returns *full*.
Note: this is surprisingly similar to reconcile_options except
that full is essentially empty and lacking in has_changed keys
so presence is enough to satisfy has_changed. consider merging
once mature.
"""
try:
for module, modopts in partial.items():
for kw, kwprop in modopts.items():
#if full[module][kw]['has_changed']:
if full[module][kw]:
if full[module][kw]['value'] != kwprop['value']:
if 'clobber' in kwprop and kwprop['clobber']:
if 'superclobber' in kwprop and kwprop['superclobber']:
# kw in full is touched, conflicts with value in partial,
# but value in partial is paramount, overwrite full with
# value in partial
full[module][kw]['value'] = kwprop['value']
full[module][kw]['has_changed'] = True
#print '@P4C4 Overwriting %s with %s' % (kw, kwprop['value'])
else:
raise ValidationError("""
Option %s value `%s` set by options block incompatible with
value `%s` in memory/molecule/command/psi4options block.""" %
(kw, full[module][kw]['value'], kwprop['value']))
else:
# kw in full is touched, conflicts with value in partial,
# but value in partial is recommended, not required, no change
pass
else:
# kw in full is touched, but in agreement with value in partial, no change
pass
else:
# If kw in full is absent, overwrite it with value in partial
full[module][kw]['value'] = kwprop['value']
full[module][kw]['has_changed'] = True
#print '@P4C4 Overwriting %s with %s' % (kw, kwprop['value'])
except KeyError as e: # not expected but want to trap
raise ValidationError("""Unexpected KeyError reconciling keywords: %s.""" % (repr(e)))
return full
def conv_float2negexp(val):
"""Returns the least restrictive negative exponent of the power 10
that would achieve the floating point convergence criterium *val*.
"""
return -1 * int(math.floor(math.log(val, 10)))
| lgpl-3.0 |
aequitas/home-assistant | homeassistant/components/heatmiser/climate.py | 6 | 3343 | """Support for the PRT Heatmiser themostats using the V3 protocol."""
import logging
import voluptuous as vol
from homeassistant.components.climate import ClimateDevice, PLATFORM_SCHEMA
from homeassistant.components.climate.const import (
SUPPORT_TARGET_TEMPERATURE)
from homeassistant.const import (
TEMP_CELSIUS, ATTR_TEMPERATURE, CONF_PORT, CONF_NAME, CONF_ID)
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_IPADDRESS = 'ipaddress'
CONF_TSTATS = 'tstats'
TSTATS_SCHEMA = vol.Schema({
vol.Required(CONF_ID): cv.string,
vol.Required(CONF_NAME): cv.string,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_IPADDRESS): cv.string,
vol.Required(CONF_PORT): cv.port,
vol.Required(CONF_TSTATS, default={}):
vol.Schema({cv.string: TSTATS_SCHEMA}),
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the heatmiser thermostat."""
from heatmiserV3 import heatmiser, connection
ipaddress = config.get(CONF_IPADDRESS)
port = str(config.get(CONF_PORT))
tstats = config.get(CONF_TSTATS)
serport = connection.connection(ipaddress, port)
serport.open()
for tstat in tstats.values():
add_entities([
HeatmiserV3Thermostat(
heatmiser, tstat.get(CONF_ID), tstat.get(CONF_NAME), serport)
])
class HeatmiserV3Thermostat(ClimateDevice):
"""Representation of a HeatmiserV3 thermostat."""
def __init__(self, heatmiser, device, name, serport):
"""Initialize the thermostat."""
self.heatmiser = heatmiser
self.serport = serport
self._current_temperature = None
self._name = name
self._id = device
self.dcb = None
self.update()
self._target_temperature = int(self.dcb.get('roomset'))
@property
def supported_features(self):
"""Return the list of supported features."""
return SUPPORT_TARGET_TEMPERATURE
@property
def name(self):
"""Return the name of the thermostat, if any."""
return self._name
@property
def temperature_unit(self):
"""Return the unit of measurement which this thermostat uses."""
return TEMP_CELSIUS
@property
def current_temperature(self):
"""Return the current temperature."""
if self.dcb is not None:
low = self.dcb.get('floortemplow ')
high = self.dcb.get('floortemphigh')
temp = (high * 256 + low) / 10.0
self._current_temperature = temp
else:
self._current_temperature = None
return self._current_temperature
@property
def target_temperature(self):
"""Return the temperature we try to reach."""
return self._target_temperature
def set_temperature(self, **kwargs):
"""Set new target temperature."""
temperature = kwargs.get(ATTR_TEMPERATURE)
if temperature is None:
return
self.heatmiser.hmSendAddress(
self._id,
18,
temperature,
1,
self.serport)
self._target_temperature = temperature
def update(self):
"""Get the latest data."""
self.dcb = self.heatmiser.hmReadAddress(self._id, 'prt', self.serport)
| apache-2.0 |
aaron-fz/neutron_full_sync | neutron/db/quota_db.py | 28 | 6934 | # Copyright 2011 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 sqlalchemy as sa
from neutron.common import exceptions
from neutron.db import model_base
from neutron.db import models_v2
class Quota(model_base.BASEV2, models_v2.HasId):
"""Represent a single quota override for a tenant.
If there is no row for a given tenant id and resource, then the
default for the quota class is used.
"""
tenant_id = sa.Column(sa.String(255), index=True)
resource = sa.Column(sa.String(255))
limit = sa.Column(sa.Integer)
class DbQuotaDriver(object):
"""Driver to perform necessary checks to enforce quotas and obtain quota
information.
The default driver utilizes the local database.
"""
@staticmethod
def get_tenant_quotas(context, resources, tenant_id):
"""Given a list of resources, retrieve the quotas for the given
tenant.
:param context: The request context, for access checks.
:param resources: A dictionary of the registered resource keys.
:param tenant_id: The ID of the tenant to return quotas for.
:return dict: from resource name to dict of name and limit
"""
# init with defaults
tenant_quota = dict((key, resource.default)
for key, resource in resources.items())
# update with tenant specific limits
q_qry = context.session.query(Quota).filter_by(tenant_id=tenant_id)
tenant_quota.update((q['resource'], q['limit']) for q in q_qry)
return tenant_quota
@staticmethod
def delete_tenant_quota(context, tenant_id):
"""Delete the quota entries for a given tenant_id.
Atfer deletion, this tenant will use default quota values in conf.
"""
with context.session.begin():
tenant_quotas = context.session.query(Quota)
tenant_quotas = tenant_quotas.filter_by(tenant_id=tenant_id)
tenant_quotas.delete()
@staticmethod
def get_all_quotas(context, resources):
"""Given a list of resources, retrieve the quotas for the all tenants.
:param context: The request context, for access checks.
:param resources: A dictionary of the registered resource keys.
:return quotas: list of dict of tenant_id:, resourcekey1:
resourcekey2: ...
"""
tenant_default = dict((key, resource.default)
for key, resource in resources.items())
all_tenant_quotas = {}
for quota in context.session.query(Quota):
tenant_id = quota['tenant_id']
# avoid setdefault() because only want to copy when actually req'd
tenant_quota = all_tenant_quotas.get(tenant_id)
if tenant_quota is None:
tenant_quota = tenant_default.copy()
tenant_quota['tenant_id'] = tenant_id
all_tenant_quotas[tenant_id] = tenant_quota
tenant_quota[quota['resource']] = quota['limit']
return all_tenant_quotas.values()
@staticmethod
def update_quota_limit(context, tenant_id, resource, limit):
with context.session.begin():
tenant_quota = context.session.query(Quota).filter_by(
tenant_id=tenant_id, resource=resource).first()
if tenant_quota:
tenant_quota.update({'limit': limit})
else:
tenant_quota = Quota(tenant_id=tenant_id,
resource=resource,
limit=limit)
context.session.add(tenant_quota)
def _get_quotas(self, context, tenant_id, resources, keys):
"""Retrieves the quotas for specific resources.
A helper method which retrieves the quotas for the specific
resources identified by keys, and which apply to the current
context.
:param context: The request context, for access checks.
:param tenant_id: the tenant_id to check quota.
:param resources: A dictionary of the registered resources.
:param keys: A list of the desired quotas to retrieve.
"""
desired = set(keys)
sub_resources = dict((k, v) for k, v in resources.items()
if k in desired)
# Make sure we accounted for all of them...
if len(keys) != len(sub_resources):
unknown = desired - set(sub_resources.keys())
raise exceptions.QuotaResourceUnknown(unknown=sorted(unknown))
# Grab and return the quotas (without usages)
quotas = DbQuotaDriver.get_tenant_quotas(
context, sub_resources, tenant_id)
return dict((k, v) for k, v in quotas.items())
def limit_check(self, context, tenant_id, resources, values):
"""Check simple quota limits.
For limits--those quotas for which there is no usage
synchronization function--this method checks that a set of
proposed values are permitted by the limit restriction.
This method will raise a QuotaResourceUnknown exception if a
given resource is unknown or if it is not a simple limit
resource.
If any of the proposed values is over the defined quota, an
OverQuota exception will be raised with the sorted list of the
resources which are too high. Otherwise, the method returns
nothing.
:param context: The request context, for access checks.
:param tenant_id: The tenant_id to check the quota.
:param resources: A dictionary of the registered resources.
:param values: A dictionary of the values to check against the
quota.
"""
# Ensure no value is less than zero
unders = [key for key, val in values.items() if val < 0]
if unders:
raise exceptions.InvalidQuotaValue(unders=sorted(unders))
# Get the applicable quotas
quotas = self._get_quotas(context, tenant_id, resources, values.keys())
# Check the quotas and construct a list of the resources that
# would be put over limit by the desired values
overs = [key for key, val in values.items()
if quotas[key] >= 0 and quotas[key] < val]
if overs:
raise exceptions.OverQuota(overs=sorted(overs))
| apache-2.0 |
rkmaddox/mne-python | mne/defaults.py | 6 | 5760 | # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Denis A. Engemann <denis.engemann@gmail.com>
# Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD (3-clause)
from copy import deepcopy
DEFAULTS = dict(
color=dict(mag='darkblue', grad='b', eeg='k', eog='k', ecg='m', emg='k',
ref_meg='steelblue', misc='k', stim='k', resp='k', chpi='k',
exci='k', ias='k', syst='k', seeg='saddlebrown', dbs='seagreen',
dipole='k', gof='k', bio='k', ecog='k', hbo='#AA3377', hbr='b',
fnirs_cw_amplitude='k', fnirs_fd_ac_amplitude='k',
fnirs_fd_phase='k', fnirs_od='k', csd='k'),
si_units=dict(mag='T', grad='T/m', eeg='V', eog='V', ecg='V', emg='V',
misc='AU', seeg='V', dbs='V', dipole='Am', gof='GOF',
bio='V', ecog='V', hbo='M', hbr='M', ref_meg='T',
fnirs_cw_amplitude='V', fnirs_fd_ac_amplitude='V',
fnirs_fd_phase='rad', fnirs_od='V', csd='V/m²'),
units=dict(mag='fT', grad='fT/cm', eeg='µV', eog='µV', ecg='µV', emg='µV',
misc='AU', seeg='mV', dbs='µV', dipole='nAm', gof='GOF',
bio='µV', ecog='µV', hbo='µM', hbr='µM', ref_meg='fT',
fnirs_cw_amplitude='V', fnirs_fd_ac_amplitude='V',
fnirs_fd_phase='rad', fnirs_od='V', csd='mV/m²'),
# scalings for the units
scalings=dict(mag=1e15, grad=1e13, eeg=1e6, eog=1e6, emg=1e6, ecg=1e6,
misc=1.0, seeg=1e3, dbs=1e6, ecog=1e6, dipole=1e9, gof=1.0,
bio=1e6, hbo=1e6, hbr=1e6, ref_meg=1e15,
fnirs_cw_amplitude=1.0, fnirs_fd_ac_amplitude=1.0,
fnirs_fd_phase=1., fnirs_od=1.0, csd=1e3),
# rough guess for a good plot
scalings_plot_raw=dict(mag=1e-12, grad=4e-11, eeg=20e-6, eog=150e-6,
ecg=5e-4, emg=1e-3, ref_meg=1e-12, misc='auto',
stim=1, resp=1, chpi=1e-4, exci=1, ias=1, syst=1,
seeg=1e-4, dbs=1e-4, bio=1e-6, ecog=1e-4, hbo=10e-6,
hbr=10e-6, whitened=10., fnirs_cw_amplitude=2e-2,
fnirs_fd_ac_amplitude=2e-2, fnirs_fd_phase=2e-1,
fnirs_od=2e-2, csd=200e-4),
scalings_cov_rank=dict(mag=1e12, grad=1e11, eeg=1e5, # ~100x scalings
seeg=1e1, dbs=1e4, ecog=1e4, hbo=1e4, hbr=1e4),
ylim=dict(mag=(-600., 600.), grad=(-200., 200.), eeg=(-200., 200.),
misc=(-5., 5.), seeg=(-20., 20.), dbs=(-200., 200.),
dipole=(-100., 100.), gof=(0., 1.), bio=(-500., 500.),
ecog=(-200., 200.), hbo=(0, 20), hbr=(0, 20), csd=(-50., 50.)),
titles=dict(mag='Magnetometers', grad='Gradiometers', eeg='EEG', eog='EOG',
ecg='ECG', emg='EMG', misc='misc', seeg='sEEG', dbs='DBS',
bio='BIO', dipole='Dipole', ecog='ECoG', hbo='Oxyhemoglobin',
ref_meg='Reference Magnetometers',
fnirs_cw_amplitude='fNIRS (CW amplitude)',
fnirs_fd_ac_amplitude='fNIRS (FD AC amplitude)',
fnirs_fd_phase='fNIRS (FD phase)',
fnirs_od='fNIRS (OD)', hbr='Deoxyhemoglobin',
gof='Goodness of fit', csd='Current source density'),
mask_params=dict(marker='o',
markerfacecolor='w',
markeredgecolor='k',
linewidth=0,
markeredgewidth=1,
markersize=4),
coreg=dict(
mri_fid_opacity=1.0,
dig_fid_opacity=1.0,
mri_fid_scale=5e-3,
dig_fid_scale=8e-3,
extra_scale=4e-3,
eeg_scale=4e-3, eegp_scale=20e-3, eegp_height=0.1,
ecog_scale=5e-3,
seeg_scale=5e-3,
dbs_scale=5e-3,
fnirs_scale=5e-3,
source_scale=5e-3,
detector_scale=5e-3,
hpi_scale=15e-3,
head_color=(0.988, 0.89, 0.74),
hpi_color=(1., 0., 1.),
extra_color=(1., 1., 1.),
eeg_color=(1., 0.596, 0.588), eegp_color=(0.839, 0.15, 0.16),
ecog_color=(1., 1., 1.),
dbs_color=(0.82, 0.455, 0.659),
seeg_color=(1., 1., .3),
fnirs_color=(1., .647, 0.),
source_color=(1., .05, 0.),
detector_color=(.3, .15, .15),
lpa_color=(1., 0., 0.),
nasion_color=(0., 1., 0.),
rpa_color=(0., 0., 1.),
),
noise_std=dict(grad=5e-13, mag=20e-15, eeg=0.2e-6),
eloreta_options=dict(eps=1e-6, max_iter=20, force_equal=False),
depth_mne=dict(exp=0.8, limit=10., limit_depth_chs=True,
combine_xyz='spectral', allow_fixed_depth=False),
depth_sparse=dict(exp=0.8, limit=None, limit_depth_chs='whiten',
combine_xyz='fro', allow_fixed_depth=True),
interpolation_method=dict(eeg='spline', meg='MNE', fnirs='nearest'),
volume_options=dict(
alpha=None, resolution=1., surface_alpha=None, blending='mip',
silhouette_alpha=None, silhouette_linewidth=2.),
prefixes={'': 1e0, 'd': 1e1, 'c': 1e2, 'm': 1e3, 'µ': 1e6, 'u': 1e6,
'n': 1e9, 'p': 1e12, 'f': 1e15}
)
def _handle_default(k, v=None):
"""Avoid dicts as default keyword arguments.
Use this function instead to resolve default dict values. Example usage::
scalings = _handle_default('scalings', scalings)
"""
this_mapping = deepcopy(DEFAULTS[k])
if v is not None:
if isinstance(v, dict):
this_mapping.update(v)
else:
for key in this_mapping:
this_mapping[key] = v
return this_mapping
HEAD_SIZE_DEFAULT = 0.095 # in [m]
_BORDER_DEFAULT = 'mean'
_EXTRAPOLATE_DEFAULT = 'auto'
| bsd-3-clause |
edvakf/thrift | lib/py/src/transport/TSocket.py | 51 | 5734 | #
# 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.
#
import errno
import os
import socket
import sys
from TTransport import *
class TSocketBase(TTransportBase):
def _resolveAddr(self):
if self._unix_socket is not None:
return [(socket.AF_UNIX, socket.SOCK_STREAM, None, None,
self._unix_socket)]
else:
return socket.getaddrinfo(self.host,
self.port,
self._socket_family,
socket.SOCK_STREAM,
0,
socket.AI_PASSIVE | socket.AI_ADDRCONFIG)
def close(self):
if self.handle:
self.handle.close()
self.handle = None
class TSocket(TSocketBase):
"""Socket implementation of TTransport base."""
def __init__(self, host='localhost', port=9090, unix_socket=None, socket_family=socket.AF_UNSPEC):
"""Initialize a TSocket
@param host(str) The host to connect to.
@param port(int) The (TCP) port to connect to.
@param unix_socket(str) The filename of a unix socket to connect to.
(host and port will be ignored.)
@param socket_family(int) The socket family to use with this socket.
"""
self.host = host
self.port = port
self.handle = None
self._unix_socket = unix_socket
self._timeout = None
self._socket_family = socket_family
def setHandle(self, h):
self.handle = h
def isOpen(self):
return self.handle is not None
def setTimeout(self, ms):
if ms is None:
self._timeout = None
else:
self._timeout = ms / 1000.0
if self.handle is not None:
self.handle.settimeout(self._timeout)
def open(self):
try:
res0 = self._resolveAddr()
for res in res0:
self.handle = socket.socket(res[0], res[1])
self.handle.settimeout(self._timeout)
try:
self.handle.connect(res[4])
except socket.error as e:
if res is not res0[-1]:
continue
else:
raise e
break
except socket.error as e:
if self._unix_socket:
message = 'Could not connect to socket %s' % self._unix_socket
else:
message = 'Could not connect to %s:%d' % (self.host, self.port)
raise TTransportException(type=TTransportException.NOT_OPEN,
message=message)
def read(self, sz):
try:
buff = self.handle.recv(sz)
except socket.error as e:
if (e.args[0] == errno.ECONNRESET and
(sys.platform == 'darwin' or sys.platform.startswith('freebsd'))):
# freebsd and Mach don't follow POSIX semantic of recv
# and fail with ECONNRESET if peer performed shutdown.
# See corresponding comment and code in TSocket::read()
# in lib/cpp/src/transport/TSocket.cpp.
self.close()
# Trigger the check to raise the END_OF_FILE exception below.
buff = ''
else:
raise
if len(buff) == 0:
raise TTransportException(type=TTransportException.END_OF_FILE,
message='TSocket read 0 bytes')
return buff
def write(self, buff):
if not self.handle:
raise TTransportException(type=TTransportException.NOT_OPEN,
message='Transport not open')
sent = 0
have = len(buff)
while sent < have:
plus = self.handle.send(buff)
if plus == 0:
raise TTransportException(type=TTransportException.END_OF_FILE,
message='TSocket sent 0 bytes')
sent += plus
buff = buff[plus:]
def flush(self):
pass
class TServerSocket(TSocketBase, TServerTransportBase):
"""Socket implementation of TServerTransport base."""
def __init__(self, host=None, port=9090, unix_socket=None, socket_family=socket.AF_UNSPEC):
self.host = host
self.port = port
self._unix_socket = unix_socket
self._socket_family = socket_family
self.handle = None
def listen(self):
res0 = self._resolveAddr()
socket_family = self._socket_family == socket.AF_UNSPEC and socket.AF_INET6 or self._socket_family
for res in res0:
if res[0] is socket_family or res is res0[-1]:
break
# We need remove the old unix socket if the file exists and
# nobody is listening on it.
if self._unix_socket:
tmp = socket.socket(res[0], res[1])
try:
tmp.connect(res[4])
except socket.error as err:
eno, message = err.args
if eno == errno.ECONNREFUSED:
os.unlink(res[4])
self.handle = socket.socket(res[0], res[1])
self.handle.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(self.handle, 'settimeout'):
self.handle.settimeout(None)
self.handle.bind(res[4])
self.handle.listen(128)
def accept(self):
client, addr = self.handle.accept()
result = TSocket()
result.setHandle(client)
return result
| apache-2.0 |
apache/allura | ForgeWiki/forgewiki/tests/test_wiki_roles.py | 2 | 2234 | # 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 __future__ import unicode_literals
from __future__ import absolute_import
from tg import tmpl_context as c, app_globals as g
from alluratest.tools import assert_equal
from alluratest.controller import setup_basic_test, setup_global_objects
from allura import model as M
from allura.lib import security
from allura.tests import decorators as td
def setUp():
setup_basic_test()
setup_with_tools()
@td.with_wiki
def setup_with_tools():
setup_global_objects()
g.set_app('wiki')
def test_role_assignments():
admin = M.User.by_username('test-admin')
user = M.User.by_username('test-user')
anon = M.User.anonymous()
def check_access(perm):
pred = security.has_access(c.app, perm)
return pred(user=admin), pred(user=user), pred(user=anon)
assert_equal(check_access('configure'), (True, False, False))
assert_equal(check_access('read'), (True, True, True))
assert_equal(check_access('create'), (True, False, False))
assert_equal(check_access('edit'), (True, False, False))
assert_equal(check_access('delete'), (True, False, False))
assert_equal(check_access('unmoderated_post'), (True, True, False))
assert_equal(check_access('post'), (True, True, False))
assert_equal(check_access('moderate'), (True, False, False))
assert_equal(check_access('admin'), (True, False, False))
| apache-2.0 |
savoirfairelinux/OpenUpgrade | addons/l10n_ro/__init__.py | 91 | 1079 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2012 TOTAL PC SYSTEMS (<http://www.erpsystems.ro>). All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import res_partner
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
michael-christen/repo-monitor | repo_monitor/python/tests/test_parsers.py | 1 | 6014 | import os
import unittest
from ..deserializers import CoverageDeserializer
from ..deserializers import NosetestDeserializer
from ..parsers import NosetestParser
from ..parsers import RadonParser
def _get_data_filename(filename):
return os.path.join(
os.path.dirname(os.path.realpath(__file__)),
'data/{}'.format(filename))
class TestCoverageDeserializer(unittest.TestCase):
def test_basic(self):
self.assertEqual(
0.883,
CoverageDeserializer(EXAMPLE_COVERAGE_XML).line_rate)
class TestTests(unittest.TestCase):
def compare_dicts(self, dict1, dict2):
for test_name, expected_time in dict1.viewitems():
try:
actual_time = dict2[test_name]
except KeyError:
self.fail(
"{} expected, but not found in:\n{}".format(
test_name, dict2.keys()))
self.assertAlmostEqual(expected_time, actual_time, delta=0.0001)
self.assertEqual(
set(dict2.keys()),
set(dict1.keys()))
def test_basic(self):
self.maxDiff = None
nosetest_data = NosetestDeserializer(EXAMPLE_TEST_XML)
self.assertEqual(5, nosetest_data.num_tests)
self.assertEqual(0.138, nosetest_data.time)
expected_test2time = {
'file_kvstore.tests.test_basic.TestBasic:test_add': 1.5,
'file_kvstore.tests.test_basic.TestBasic:test_format': 0.023,
'file_kvstore.tests.test_basic.TestBasic:test_order': 0.13,
'file_kvstore.tests.test_basic.TestBasic:test_start': 0.00015,
'file_kvstore.tests.test_basic.TestBasic:test_replace': 10.23,
}
self.compare_dicts(expected_test2time, nosetest_data.test2time)
def test_nosetest_parser(self):
file_arg = '--file={}'.format(_get_data_filename('test_nosetests.xml'))
self.assertEqual('0.138', NosetestParser().run(['time', file_arg]))
self.assertEqual('5', NosetestParser().run(['num_tests', file_arg]))
self.assertEqual(5,
len(NosetestParser().run(['test2time',
file_arg]).split('\n')))
class TestRadon(unittest.TestCase):
def test_radon_parser(self):
base_args = [
'--raw_json={}'.format(_get_data_filename('test_raw_radon.json')),
'--mi_json={}'.format(_get_data_filename('test_mi_radon.json')),
]
self.assertEqual('192', RadonParser().run(base_args + ['lloc']))
self.assertEqual('54.34', RadonParser().run(base_args + ['mi']))
EXAMPLE_COVERAGE_XML = '''<?xml version="1.0" ?>
<coverage branch-rate="0" line-rate="0.883" timestamp="1493359236075" version="4.0.3">
<!-- Generated by coverage.py: https://coverage.readthedocs.org -->
<!-- Based on https://raw.githubusercontent.com/cobertura/web/f0366e5e2cf18f111cbd61fc34ef720a6584ba02/htdocs/xml/coverage-03.dtd -->
<sources>
<source>/home/michael/projects/scripts/file-kvstore</source>
<source>/home/michael/projects/scripts/file-kvstore/file_kvstore</source>
</sources>
<packages>
<package branch-rate="0" complexity="0" line-rate="0.8036" name="file_kvstore">
<classes>
<class branch-rate="0" complexity="0" filename="file_kvstore/__init__.py" line-rate="1" name="__init__.py">
<methods/>
<lines/>
</class>
<class branch-rate="0" complexity="0" filename="file_kvstore/constants.py" line-rate="1" name="constants.py">
<methods/>
<lines>
<line hits="1" number="1"/>
</lines>
</class>
<class branch-rate="0" complexity="0" filename="file_kvstore/io.py" line-rate="0.7083" name="io.py">
<methods/>
<lines>
<line hits="1" number="1"/>
</lines>
</class>
<class branch-rate="0" complexity="0" filename="file_kvstore/parser.py" line-rate="0.8889" name="parser.py">
<methods/>
<lines>
<line hits="1" number="1"/>
</lines>
</class>
<class branch-rate="0" complexity="0" filename="file_kvstore/utils.py" line-rate="0.8462" name="utils.py">
<methods/>
<lines>
<line hits="0" number="19"/>
</lines>
</class>
</classes>
</package>
<package branch-rate="0" complexity="0" line-rate="1" name="file_kvstore.tests">
<classes>
<class branch-rate="0" complexity="0" filename="file_kvstore/tests/__init__.py" line-rate="1" name="__init__.py">
<methods/>
<lines/>
</class>
<class branch-rate="0" complexity="0" filename="file_kvstore/tests/test_basic.py" line-rate="1" name="test_basic.py">
<methods/>
<lines>
<line hits="1" number="1"/>
<line hits="1" number="2"/>
<line hits="1" number="4"/>
</lines>
</class>
</classes>
</package>
</packages>
</coverage>
''' # noqa
EXAMPLE_TEST_XML = '''<?xml version="1.0" encoding="utf-8"?>
<testsuite errors="0" failures="0" name="pytest" skips="0" tests="5" time="0.138">
<testcase
classname="file_kvstore.tests.test_basic.TestBasic"
file="file_kvstore/tests/test_basic.py"
line="30"
name="test_add"
time="1.5000000001"></testcase>
<testcase
classname="file_kvstore.tests.test_basic.TestBasic"
file="file_kvstore/tests/test_basic.py"
line="51"
name="test_format"
time="0.023"><system-out>a: 5.123 h: hello </system-out></testcase>
<testcase
classname="file_kvstore.tests.test_basic.TestBasic"
file="file_kvstore/tests/test_basic.py"
line="37"
name="test_order"
time="0.13"></testcase>
<testcase
classname="file_kvstore.tests.test_basic.TestBasic"
file="file_kvstore/tests/test_basic.py"
line="44"
name="test_replace"
time="10.23"></testcase>
<testcase
classname="file_kvstore.tests.test_basic.TestBasic"
file="file_kvstore/tests/test_basic.py"
line="23"
name="test_start"
time="0.00015"></testcase></testsuite>
''' # noqa
| mit |
gloutsch/sqreen-test | api2sshallowedusers/helpers.py | 1 | 2199 | #!/usr/bin/env python3
import logging
import re
import subprocess
from functools import wraps
from string import Template
from flask import abort, request
TOKENS = []
REGEX_USERNAME = re.compile('^\w{1,20}$')
logger = logging.getLogger(__name__)
def authorize_badtoken(f):
@wraps(f)
def check_token(*args, **kwargs):
magic_header = request.environ.get('HTTP_BADTOKEN')
if magic_header in TOKENS:
return f(*args, **kwargs)
else:
return abort(403)
return check_token
def sanitize_user():
def decorator(f):
@wraps(f)
def check_user(*args, **kwargs):
if REGEX_USERNAME.match(kwargs.get('user')):
return f(*args, **kwargs)
else:
return abort(400)
return check_user
return decorator
class Command(object):
def __init__(self, sysinit=None, service=None):
self.sysinit = sysinit
self.service = service
self.cli = self.format_cli()
def format_cli(self):
if 'system' in self.sysinit:
return Template('systemctl $action %s' % self.service)
if 'init' in self.sysinit:
return Template('/etc/init.d/%s $action' % self.service)
return '/bin/false'
def check(self):
cmd = self.cli.substitute(action='status')
try:
subprocess.check_call(cmd.split(),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
return True
except Exception as e:
logger.debug(e)
logger.debug('cannot interact with daemon "%s"' % cmd)
return False
def reload(self):
cmd = self.cli.substitute(action='reload')
try:
subprocess.run(cmd.split(), check=True,
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
logger.info('daemon reloaded')
return True
except subprocess.CalledProcessError:
logger.error('cannot interact with daemon "%s"' % cmd)
return False
| mit |
Vaidyanath/tempest | tools/install_venv.py | 27 | 2399 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2010 OpenStack Foundation
# Copyright 2013 IBM Corp.
#
# 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 os
import sys
import install_venv_common as install_venv # noqa
def print_help(venv, root):
help = """
OpenStack development environment setup is complete.
OpenStack development uses virtualenv to track and manage Python
dependencies while in development and testing.
To activate the OpenStack virtualenv for the extent of your current shell
session you can run:
$ source %s/bin/activate
Or, if you prefer, you can run commands in the virtualenv on a case by case
basis by running:
$ %s/tools/with_venv.sh <your command>
Also, make test will automatically use the virtualenv.
"""
print(help % (venv, root))
def main(argv):
root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if os.environ.get('tools_path'):
root = os.environ['tools_path']
venv = os.path.join(root, '.venv')
if os.environ.get('venv'):
venv = os.environ['venv']
pip_requires = os.path.join(root, 'requirements.txt')
test_requires = os.path.join(root, 'test-requirements.txt')
py_version = "python%s.%s" % (sys.version_info[0], sys.version_info[1])
project = 'Tempest'
install = install_venv.InstallVenv(root, venv, pip_requires, test_requires,
py_version, project)
options = install.parse_args(argv)
install.check_python_version()
install.check_dependencies()
install.create_virtualenv(no_site_packages=options.no_site_packages)
install.install_dependencies()
print_help(venv, root)
if __name__ == '__main__':
main(sys.argv)
| apache-2.0 |
rackerlabs/django-DefectDojo | dojo/tools/php_security_audit_v2/parser.py | 1 | 2477 | import json
import math
from dojo.models import Finding
class PhpSecurityAuditV2(object):
def __init__(self, filename, test):
tree = filename.read()
try:
data = json.loads(str(tree, 'utf-8'))
except:
data = json.loads(tree)
dupes = dict()
for filepath, report in list(data["files"].items()):
errors = report.get("errors") or 0
warns = report.get("warnings") or 0
if errors + warns > 0:
for issue in report["messages"]:
title = issue["source"]
findingdetail = "Filename: " + filepath + "\n"
findingdetail += "Line: " + str(issue["line"]) + "\n"
findingdetail += "Column: " + str(issue["column"]) + "\n"
findingdetail += "Rule Source: " + issue["source"] + "\n"
findingdetail += "Details: " + issue["message"] + "\n"
sev = PhpSecurityAuditV2.get_severity_word(issue["severity"])
dupe_key = title + filepath + str(issue["line"]) + str(issue["column"])
if dupe_key in dupes:
find = dupes[dupe_key]
else:
dupes[dupe_key] = True
find = Finding(title=title,
test=test,
active=False,
verified=False,
description=findingdetail,
severity=sev.title(),
numerical_severity=Finding.get_numerical_severity(sev),
mitigation='',
impact='',
references='',
file_path=filepath,
url='N/A',
static_finding=True)
dupes[dupe_key] = find
findingdetail = ''
self.items = list(dupes.values())
@staticmethod
def get_severity_word(severity):
sev = math.ceil(severity / 2)
if sev == 5:
return 'Critical'
elif sev == 4:
return 'High'
elif sev == 3:
return 'Medium'
else:
return 'Low'
| bsd-3-clause |
mouadino/scrapy | extras/scrapy-ws.py | 8 | 3659 | #!/usr/bin/env python
"""
Example script to control a Scrapy server using its JSON-RPC web service.
It only provides a reduced functionality as its main purpose is to illustrate
how to write a web service client. Feel free to improve or write you own.
Also, keep in mind that the JSON-RPC API is not stable. The recommended way for
controlling a Scrapy server is through the execution queue (see the "queue"
command).
"""
import sys, optparse, urllib, json
from urlparse import urljoin
from scrapy.utils.jsonrpc import jsonrpc_client_call, JsonRpcError
def get_commands():
return {
'help': cmd_help,
'stop': cmd_stop,
'list-available': cmd_list_available,
'list-running': cmd_list_running,
'list-resources': cmd_list_resources,
'get-global-stats': cmd_get_global_stats,
'get-spider-stats': cmd_get_spider_stats,
}
def cmd_help(args, opts):
"""help - list available commands"""
print "Available commands:"
for _, func in sorted(get_commands().items()):
print " ", func.__doc__
def cmd_stop(args, opts):
"""stop <spider> - stop a running spider"""
jsonrpc_call(opts, 'crawler/engine', 'close_spider', args[0])
def cmd_list_running(args, opts):
"""list-running - list running spiders"""
for x in json_get(opts, 'crawler/engine/open_spiders'):
print x
def cmd_list_available(args, opts):
"""list-available - list name of available spiders"""
for x in jsonrpc_call(opts, 'crawler/spiders', 'list'):
print x
def cmd_list_resources(args, opts):
"""list-resources - list available web service resources"""
for x in json_get(opts, '')['resources']:
print x
def cmd_get_spider_stats(args, opts):
"""get-spider-stats <spider> - get stats of a running spider"""
stats = jsonrpc_call(opts, 'stats', 'get_stats', args[0])
for name, value in stats.items():
print "%-40s %s" % (name, value)
def cmd_get_global_stats(args, opts):
"""get-global-stats - get global stats"""
stats = jsonrpc_call(opts, 'stats', 'get_stats')
for name, value in stats.items():
print "%-40s %s" % (name, value)
def get_wsurl(opts, path):
return urljoin("http://%s:%s/"% (opts.host, opts.port), path)
def jsonrpc_call(opts, path, method, *args, **kwargs):
url = get_wsurl(opts, path)
return jsonrpc_client_call(url, method, *args, **kwargs)
def json_get(opts, path):
url = get_wsurl(opts, path)
return json.loads(urllib.urlopen(url).read())
def parse_opts():
usage = "%prog [options] <command> [arg] ..."
description = "Scrapy web service control script. Use '%prog help' " \
"to see the list of available commands."
op = optparse.OptionParser(usage=usage, description=description)
op.add_option("-H", dest="host", default="localhost", \
help="Scrapy host to connect to")
op.add_option("-P", dest="port", type="int", default=6080, \
help="Scrapy port to connect to")
opts, args = op.parse_args()
if not args:
op.print_help()
sys.exit(2)
cmdname, cmdargs, opts = args[0], args[1:], opts
commands = get_commands()
if cmdname not in commands:
sys.stderr.write("Unknown command: %s\n\n" % cmdname)
cmd_help(None, None)
sys.exit(1)
return commands[cmdname], cmdargs, opts
def main():
cmd, args, opts = parse_opts()
try:
cmd(args, opts)
except IndexError:
print cmd.__doc__
except JsonRpcError, e:
print str(e)
if e.data:
print "Server Traceback below:"
print e.data
if __name__ == '__main__':
main()
| bsd-3-clause |
campadrenalin/PyTide | NetworkTools/models/websocket.py | 1 | 8197 | """
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
"""
import sys, re, urlparse, socket, asyncore, threading
urlparse.uses_netloc.append("ws")
urlparse.uses_fragment.append("ws")
class WebSocket(object):
def __init__(self, url, **kwargs):
self.host, self.port, self.resource, self.secure = WebSocket._parse_url(url)
self.protocol = kwargs.pop('protocol', None)
self.cookie_jar = kwargs.pop('cookie_jar', None)
self.onopen = kwargs.pop('onopen', None)
self.onmessage = kwargs.pop('onmessage', None)
self.onerror = kwargs.pop('onerror', None)
self.onclose = kwargs.pop('onclose', None)
if kwargs: raise ValueError('Unexpected argument(s): %s' % ', '.join(kwargs.values()))
self._dispatcher = _Dispatcher(self)
def send(self, data,sync=False):
self._dispatcher.write('\x00' + _utf8(data) + '\xff',sync)
def close(self):
self._dispatcher.handle_close()
@classmethod
def _parse_url(cls, url):
p = urlparse.urlparse(url)
if p.hostname:
host = p.hostname
else:
raise ValueError('URL must be absolute')
if p.fragment:
raise ValueError('URL must not contain a fragment component')
if p.scheme == 'ws':
secure = False
port = p.port or 80
elif p.scheme == 'wss':
raise NotImplementedError('Secure WebSocket not yet supported')
# secure = True
# port = p.port or 443
else:
raise ValueError('Invalid URL scheme')
resource = p.path or u'/'
if p.query: resource += u'?' + p.query
return (host, port, resource, secure)
#@classmethod
#def _generate_key(cls):
# spaces = random.randint(1, 12)
# number = random.randint(0, 0xffffffff/spaces)
# key = list(str(number*spaces))
# chars = map(unichr, range(0x21, 0x2f) + range(0x3a, 0x7e))
# random_inserts = random.sample(xrange(len(key)), random.randint(1,12))
# for (i, c) in [(r, random.choice(chars)) for r in random_inserts]:
# key.insert(i, c)
# print key
# return ''.join(key)
class WebSocketError(Exception):
def _init_(self, value):
self.value = value
def _str_(self):
return str(self.value)
class _Dispatcher(asyncore.dispatcher):
def __init__(self, ws):
self.lock = threading.Lock() #threadsafe addon
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((ws.host, ws.port))
self.ws = ws
self._read_buffer = ''
with self.lock: #threadsafe addon
self._write_buffer = ''
self._handshake_complete = False
if self.ws.port != 80:
hostport = '%s:%d' % (self.ws.host, self.ws.port)
else:
hostport = self.ws.host
fields = [
'Upgrade: WebSocket',
'Connection: Upgrade',
'Host: ' + hostport,
'Origin: http://' + hostport,
#'Sec-WebSocket-Key1: %s' % WebSocket.generate_key(),
#'Sec-WebSocket-Key2: %s' % WebSocket.generate_key()
]
if self.ws.protocol: fields['Sec-WebSocket-Protocol'] = self.ws.protocol
if self.ws.cookie_jar:
cookies = filter(lambda c: _cookie_for_domain(c, _eff_host(self.ws.host)) and \
_cookie_for_path(c, self.ws.resource) and \
not c.is_expired(), self.ws.cookie_jar)
for cookie in cookies:
fields.append('Cookie: %s=%s' % (cookie.name, cookie.value))
# key3 = ''.join(map(unichr, (random.randrange(256) for i in xrange(8))))
self.write(_utf8('GET %s HTTP/1.1\r\n' \
'%s\r\n\r\n' % (self.ws.resource,
'\r\n'.join(fields))))
# key3)))
def handl_expt(self):
self.handle_error()
def handle_error(self):
self.close()
t, e, trace = sys.exc_info()
if self.ws.onerror:
self.ws.onerror(e)
else:
asyncore.dispatcher.handle_error(self)
def handle_close(self):
self.close()
if self.ws.onclose:
self.ws.onclose()
def handle_connect (self):
pass
def handle_read(self):
if self._handshake_complete:
self._read_until('\xff', self._handle_frame)
else:
self._read_until('\r\n\r\n', self._handle_header)
def handle_write(self):
with self.lock: #threadsafe addon
sent = self.send(self._write_buffer)
self._write_buffer = self._write_buffer[sent:]
def writable(self):
with self.lock: #threadsafe addon
return len(self._write_buffer) > 0
def write(self, data,sync=False):
with self.lock: #threadsafe addon
self._write_buffer += data # TODO: separate buffer for handshake from data to
# prevent mix-up when send() is called before
# handshake is complete?
if sync:
self.handle_write()
def _read_until(self, delimiter, callback):
self._read_buffer += self.recv(4096)
pos = self._read_buffer.find(delimiter)
if pos >= 0:
pos += len(delimiter)
if pos > 0:
data = self._read_buffer[:pos]
self._read_buffer = self._read_buffer[pos:]
if data:
callback(data)
def _handle_frame(self, frame):
assert frame[-1] == '\xff'
if frame[0] != '\x00':
raise WebSocketError('WebSocket stream error')
if self.ws.onmessage:
self.ws.onmessage(frame[1:-1])
# TODO: else raise WebSocketError('No message handler defined')
def _handle_header(self, header):
assert header[-4:] == '\r\n\r\n'
start_line, fields = _parse_http_header(header)
if start_line != 'HTTP/1.1 101 Web Socket Protocol Handshake' or \
fields.get('Connection', None) != 'Upgrade' or \
fields.get('Upgrade', None) != 'WebSocket':
raise WebSocketError('Invalid server handshake')
self._handshake_complete = True
if self.ws.onopen:
self.ws.onopen()
_IPV4_RE = re.compile(r'\.\d+$')
_PATH_SEP = re.compile(r'/+')
def _parse_http_header(header):
def split_field(field):
k, v = field.split(':', 1)
return (k, v.strip())
lines = header.strip().split('\r\n')
if len(lines) > 0:
start_line = lines[0]
else:
start_line = None
return (start_line, dict(map(split_field, lines[1:])))
def _eff_host(host):
if host.find('.') == -1 and not _IPV4_RE.search(host):
return host + '.local'
return host
def _cookie_for_path(cookie, path):
if not cookie.path or path == '' or path == '/':
return True
path = _PATH_SEP.split(path)[1:]
cookie_path = _PATH_SEP.split(cookie.path)[1:]
for p1, p2 in map(lambda *ps: ps, path, cookie_path):
if p1 == None:
return True
elif p1 != p2:
return False
return True
def _cookie_for_domain(cookie, domain):
if not cookie.domain:
return True
elif cookie.domain[0] == '.':
return domain.endswith(cookie.domain)
else:
return cookie.domain == domain
def _utf8(s):
return s.encode('utf-8')
| apache-2.0 |
ar7z1/ansible | lib/ansible/modules/network/meraki/meraki_vlan.py | 17 | 13516 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Kevin Breit (@kbreit) <kevin.breit@kevinbreit.net>
# 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 = r'''
---
module: meraki_vlan
short_description: Manage VLANs in the Meraki cloud
version_added: "2.7"
description:
- Create, edit, query, or delete VLANs in a Meraki environment.
notes:
- Some of the options are likely only used for developers within Meraki.
- Meraki's API defaults to networks having VLAN support disabled and there is no way to enable VLANs support in the API. VLAN support must be enabled manually.
options:
state:
description:
- Specifies whether object should be queried, created/modified, or removed.
choices: [absent, present, query]
default: query
net_name:
description:
- Name of network which VLAN is in or should be in.
aliases: [network]
net_id:
description:
- ID of network which VLAN is in or should be in.
vlan_id:
description:
- ID number of VLAN.
- ID should be between 1-4096.
name:
description:
- Name of VLAN.
aliases: [vlan_name]
subnet:
description:
- CIDR notation of network subnet.
appliance_ip:
description:
- IP address of appliance.
- Address must be within subnet specified in C(subnet) parameter.
dns_nameservers:
description:
- Semi-colon delimited list of DNS IP addresses.
- Specify one of the following options for preprogrammed DNS entries opendns, google_dns, upstream_dns
reserved_ip_range:
description:
- IP address ranges which should be reserve and not distributed via DHCP.
vpn_nat_subnet:
description:
- The translated VPN subnet if VPN and VPN subnet translation are enabled on the VLAN.
fixed_ip_assignments:
description:
- Static IP address assignements to be distributed via DHCP by MAC address.
author:
- Kevin Breit (@kbreit)
extends_documentation_fragment: meraki
'''
EXAMPLES = r'''
- name: Query all VLANs in a network.
meraki_vlan:
auth_key: abc12345
org_name: YourOrg
net_name: YourNet
state: query
delegate_to: localhost
- name: Query information about a single VLAN by ID.
meraki_vlan:
auth_key: abc12345
org_name: YourOrg
net_name: YourNet
vlan_id: 2
state: query
delegate_to: localhost
- name: Create a VLAN.
meraki_vlan:
auth_key: abc12345
org_name: YourOrg
net_name: YourNet
state: present
vlan_id: 2
name: TestVLAN
subnet: 192.0.1.0/24
appliance_ip: 192.0.1.1
delegate_to: localhost
- name: Update a VLAN.
meraki_vlan:
auth_key: abc12345
org_name: YourOrg
net_name: YourNet
state: present
vlan_id: 2
name: TestVLAN
subnet: 192.0.1.0/24
appliance_ip: 192.168.250.2
fixed_ip_assignments:
- mac: "13:37:de:ad:be:ef"
ip: 192.168.250.10
name: fixed_ip
reserved_ip_range:
- start: 192.168.250.10
end: 192.168.250.20
comment: reserved_range
dns_nameservers: opendns
delegate_to: localhost
- name: Delete a VLAN.
meraki_vlan:
auth_key: abc12345
org_name: YourOrg
net_name: YourNet
state: absent
vlan_id: 2
delegate_to: localhost
'''
RETURN = r'''
response:
description: Information about the organization which was created or modified
returned: success
type: complex
contains:
applianceIp:
description: IP address of Meraki appliance in the VLAN
returned: success
type: string
sample: 192.0.1.1
dnsnamservers:
description: IP address or Meraki defined DNS servers which VLAN should use by default
returned: success
type: string
sample: upstream_dns
fixedIpAssignments:
description: List of MAC addresses which have IP addresses assigned.
returned: success
type: complex
contains:
macaddress:
description: MAC address which has IP address assigned to it. Key value is the actual MAC address.
returned: success
type: complex
contains:
ip:
description: IP address which is assigned to the MAC address.
returned: success
type: string
sample: 192.0.1.4
name:
description: Descriptive name for binding.
returned: success
type: string
sample: fixed_ip
reservedIpRanges:
description: List of IP address ranges which are reserved for static assignment.
returned: success
type: complex
contains:
comment:
description: Description for IP address reservation.
returned: success
type: string
sample: reserved_range
end:
description: Last IP address in reservation range.
returned: success
type: string
sample: 192.0.1.10
start:
description: First IP address in reservation range.
returned: success
type: string
sample: 192.0.1.5
id:
description: VLAN ID number.
returned: success
type: int
sample: 2
name:
description: Descriptive name of VLAN
returned: success
type: string
sample: TestVLAN
networkId:
description: ID number of Meraki network which VLAN is associated to.
returned: success
type: string
sample: N_12345
subnet:
description: CIDR notation IP subnet of VLAN.
returned: success
type: string
sample: 192.0.1.0/24
'''
import os
from ansible.module_utils.basic import AnsibleModule, json, env_fallback
from ansible.module_utils._text import to_native
from ansible.module_utils.network.meraki.meraki import MerakiModule, meraki_argument_spec
def fixed_ip_factory(meraki, data):
fixed_ips = dict()
for item in data:
fixed_ips[item['mac']] = {'ip': item['ip'], 'name': item['name']}
return fixed_ips
def temp_get_nets(meraki, org_name):
org_id = meraki.get_org_id(org_name)
path = meraki.construct_path('get_all', function='network', org_id=org_id)
r = meraki.request(path, method='GET')
return r
def get_vlans(meraki, net_id):
path = meraki.construct_path('get_all', net_id=net_id)
return meraki.request(path, method='GET')
# TODO: Allow method to return actual item if True to reduce number of calls needed
def is_vlan_valid(meraki, net_id, vlan_id):
vlans = get_vlans(meraki, net_id)
for vlan in vlans:
if vlan_id == vlan['id']:
return True
return False
def format_dns(nameservers):
return nameservers.replace(';', '\n')
def main():
# define the available arguments/parameters that a user can pass to
# the module
fixed_ip_arg_spec = dict(mac=dict(type='str'),
ip=dict(type='str'),
name=dict(type='str'),
)
reserved_ip_arg_spec = dict(start=dict(type='str'),
end=dict(type='str'),
comment=dict(type='str'),
)
argument_spec = meraki_argument_spec()
argument_spec.update(state=dict(type='str', choices=['absent', 'present', 'query'], default='query'),
net_name=dict(type='str', aliases=['network']),
net_id=dict(type='str'),
vlan_id=dict(type='int'),
name=dict(type='str', aliases=['vlan_name']),
subnet=dict(type='str'),
appliance_ip=dict(type='str'),
fixed_ip_assignments=dict(type='list', default=None, elements='dict', options=fixed_ip_arg_spec),
reserved_ip_range=dict(type='list', default=None, elements='dict', options=reserved_ip_arg_spec),
vpn_nat_subnet=dict(type='str'),
dns_nameservers=dict(type='str'),
)
# seed the result dict in the object
# we primarily care about changed and state
# change is if this module effectively modified the target
# state will include any data that you want your module to pass back
# for consumption, for example, in a subsequent task
result = dict(
changed=False,
)
# the AnsibleModule object will be our abstraction working with Ansible
# this includes instantiation, a couple of common attr would be the
# args/params passed to the execution, as well as if the module
# supports check mode
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True,
)
meraki = MerakiModule(module, function='vlan')
meraki.params['follow_redirects'] = 'all'
query_urls = {'vlan': '/networks/{net_id}/vlans'}
query_url = {'vlan': '/networks/{net_id}/vlans/{vlan_id}'}
create_url = {'vlan': '/networks/{net_id}/vlans'}
update_url = {'vlan': '/networks/{net_id}/vlans/'}
delete_url = {'vlan': '/networks/{net_id}/vlans/'}
meraki.url_catalog['get_all'].update(query_urls)
meraki.url_catalog['get_one'].update(query_url)
meraki.url_catalog['create'] = create_url
meraki.url_catalog['update'] = update_url
meraki.url_catalog['delete'] = delete_url
payload = None
org_id = meraki.params['org_id']
if org_id is None:
org_id = meraki.get_org_id(meraki.params['org_name'])
nets = meraki.get_nets(org_id=org_id)
net_id = None
if meraki.params['net_name']:
net_id = meraki.get_net_id(net_name=meraki.params['net_name'], data=nets)
elif meraki.params['net_id']:
net_id = meraki.params['net_id']
if meraki.params['state'] == 'query':
if not meraki.params['vlan_id']:
meraki.result['data'] = get_vlans(meraki, net_id)
else:
path = meraki.construct_path('get_one', net_id=net_id, custom={'vlan_id': meraki.params['vlan_id']})
response = meraki.request(path, method='GET')
meraki.result['data'] = response
elif meraki.params['state'] == 'present':
payload = {'id': meraki.params['vlan_id'],
'name': meraki.params['name'],
'subnet': meraki.params['subnet'],
'applianceIp': meraki.params['appliance_ip'],
}
if is_vlan_valid(meraki, net_id, meraki.params['vlan_id']) is False:
path = meraki.construct_path('create', net_id=net_id)
response = meraki.request(path, method='POST', payload=json.dumps(payload))
meraki.result['changed'] = True
meraki.result['data'] = response
else:
path = meraki.construct_path('get_one', net_id=net_id, custom={'vlan_id': meraki.params['vlan_id']})
original = meraki.request(path, method='GET')
if meraki.params['dns_nameservers']:
if meraki.params['dns_nameservers'] not in ('opendns', 'google_dns', 'upstream_dns'):
payload['dnsNameservers'] = format_dns(meraki.params['dns_nameservers'])
else:
payload['dnsNameservers'] = meraki.params['dns_nameservers']
if meraki.params['fixed_ip_assignments']:
payload['fixedIpAssignments'] = fixed_ip_factory(meraki, meraki.params['fixed_ip_assignments'])
if meraki.params['reserved_ip_range']:
payload['reservedIpRanges'] = meraki.params['reserved_ip_range']
if meraki.params['vpn_nat_subnet']:
payload['vpnNatSubnet'] = meraki.params['vpn_nat_subnet']
ignored = ['networkId']
if meraki.is_update_required(original, payload, optional_ignore=ignored):
path = meraki.construct_path('update', net_id=net_id) + str(meraki.params['vlan_id'])
response = meraki.request(path, method='PUT', payload=json.dumps(payload))
meraki.result['changed'] = True
meraki.result['data'] = response
elif meraki.params['state'] == 'absent':
if is_vlan_valid(meraki, net_id, meraki.params['vlan_id']):
path = meraki.construct_path('delete', net_id=net_id) + str(meraki.params['vlan_id'])
response = meraki.request(path, 'DELETE')
meraki.result['changed'] = True
meraki.result['data'] = response
# if the user is working with this module in only check mode we do not
# want to make any changes to the environment, just return the current
# state with no modifications
# FIXME: Work with Meraki so they can implement a check mode
if module.check_mode:
meraki.exit_json(**meraki.result)
# execute checks for argument completeness
# manipulate or modify the state as needed (this is going to be the
# part where your module will do what it needs to do)
# in the event of a successful module execution, you will want to
# simple AnsibleModule.exit_json(), passing the key/value results
meraki.exit_json(**meraki.result)
if __name__ == '__main__':
main()
| gpl-3.0 |
sebaleh/AliPhysics | PWGJE/EMCALJetTasks/Tracks/analysis/base/struct/ClusterTHnSparse.py | 41 | 5256 | #**************************************************************************
#* Copyright(c) 1998-2014, ALICE Experiment at CERN, All rights reserved. *
#* *
#* Author: The ALICE Off-line Project. *
#* Contributors are mentioned in the code where appropriate. *
#* *
#* Permission to use, copy, modify and distribute this software and its *
#* documentation strictly for non-commercial purposes is hereby granted *
#* without fee, provided that the above copyright notice appears in all *
#* copies and that both the copyright notice and this permission notice *
#* appear in the supporting documentation. The authors make no claims *
#* about the suitability of this software for any purpose. It is *
#* provided "as is" without express or implied warranty. *
#**************************************************************************
from PWGJE.EMCALJetTasks.Tracks.analysis.base.struct.THnSparseWrapper import THnSparseWrapper,AxisFormat
from copy import copy,deepcopy
class AxisFormatClustersOld(AxisFormat):
'''
Axis format for old cluster THnSparse
'''
def __init__(self):
'''
Constructor
'''
AxisFormat.__init__(self, "clustersold")
self._axes["energy"] = 0
self._axes["vertexz"] = 1
self._axes["pileup"] = 2
self._axes["mbtrigger"] = 3
def __deepcopy__(self, other, memo):
'''
Deep copy constructor
'''
newobj = AxisFormatClustersOld()
newobj._Deepcopy(other, memo)
return newobj
def __copy__(self, other):
'''
Shallow copy constructor
'''
newobj = AxisFormatClustersOld()
newobj._Copy()
return newobj
class AxisFormatClustersNew(AxisFormat):
'''
Axis format for new cluster THnSparse
'''
def __init__(self):
'''
Constructor
'''
AxisFormat.__init__(self, "clustersnew")
self._axes["energy"] = 0
self._axes["eta"] = 1
self._axes["phi"] = 2
self._axes["vertexz"] = 3
self._axes["mbtrigger"] = 4
def __deepcopy__(self, memo):
'''
Deep copy constructor
'''
newobj = AxisFormatClustersNew()
newobj._Deepcopy(self, memo)
return newobj
def __copy__(self, other):
'''
Shallow copy constructor
'''
newobj = AxisFormatClustersNew()
newobj._Copy(self)
return newobj
class ClusterTHnSparse(THnSparseWrapper):
'''
Base class wrapper for cluster-based THnSparse
'''
def __init__(self, roothist):
'''
Constructor
'''
THnSparseWrapper.__init__(self, roothist)
def SetEtaCut(self, etamin, etamax):
'''
Apply cut in eta
'''
self.ApplyCut("eta",etamin,etamax)
def SetPhiCut(self, phimin, phimax):
'''
Apply cut in phi
'''
self.ApplyCut("phi", phimin, phimax)
def SetVertexCut(self, vzmin, vzmax):
'''
Apply cut on vertex-z
'''
self.ApplyCut("vertexz", vzmin, vzmax)
def SetRequestSeenInMB(self, vzmin, vzmax):
'''
Request that the track was also in a min. bias event
'''
self.ApplyCut("mbtrigger", 1., 1.)
def SetPileupRejection(self, on):
if on and self._axisdefinition.FindAxis("pileup"):
self.ApplyCut("pileup", 1., 1.)
def Print(self):
pass
class ClusterTHnSparseOld(ClusterTHnSparse):
'''
Old format cluster THnSparse
'''
def __init__(self, roothist):
'''
Constructor
'''
ClusterTHnSparse.__init__(self, roothist)
self._axisdefinition = AxisFormatClustersOld()
def __deepcopy__(self, memo):
'''
Deep copy constructor
'''
result = ClusterTHnSparseOld(deepcopy(self._rootthnsparse))
result.CopyCuts(self._cutlist, True)
return result
def __copy__(self):
'''
Shallow copy constructor
'''
result = ClusterTHnSparseOld(copy(self._rootthnsparse))
result.CopyCuts(self._cutlist, False)
return result
class ClusterTHnSparseNew(ClusterTHnSparse):
'''
New format cluster THnSparse
'''
def __init__(self, roothist):
'''
Constructor
'''
ClusterTHnSparse.__init__(self, roothist)
self._axisdefinition = AxisFormatClustersNew()
def __deepcopy__(self, memo):
'''
Deep copy constructor
'''
result = ClusterTHnSparseNew(deepcopy(self._rootthnsparse))
result.CopyCuts(self._cutlist, True)
return result
def __copy__(self):
'''
Shallow copy constructor
'''
result = ClusterTHnSparseNew(copy(self._rootthnsparse))
result.CopyCuts(self._cutlist, False)
return result | bsd-3-clause |
dbaxa/django | tests/auth_tests/models/invalid_models.py | 251 | 1340 | from django.contrib.auth.models import AbstractBaseUser, UserManager
from django.db import models
class CustomUserNonUniqueUsername(AbstractBaseUser):
"""
A user with a non-unique username.
This model is not invalid if it is used with a custom authentication
backend which supports non-unique usernames.
"""
username = models.CharField(max_length=30)
email = models.EmailField(blank=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email']
objects = UserManager()
class Meta:
app_label = 'auth'
class CustomUserNonListRequiredFields(AbstractBaseUser):
"A user with a non-list REQUIRED_FIELDS"
username = models.CharField(max_length=30, unique=True)
date_of_birth = models.DateField()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = 'date_of_birth'
class Meta:
app_label = 'auth'
class CustomUserBadRequiredFields(AbstractBaseUser):
"A user with a USERNAME_FIELD that appears in REQUIRED_FIELDS (invalid)"
username = models.CharField(max_length=30, unique=True)
date_of_birth = models.DateField()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['username', 'date_of_birth']
class Meta:
app_label = 'auth'
| bsd-3-clause |
mpachas/django-embed-video | embed_video/tests/backends/tests_youtube.py | 1 | 2440 | from unittest import TestCase
from . import BackendTestMixin
from embed_video.backends import YoutubeBackend, UnknownIdException
class YoutubeBackendTestCase(BackendTestMixin, TestCase):
urls = (
('http://youtu.be/jsrRJyHBvzw', 'jsrRJyHBvzw'),
('http://youtu.be/n17B_uFF4cA', 'n17B_uFF4cA'),
('http://youtu.be/t-ZRX8984sc', 't-ZRX8984sc'),
('https://youtu.be/t-ZRX8984sc', 't-ZRX8984sc'),
('http://youtube.com/watch?v=jsrRJyHBvzw', 'jsrRJyHBvzw'),
('https://youtube.com/watch?v=jsrRJyHBvzw', 'jsrRJyHBvzw'),
('http://www.youtube.com/v/0zM3nApSvMg?rel=0', '0zM3nApSvMg'),
('https://www.youtube.com/v/0zM3nApSvMg?rel=0', '0zM3nApSvMg'),
('http://www.youtube.com/embed/0zM3nApSvMg?rel=0', '0zM3nApSvMg'),
('https://www.youtube.com/embed/0zM3nApSvMg?rel=0', '0zM3nApSvMg'),
('http://www.youtube.com/watch?v=jsrRJyHBvzw', 'jsrRJyHBvzw'),
('https://www.youtube.com/watch?v=t-ZRX8984sc', 't-ZRX8984sc'),
('http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related', 'iwGFalTRHDA'),
('https://www.youtube.com/watch?v=iwGFalTRHDA&feature=related', 'iwGFalTRHDA'),
('http://www.youtube.com/watch?feature=player_embedded&v=2NpZbaAIXag', '2NpZbaAIXag'),
('https://www.youtube.com/watch?feature=player_embedded&v=2NpZbaAIXag', '2NpZbaAIXag'),
('https://www.youtube.com/watch?v=XPk521voaOE&feature=youtube_gdata_player', 'XPk521voaOE'),
('http://www.youtube.com/watch?v=6xu00J3-g2s&list=PLb5n6wzDlPakFKvJ69rJ9AJW24Aaaki2z', '6xu00J3-g2s'),
('https://m.youtube.com/#/watch?v=IAooXLAPoBQ', 'IAooXLAPoBQ'),
('https://m.youtube.com/watch?v=IAooXLAPoBQ', 'IAooXLAPoBQ'),
('http://www.youtube.com/edit?video_id=eBea01qmnOE', 'eBea01qmnOE')
)
instance = YoutubeBackend
def test_youtube_keyerror(self):
""" Test for issue #7 """
backend = self.instance('http://youtube.com/watch?id=5')
self.assertRaises(UnknownIdException, backend.get_code)
def test_thumbnail(self):
for url in self.urls:
backend = self.instance(url[0])
self.assertIn(url[1], backend.thumbnail)
def test_get_better_resolution_youtube(self):
backend = self.instance('https://www.youtube.com/watch?v=1Zo0-sWD7xE')
self.assertIn(
'img.youtube.com/vi/1Zo0-sWD7xE/maxresdefault.jpg',
backend.thumbnail)
| mit |
easherma/GAM_website | GAM_website/payments/views.py | 1 | 5755 | from flask import Blueprint, flash, redirect, render_template, request, url_for, jsonify
import braintree
import os
from os.path import join, dirname
from dotenv import load_dotenv, find_dotenv
blueprint = Blueprint('payments', __name__, static_folder='../static')
# dotenv_path = join('..', '..', dirname(__file__), '.env')
# print(dotenv_path)
load_dotenv(find_dotenv())
secret_key = os.environ.get('APP_SECRET_KEY')
braintree.Configuration.configure(
os.environ.get('BT_ENVIRONMENT'),
os.environ.get('BT_MERCHANT_ID'),
os.environ.get('BT_PUBLIC_KEY'),
os.environ.get('BT_PRIVATE_KEY')
)
TRANSACTION_SUCCESS_STATUSES = [
braintree.Transaction.Status.Authorized,
braintree.Transaction.Status.Authorizing,
braintree.Transaction.Status.Settled,
braintree.Transaction.Status.SettlementConfirmed,
braintree.Transaction.Status.SettlementPending,
braintree.Transaction.Status.Settling,
braintree.Transaction.Status.SubmittedForSettlement
]
@blueprint.route('/payments/', methods=['GET'])
def donate():
client_token = braintree.ClientToken.generate()
return render_template('payments/checkouts/donate_form.html', client_token=client_token)
@blueprint.route('/payments/checkouts/new', methods=['GET'])
def new_checkout():
client_token = braintree.ClientToken.generate()
return render_template('payments/checkouts/donate_form.html', client_token=client_token)
@blueprint.route('/payments/checkouts/<transaction_id>', methods=['GET'])
def show_checkout(transaction_id):
transaction = braintree.Transaction.find(transaction_id)
result = {}
if transaction.status in TRANSACTION_SUCCESS_STATUSES:
result = {
'header': 'Sweet Success!',
'icon': 'success',
'message': 'Your test transaction has been successfully processed. See the Braintree API response and try again.'
}
else:
result = {
'header': 'Transaction Failed',
'icon': 'fail',
'message': 'Your test transaction has a status of ' + transaction.status + '. See the Braintree API response and try again.'
}
return render_template('payments/checkouts/show.html', transaction=transaction, result=result)
@blueprint.route('/payments/checkouts', methods=['POST'])
def create_checkout():
print(request.form)
result = None
# single non subscription payment (should this be possible?)
# if 'recurring' not in request.form:
# result = braintree.Transaction.sale({
# 'amount': request.form['amount'],
# 'payment_method_nonce': request.form['payment_method_nonce'],
# 'customer': {
# 'first_name': request.form['first_name'],
# 'last_name': request.form['last_name'],
# 'email': request.form['email']
# },
# 'options': {
# "submit_for_settlement": True,
# "store_in_vault_on_success": True,
# }
# })
# recurring payments
if os.environ.get('BT_ENVIRONMENT') == 'sandbox':
customer_result = braintree.Customer.create({
'first_name': request.form['first_name'],
'last_name': request.form['last_name'],
'email': request.form['email'],
"payment_method_nonce": 'fake-valid-no-billing-address-nonce'
})
else:
customer_result = braintree.Customer.create({
'first_name': request.form['first_name'],
'last_name': request.form['last_name'],
'email': request.form['email'],
"payment_method_nonce": request.form['payment_method_nonce']
})
try:
if customer_result.is_success:
customer_id = customer_result.customer.id
payment_token = customer_result.customer.payment_methods[0].token
result = braintree.Subscription.create({
# 'payment_method_nonce': request.form['payment_method_nonce'],
"payment_method_token": payment_token,
# type
"plan_id": str(request.form['options'] + request.form['tier']),
# "price": request.form['amount'],
# "options": {
# "start_immediately": True
# }
})
else:
print("no subscription created")
result = None
except Exception as e:
print("ERROR")
error_code = "An error occured:"
print(e)
flash('Error: %s: %s' % (error_code, e))
return redirect(url_for('public.home'))
# return redirect(url_for('public.home'))
# if customer_result.is_success:
# import pdb; pdb.set_trace()
if result:
if (result.is_success == True or result.transaction):
flash("success")
return redirect(url_for('public.home'))
# return redirect(url_for('payments.show_checkout',transaction_id=result.transaction.id))
elif result.errors:
for error in result.errors.deep_errors:
print("ERROR")
print(error.code)
print(error.message)
flash('Error: %s: %s' % (error.code, error.message))
return redirect(url_for('public.home'))
elif not customer_result.is_success:
print("ERROR")
error_code = "No Customer,"
print(customer_result.message)
flash('Error: %s: %s' % (error_code, customer_result.message))
return redirect(url_for('public.home'))
else:
print("ERROR")
flash('Error: %s: %s' % ("General Error:", "contact us for details"))
return redirect(url_for('public.home'))
return redirect(url_for('public.home'))
| bsd-3-clause |
js0701/chromium-crosswalk | native_client_sdk/src/tools/run.py | 51 | 3016 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""Launch a local http server, then launch a executable directed at the server.
This command creates a local server (on port 5103 by default) then runs:
<executable> <args..> http://localhost:<port>/<page>.
Where <page> can be set by -P, or uses index.html by default.
"""
import argparse
import copy
import getos
import os
import subprocess
import sys
import httpd
if sys.version_info < (2, 7, 0):
sys.stderr.write("python 2.7 or later is required run this script\n")
sys.exit(1)
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-C', '--serve-dir',
help='Serve files out of this directory.',
dest='serve_dir', default=os.path.abspath('.'))
parser.add_argument('-P', '--path', help='Path to load from local server.',
dest='path', default='index.html')
parser.add_argument('-D',
help='Add debug command-line when launching the chrome debug.',
dest='debug', action='append', default=[])
parser.add_argument('-E',
help='Add environment variables when launching the executable.',
dest='environ', action='append', default=[])
parser.add_argument('-p', '--port',
help='Port to run server on. Default is 5103, ephemeral is 0.',
type=int, default=5103)
parser.add_argument('executable', help='command to run')
parser.add_argument('args', nargs='*', help='arguments for executable')
options = parser.parse_args(args)
# 0 means use an ephemeral port.
server = httpd.LocalHTTPServer(options.serve_dir, options.port)
print 'Serving %s on %s...' % (options.serve_dir, server.GetURL(''))
env = copy.copy(os.environ)
for e in options.environ:
key, value = map(str.strip, e.split('='))
env[key] = value
cmd = [options.executable] + options.args + [server.GetURL(options.path)]
print 'Running: %s...' % (' '.join(cmd),)
process = subprocess.Popen(cmd, env=env)
# If any debug args are passed in, assume we want to debug
if options.debug:
if getos.GetPlatform() == 'linux':
cmd = ['xterm', '-title', 'NaCl Debugger', '-e']
cmd += options.debug
elif getos.GetPlatform() == 'mac':
cmd = ['osascript', '-e',
'tell application "Terminal" to do script "%s"' %
' '.join(r'\"%s\"' % x for x in options.debug)]
elif getos.GetPlatform() == 'win':
cmd = ['cmd.exe', '/c', 'start', 'cmd.exe', '/c']
cmd += options.debug
print 'Starting debugger: ' + ' '.join(cmd)
debug_process = subprocess.Popen(cmd, env=env)
else:
debug_process = False
try:
return server.ServeUntilSubprocessDies(process)
finally:
if process.returncode is None:
process.kill()
if debug_process and debug_process.returncode is None:
debug_process.kill()
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| bsd-3-clause |
GeorgePlukov/FloodWatch | XBee-2.2.3/examples/led_adc_example.py | 1 | 2772 | #! /usr/bin/python
"""
led_adc_example.py
By Paul Malmsten, 2010
pmalmsten@gmail.com
A simple example which sets up a remote device to read an analog value
on ADC0 and a digital output on DIO1. It will then read voltage
measurements and write an active-low result to the remote DIO1 pin.
"""
from xbee import XBee
import serial
ser = serial.Serial('/dev/tty.usbserial-142', 9600)
xbee = XBee(ser)
## Set up remote device
#xbee.send('remote_at',
#frame_id='A',
#dest_addr_long='\x00\x00\x00\x00\x00\x00\x00\x00',
#dest_addr='\x56\x78',
#options='\x02',
#command='D0',
#parameter='\x02')
#print xbee.wait_read_frame()['status']
#xbee.send('remote_at',
#frame_id='B',
#dest_addr_long='\x00\x00\x00\x00\x00\x00\x00\x00',
#dest_addr='\x56\x78',
#options='\x02',
#command='D1',
#parameter='\x05')
#print xbee.wait_read_frame()['status']
#xbee.send('remote_at',
#frame_id='C',
#dest_addr_long='\x00\x00\x00\x00\x00\x00\x00\x00',
#dest_addr='\x56\x78',
#options='\x02',
#command='IR',
#parameter='\x32')
#print xbee.wait_read_frame()['status']
#xbee.send('remote_at',
#frame_id='C',
#dest_addr_long='\x00\x00\x00\x00\x00\x00\x00\x00',
#dest_addr='\x56\x78',
#options='\x02',
#command='WR')
# Deactivate alarm pin
xbee.remote_at(
dest_addr='\x56\x78',
command='D2',
parameter='\x04')
xbee.remote_at(
dest_addr='\x56\x78',
command='WR')
print ("test")
# print xbee.wait_read_frame()['status']
print ("test2")
while True:
try:
packet = xbee.wait_read_frame()
print packet
# If it's a sample, check it
if packet['id'] == 'rx_io_data':
# Set remote LED status
if packet['samples'][0]['adc-0'] > 160:
# Active low
xbee.remote_at(
dest_addr='\x56\x78',
command='D1',
parameter='\x04')
# Active high alarm pin
xbee.remote_at(
dest_addr='\x56\x78',
command='D2',
parameter='\x05')
else:
xbee.remote_at(
dest_addr='\x56\x78',
command='D1',
parameter='\x05')
# Deactivate alarm pin
xbee.remote_at(
dest_addr='\x56\x78',
command='D2',
parameter='\x04')
except KeyboardInterrupt:
break
ser.close()
| mit |
yb-kim/gemV | util/streamline/m5stats2streamline.py | 3 | 41662 | #!/usr/bin/env python
# Copyright (c) 2012 ARM Limited
# All rights reserved
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# 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.
#
# Author: Dam Sunwoo
#
# This script converts gem5 output to ARM DS-5 Streamline .apc project file
# (Requires the gem5 runs to be run with ContextSwitchStatsDump enabled and
# some patches applied to target Linux kernel.)
# Visit http://www.gem5.org/Streamline for more details.
#
# Usage:
# m5stats2streamline.py <stat_config.ini> <gem5 run folder> <dest .apc folder>
#
# <stat_config.ini>: .ini file that describes which stats to be included
# in conversion. Sample .ini files can be found in
# util/streamline.
# NOTE: this is NOT the gem5 config.ini file.
#
# <gem5 run folder>: Path to gem5 run folder (must contain config.ini,
# stats.txt[.gz], and system.tasks.txt.)
#
# <dest .apc folder>: Destination .apc folder path
#
# APC project generation based on Gator v12 (DS-5 v5.13)
# Subsequent versions should be backward compatible
import re, sys, os
from ConfigParser import ConfigParser
import gzip
import xml.etree.ElementTree as ET
import xml.dom.minidom as minidom
import shutil
import zlib
import argparse
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description="""
Converts gem5 runs to ARM DS-5 Streamline .apc project file.
(NOTE: Requires gem5 runs to be run with ContextSwitchStatsDump
enabled and some patches applied to the target Linux kernel.)
Visit http://www.gem5.org/Streamline for more details.
APC project generation based on Gator v12 (DS-5 v5.13)
Subsequent versions should be backward compatible
""")
parser.add_argument("stat_config_file", metavar="<stat_config.ini>",
help=".ini file that describes which stats to be included \
in conversion. Sample .ini files can be found in \
util/streamline. NOTE: this is NOT the gem5 config.ini \
file.")
parser.add_argument("input_path", metavar="<gem5 run folder>",
help="Path to gem5 run folder (must contain config.ini, \
stats.txt[.gz], and system.tasks.txt.)")
parser.add_argument("output_path", metavar="<dest .apc folder>",
help="Destination .apc folder path")
parser.add_argument("--num-events", action="store", type=int,
default=1000000,
help="Maximum number of scheduling (context switch) \
events to be processed. Set to truncate early. \
Default=1000000")
parser.add_argument("--gzipped-bmp-not-supported", action="store_true",
help="Do not use gzipped .bmp files for visual annotations. \
This option is only required when using Streamline versions \
older than 5.14")
parser.add_argument("--verbose", action="store_true",
help="Enable verbose output")
args = parser.parse_args()
if not re.match("(.*)\.apc", args.output_path):
print "ERROR: <dest .apc folder> should end with '.apc'!"
sys.exit(1)
# gzipped BMP files for visual annotation is supported in Streamline 5.14.
# Setting this to True will significantly compress the .apc binary file that
# includes frame buffer snapshots.
gzipped_bmp_supported = not args.gzipped_bmp_not_supported
ticks_in_ns = -1
# Default max # of events. Increase this for longer runs.
num_events = args.num_events
start_tick = -1
end_tick = -1
# Parse gem5 config.ini file to determine some system configurations.
# Number of CPUs, L2s, etc.
def parseConfig(config_file):
global num_cpus, num_l2
print "\n==============================="
print "Parsing gem5 config.ini file..."
print config_file
print "===============================\n"
config = ConfigParser()
if not config.read(config_file):
print "ERROR: config file '", config_file, "' not found"
sys.exit(1)
if config.has_section("system.cpu"):
num_cpus = 1
else:
num_cpus = 0
while config.has_section("system.cpu" + str(num_cpus)):
num_cpus += 1
if config.has_section("system.l2"):
num_l2 = 1
else:
num_l2 = 0
while config.has_section("system.l2" + str(num_l2)):
num_l2 += 1
print "Num CPUs:", num_cpus
print "Num L2s:", num_l2
print ""
return (num_cpus, num_l2)
process_dict = {}
thread_dict = {}
process_list = []
idle_uid = -1
kernel_uid = -1
class Task(object):
def __init__(self, uid, pid, tgid, task_name, is_process, tick):
if pid == 0: # Idle
self.uid = 0
elif pid == -1: # Kernel
self.uid = 0
else:
self.uid = uid
self.pid = pid
self.tgid = tgid
self.is_process = is_process
self.task_name = task_name
self.children = []
self.tick = tick # time this task first appeared
class Event(object):
def __init__(self, tick, task):
self.tick = tick
self.task = task
############################################################
# Types used in APC Protocol
# - packed32, packed64
# - int32
# - string
############################################################
# variable length packed 4-byte signed value
def packed32(x):
ret = []
if ((x & 0xffffff80) == 0):
ret.append(x & 0x7f)
elif ((x & 0xffffc000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append((x >> 7) & 0x7f)
elif ((x & 0xffe00000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append((x >> 14) & 0x7f)
elif ((x & 0xf0000000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append(((x >> 14) | 0x80) & 0xff)
ret.append((x >> 21) & 0x7f)
else:
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append(((x >> 14) | 0x80) & 0xff)
ret.append(((x >> 21) | 0x80) & 0xff)
ret.append((x >> 28) & 0x0f)
return ret
# variable length packed 8-byte signed value
def packed64(x):
ret = []
if ((x & 0xffffffffffffff80) == 0):
ret.append(x & 0x7f)
elif ((x & 0xffffffffffffc000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append((x >> 7) & 0x7f)
elif ((x & 0xffffffffffe00000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append((x >> 14) & 0x7f)
elif ((x & 0xfffffffff0000000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append(((x >> 14) | 0x80) & 0xff)
ret.append((x >> 21) & 0x7f)
elif ((x & 0xfffffff800000000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append(((x >> 14) | 0x80) & 0xff)
ret.append(((x >> 21) | 0x80) & 0xff)
ret.append((x >> 28) & 0x7f)
elif ((x & 0xfffffc0000000000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append(((x >> 14) | 0x80) & 0xff)
ret.append(((x >> 21) | 0x80) & 0xff)
ret.append(((x >> 28) | 0x80) & 0xff)
ret.append((x >> 35) & 0x7f)
elif ((x & 0xfffe000000000000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append(((x >> 14) | 0x80) & 0xff)
ret.append(((x >> 21) | 0x80) & 0xff)
ret.append(((x >> 28) | 0x80) & 0xff)
ret.append(((x >> 35) | 0x80) & 0xff)
ret.append((x >> 42) & 0x7f)
elif ((x & 0xff00000000000000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append(((x >> 14) | 0x80) & 0xff)
ret.append(((x >> 21) | 0x80) & 0xff)
ret.append(((x >> 28) | 0x80) & 0xff)
ret.append(((x >> 35) | 0x80) & 0xff)
ret.append(((x >> 42) | 0x80) & 0xff)
ret.append((x >> 49) & 0x7f)
elif ((x & 0x8000000000000000) == 0):
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append(((x >> 14) | 0x80) & 0xff)
ret.append(((x >> 21) | 0x80) & 0xff)
ret.append(((x >> 28) | 0x80) & 0xff)
ret.append(((x >> 35) | 0x80) & 0xff)
ret.append(((x >> 42) | 0x80) & 0xff)
ret.append(((x >> 49) | 0x80) & 0xff)
ret.append((x >> 56) & 0x7f)
else:
ret.append((x | 0x80) & 0xff)
ret.append(((x >> 7) | 0x80) & 0xff)
ret.append(((x >> 14) | 0x80) & 0xff)
ret.append(((x >> 21) | 0x80) & 0xff)
ret.append(((x >> 28) | 0x80) & 0xff)
ret.append(((x >> 35) | 0x80) & 0xff)
ret.append(((x >> 42) | 0x80) & 0xff)
ret.append(((x >> 49) | 0x80) & 0xff)
ret.append(((x >> 56) | 0x80) & 0xff)
ret.append((x >> 63) & 0x7f)
return ret
# 4-byte signed little endian
def int32(x):
ret = []
ret.append(x & 0xff)
ret.append((x >> 8) & 0xff)
ret.append((x >> 16) & 0xff)
ret.append((x >> 24) & 0xff)
return ret
# 2-byte signed little endian
def int16(x):
ret = []
ret.append(x & 0xff)
ret.append((x >> 8) & 0xff)
return ret
# a packed32 length followed by the specified number of characters
def stringList(x):
ret = []
ret += packed32(len(x))
for i in x:
ret.append(i)
return ret
def utf8StringList(x):
ret = []
for i in x:
ret.append(ord(i))
return ret
# packed64 time value in nanoseconds relative to the uptime from the
# Summary message.
def timestampList(x):
ret = packed64(x)
return ret
############################################################
# Write binary
############################################################
def writeBinary(outfile, binary_list):
for i in binary_list:
outfile.write("%c" % i)
############################################################
# APC Protocol Frame Types
############################################################
def addFrameHeader(frame_type, body, core):
ret = []
if frame_type == "Summary":
code = 1
elif frame_type == "Backtrace":
code = 2
elif frame_type == "Name":
code = 3
elif frame_type == "Counter":
code = 4
elif frame_type == "Block Counter":
code = 5
elif frame_type == "Annotate":
code = 6
elif frame_type == "Sched Trace":
code = 7
elif frame_type == "GPU Trace":
code = 8
elif frame_type == "Idle":
code = 9
else:
print "ERROR: Unknown frame type:", frame_type
sys.exit(1)
packed_code = packed32(code)
packed_core = packed32(core)
length = int32(len(packed_code) + len(packed_core) + len(body))
ret = length + packed_code + packed_core + body
return ret
# Summary frame
# - timestamp: packed64
# - uptime: packed64
def summaryFrame(timestamp, uptime):
frame_type = "Summary"
body = packed64(timestamp) + packed64(uptime)
ret = addFrameHeader(frame_type, body, 0)
return ret
# Backtrace frame
# - not implemented yet
def backtraceFrame():
pass
# Cookie name message
# - cookie: packed32
# - name: string
def cookieNameFrame(cookie, name):
frame_type = "Name"
packed_code = packed32(1)
body = packed_code + packed32(cookie) + stringList(name)
ret = addFrameHeader(frame_type, body, 0)
return ret
# Thread name message
# - timestamp: timestamp
# - thread id: packed32
# - name: string
def threadNameFrame(timestamp, thread_id, name):
frame_type = "Name"
packed_code = packed32(2)
body = packed_code + timestampList(timestamp) + \
packed32(thread_id) + stringList(name)
ret = addFrameHeader(frame_type, body, 0)
return ret
# Core name message
# - name: string
def coreNameFrame(name):
frame_type = "Name"
packed_code = packed32(3)
body = packed_code + stringList(name)
ret = addFrameHeader(frame_type, body, 0)
return ret
# Counter frame message
# - timestamp: timestamp
# - core: packed32
# - key: packed32
# - value: packed64
def counterFrame(timestamp, core, key, value):
frame_type = "Counter"
body = timestampList(timestamp) + packed32(core) + packed32(key) + \
packed64(value)
ret = addFrameHeader(frame_type, body, core)
return ret
# Block Counter frame message
# - key: packed32
# - value: packed64
def blockCounterFrame(core, key, value):
frame_type = "Block Counter"
body = packed32(key) + packed64(value)
ret = addFrameHeader(frame_type, body, core)
return ret
# Annotate frame messages
# - core: packed32
# - tid: packed32
# - timestamp: timestamp
# - size: packed32
# - body
def annotateFrame(core, tid, timestamp, size, userspace_body):
frame_type = "Annotate"
body = packed32(core) + packed32(tid) + timestampList(timestamp) + \
packed32(size) + userspace_body
ret = addFrameHeader(frame_type, body, core)
return ret
# Scheduler Trace frame messages
# Sched Switch
# - Code: 1
# - timestamp: timestamp
# - pid: packed32
# - tid: packed32
# - cookie: packed32
# - state: packed32
def schedSwitchFrame(core, timestamp, pid, tid, cookie, state):
frame_type = "Sched Trace"
body = packed32(1) + timestampList(timestamp) + packed32(pid) + \
packed32(tid) + packed32(cookie) + packed32(state)
ret = addFrameHeader(frame_type, body, core)
return ret
# Sched Thread Exit
# - Code: 2
# - timestamp: timestamp
# - tid: packed32
def schedThreadExitFrame(core, timestamp, pid, tid, cookie, state):
frame_type = "Sched Trace"
body = packed32(2) + timestampList(timestamp) + packed32(tid)
ret = addFrameHeader(frame_type, body, core)
return ret
# GPU Trace frame messages
# - Not implemented yet
def gpuTraceFrame():
pass
# Idle frame messages
# Enter Idle
# - code: 1
# - timestamp: timestamp
# - core: packed32
def enterIdleFrame(timestamp, core):
frame_type = "Idle"
body = packed32(1) + timestampList(timestamp) + packed32(core)
ret = addFrameHeader(frame_type, body, core)
return ret
# Exit Idle
# - code: 2
# - timestamp: timestamp
# - core: packed32
def exitIdleFrame(timestamp, core):
frame_type = "Idle"
body = packed32(2) + timestampList(timestamp) + packed32(core)
ret = addFrameHeader(frame_type, body, core)
return ret
####################################################################
def parseProcessInfo(task_file):
print "\n==============================="
print "Parsing Task file..."
print task_file
print "===============================\n"
global start_tick, end_tick, num_cpus
global process_dict, thread_dict, process_list
global event_list, unified_event_list
global idle_uid, kernel_uid
event_list = []
unified_event_list = []
for cpu in range(num_cpus):
event_list.append([])
uid = 1 # uid 0 is reserved for idle
# Dummy Tasks for frame buffers and system diagrams
process = Task(uid, 9999, 9999, "framebuffer", True, 0)
process_list.append(process)
uid += 1
thread = Task(uid, 9999, 9999, "framebuffer", False, 0)
process.children.append(thread)
uid += 1
process = Task(uid, 9998, 9998, "System", True, 0)
process_list.append(process)
# if we don't find the real kernel, use this to keep things going
kernel_uid = uid
uid += 1
thread = Task(uid, 9998, 9998, "System", False, 0)
process.children.append(thread)
uid += 1
ext = os.path.splitext(task_file)[1]
try:
if ext == ".gz":
process_file = gzip.open(task_file, 'rb')
else:
process_file = open(task_file, 'rb')
except:
print "ERROR opening task file:", task_file
print "Make sure context switch task dumping is enabled in gem5."
sys.exit(1)
process_re = re.compile("tick=(\d+)\s+(\d+)\s+cpu_id=(\d+)\s+" +
"next_pid=([-\d]+)\s+next_tgid=([-\d]+)\s+next_task=(.*)")
task_name_failure_warned = False
for line in process_file:
match = re.match(process_re, line)
if match:
tick = int(match.group(1))
if (start_tick < 0):
start_tick = tick
cpu_id = int(match.group(3))
pid = int(match.group(4))
tgid = int(match.group(5))
task_name = match.group(6)
if not task_name_failure_warned:
if task_name == "FailureIn_curTaskName":
print "-------------------------------------------------"
print "WARNING: Task name not set correctly!"
print "Process/Thread info will not be displayed correctly"
print "Perhaps forgot to apply m5struct.patch to kernel?"
print "-------------------------------------------------"
task_name_failure_warned = True
if not tgid in process_dict:
if tgid == pid:
# new task is parent as well
if args.verbose:
print "new process", uid, pid, tgid, task_name
if tgid == 0:
# new process is the "idle" task
process = Task(uid, pid, tgid, "idle", True, tick)
idle_uid = 0
else:
process = Task(uid, pid, tgid, task_name, True, tick)
else:
if tgid == 0:
process = Task(uid, tgid, tgid, "idle", True, tick)
idle_uid = 0
else:
# parent process name not known yet
process = Task(uid, tgid, tgid, "_Unknown_", True, tick)
if tgid == -1: # kernel
kernel_uid = 0
uid += 1
process_dict[tgid] = process
process_list.append(process)
else:
if tgid == pid:
if process_dict[tgid].task_name == "_Unknown_":
if args.verbose:
print "new process", \
process_dict[tgid].uid, pid, tgid, task_name
process_dict[tgid].task_name = task_name
if process_dict[tgid].task_name != task_name and tgid != 0:
process_dict[tgid].task_name = task_name
if not pid in thread_dict:
if args.verbose:
print "new thread", \
uid, process_dict[tgid].uid, pid, tgid, task_name
thread = Task(uid, pid, tgid, task_name, False, tick)
uid += 1
thread_dict[pid] = thread
process_dict[tgid].children.append(thread)
else:
if thread_dict[pid].task_name != task_name:
thread_dict[pid].task_name = task_name
if args.verbose:
print tick, uid, cpu_id, pid, tgid, task_name
task = thread_dict[pid]
event = Event(tick, task)
event_list[cpu_id].append(event)
unified_event_list.append(event)
if len(unified_event_list) == num_events:
print "Truncating at", num_events, "events!"
break
print "Found %d events." % len(unified_event_list)
for process in process_list:
if process.pid > 9990: # fix up framebuffer ticks
process.tick = start_tick
print process.uid, process.pid, process.tgid, \
process.task_name, str(process.tick)
for thread in process.children:
if thread.pid > 9990:
thread.tick = start_tick
print "\t", thread.uid, thread.pid, thread.tgid, \
thread.task_name, str(thread.tick)
end_tick = tick
print "Start tick:", start_tick
print "End tick: ", end_tick
print ""
return
def initOutput(output_path):
if not os.path.exists(output_path):
os.mkdir(output_path)
def ticksToNs(tick):
if ticks_in_ns < 0:
print "ticks_in_ns not set properly!"
sys.exit(1)
return tick / ticks_in_ns
def writeXmlFile(xml, filename):
f = open(filename, "w")
txt = ET.tostring(xml)
f.write(minidom.parseString(txt).toprettyxml())
f.close()
# StatsEntry that contains individual statistics
class StatsEntry(object):
def __init__(self, name, group, group_index, per_cpu, per_switchcpu, key):
# Full name of statistics
self.name = name
# Streamline group name that statistic will belong to
self.group = group
# Index of statistics within group (used to change colors within groups)
self.group_index = group_index
# Shorter name with "system" stripped off
# and symbols converted to alphanumerics
self.short_name = re.sub("system\.", "", name)
self.short_name = re.sub(":", "_", name)
# Regex for this stat (string version used to construct union regex)
self.regex_string = "^" + name + "\s+([\d\.]+)"
self.regex = re.compile("^" + name + "\s+([\d\.e\-]+)\s+# (.*)$", re.M)
self.description = ""
# Whether this stat is use per CPU or not
self.per_cpu = per_cpu
self.per_switchcpu = per_switchcpu
# Key used in .apc protocol (as described in captured.xml)
self.key = key
# List of values of stat per timestamp
self.values = []
# Whether this stat has been found for the current timestamp
self.found = False
# Whether this stat has been found at least once
# (to suppress too many warnings)
self.not_found_at_least_once = False
# Field used to hold ElementTree subelement for this stat
self.ET_element = None
# Create per-CPU stat name and regex, etc.
if self.per_cpu:
self.per_cpu_regex_string = []
self.per_cpu_regex = []
self.per_cpu_name = []
self.per_cpu_found = []
for i in range(num_cpus):
# Resuming from checkpoints results in using "switch_cpus"
if per_switchcpu:
per_cpu_name = "system.switch_cpus"
else:
per_cpu_name = "system.cpu"
# No CPU number appends if num_cpus == 1
if num_cpus > 1:
per_cpu_name += str(i)
per_cpu_name += "." + self.name
self.per_cpu_name.append(per_cpu_name)
print "\t", per_cpu_name
self.per_cpu_regex_string.\
append("^" + per_cpu_name + "\s+[\d\.]+")
self.per_cpu_regex.append(re.compile("^" + per_cpu_name + \
"\s+([\d\.e\-]+)\s+# (.*)$", re.M))
self.values.append([])
self.per_cpu_found.append(False)
def append_value(self, val, per_cpu_index = None):
if self.per_cpu:
self.values[per_cpu_index].append(str(val))
else:
self.values.append(str(val))
# Global stats object that contains the list of stats entries
# and other utility functions
class Stats(object):
def __init__(self):
self.stats_list = []
self.tick_list = []
self.next_key = 1
def register(self, name, group, group_index, per_cpu, per_switchcpu):
print "registering stat:", name, "group:", group, group_index
self.stats_list.append(StatsEntry(name, group, group_index, per_cpu, \
per_switchcpu, self.next_key))
self.next_key += 1
# Union of all stats to accelerate parsing speed
def createStatsRegex(self):
regex_strings = [];
print "\nnum entries in stats_list", len(self.stats_list)
for entry in self.stats_list:
if entry.per_cpu:
for i in range(num_cpus):
regex_strings.append(entry.per_cpu_regex_string[i])
else:
regex_strings.append(entry.regex_string)
self.regex = re.compile('|'.join(regex_strings))
def registerStats(config_file):
print "==============================="
print "Parsing stats config.ini file..."
print config_file
print "==============================="
config = ConfigParser()
if not config.read(config_file):
print "ERROR: config file '", config_file, "' not found!"
sys.exit(1)
print "\nRegistering Stats..."
stats = Stats()
per_cpu_stat_groups = config.options('PER_CPU_STATS')
for group in per_cpu_stat_groups:
i = 0
per_cpu_stats_list = config.get('PER_CPU_STATS', group).split('\n')
for item in per_cpu_stats_list:
if item:
stats.register(item, group, i, True, False)
i += 1
per_cpu_stat_groups = config.options('PER_SWITCHCPU_STATS')
for group in per_cpu_stat_groups:
i = 0
per_cpu_stats_list = \
config.get('PER_SWITCHCPU_STATS', group).split('\n')
for item in per_cpu_stats_list:
if item:
stats.register(item, group, i, True, True)
i += 1
per_l2_stat_groups = config.options('PER_L2_STATS')
for group in per_l2_stat_groups:
i = 0
per_l2_stats_list = config.get('PER_L2_STATS', group).split('\n')
for item in per_l2_stats_list:
if item:
for l2 in range(num_l2):
name = item
prefix = "system.l2"
if num_l2 > 1:
prefix += str(l2)
prefix += "."
name = prefix + name
stats.register(name, group, i, False, False)
i += 1
other_stat_groups = config.options('OTHER_STATS')
for group in other_stat_groups:
i = 0
other_stats_list = config.get('OTHER_STATS', group).split('\n')
for item in other_stats_list:
if item:
stats.register(item, group, i, False, False)
i += 1
stats.createStatsRegex()
return stats
# Parse and read in gem5 stats file
# Streamline counters are organized per CPU
def readGem5Stats(stats, gem5_stats_file):
print "\n==============================="
print "Parsing gem5 stats file..."
print gem5_stats_file
print "===============================\n"
ext = os.path.splitext(gem5_stats_file)[1]
window_start_regex = \
re.compile("^---------- Begin Simulation Statistics ----------")
window_end_regex = \
re.compile("^---------- End Simulation Statistics ----------")
final_tick_regex = re.compile("^final_tick\s+(\d+)")
global ticks_in_ns
sim_freq_regex = re.compile("^sim_freq\s+(\d+)")
sim_freq = -1
try:
if ext == ".gz":
f = gzip.open(gem5_stats_file, "r")
else:
f = open(gem5_stats_file, "r")
except:
print "ERROR opening stats file", gem5_stats_file, "!"
sys.exit(1)
stats_not_found_list = stats.stats_list[:]
window_num = 0
while (True):
error = False
try:
line = f.readline()
except IOError:
print ""
print "WARNING: IO error in stats file"
print "(gzip stream not closed properly?)...continuing for now"
error = True
if not line:
break
# Find out how many gem5 ticks in 1ns
if sim_freq < 0:
m = sim_freq_regex.match(line)
if m:
sim_freq = int(m.group(1)) # ticks in 1 sec
ticks_in_ns = int(sim_freq / 1e9)
print "Simulation frequency found! 1 tick == %e sec\n" \
% (1.0 / sim_freq)
# Final tick in gem5 stats: current absolute timestamp
m = final_tick_regex.match(line)
if m:
tick = int(m.group(1))
if tick > end_tick:
break
stats.tick_list.append(tick)
if (window_end_regex.match(line) or error):
if args.verbose:
print "new window"
for stat in stats.stats_list:
if stat.per_cpu:
for i in range(num_cpus):
if not stat.per_cpu_found[i]:
if not stat.not_found_at_least_once:
print "WARNING: stat not found in window #", \
window_num, ":", stat.per_cpu_name[i]
print "suppressing further warnings for " + \
"this stat"
stat.not_found_at_least_once = True
stat.values[i].append(str(0))
stat.per_cpu_found[i] = False
else:
if not stat.found:
if not stat.not_found_at_least_once:
print "WARNING: stat not found in window #", \
window_num, ":", stat.name
print "suppressing further warnings for this stat"
stat.not_found_at_least_once = True
stat.values.append(str(0))
stat.found = False
stats_not_found_list = stats.stats_list[:]
window_num += 1
if error:
break
# Do a single regex of the union of all stats first for speed
if stats.regex.match(line):
# Then loop through only the stats we haven't seen in this window
for stat in stats_not_found_list[:]:
if stat.per_cpu:
for i in range(num_cpus):
m = stat.per_cpu_regex[i].match(line)
if m:
if stat.name == "ipc":
value = str(int(float(m.group(1)) * 1000))
else:
value = str(int(float(m.group(1))))
if args.verbose:
print stat.per_cpu_name[i], value
stat.values[i].append(value)
stat.per_cpu_found[i] = True
all_found = True
for j in range(num_cpus):
if not stat.per_cpu_found[j]:
all_found = False
if all_found:
stats_not_found_list.remove(stat)
if stat.description == "":
stat.description = m.group(2)
else:
m = stat.regex.match(line)
if m:
value = str(int(float(m.group(1))))
if args.verbose:
print stat.name, value
stat.values.append(value)
stat.found = True
stats_not_found_list.remove(stat)
if stat.description == "":
stat.description = m.group(2)
f.close()
# Create session.xml file in .apc folder
def doSessionXML(output_path):
session_file = output_path + "/session.xml"
xml = ET.Element("session")
xml.set("version", "1")
xml.set("call_stack_unwinding", "no")
xml.set("parse_debug_info", "no")
xml.set("high_resolution", "yes")
xml.set("buffer_mode", "streaming")
xml.set("sample_rate", "low")
# Setting duration to zero for now. Doesn't affect visualization.
xml.set("duration", "0")
xml.set("target_host", "")
xml.set("target_port", "8080")
writeXmlFile(xml, session_file)
# Create captured.xml file in .apc folder
def doCapturedXML(output_path, stats):
captured_file = output_path + "/captured.xml"
xml = ET.Element("captured")
xml.set("version", "1")
xml.set("protocol", "12")
target = ET.SubElement(xml, "target")
target.set("name", "gem5")
target.set("sample_rate", "1000")
target.set("cores", str(num_cpus))
counters = ET.SubElement(xml, "counters")
for stat in stats.stats_list:
s = ET.SubElement(counters, "counter")
stat_name = re.sub("\.", "_", stat.short_name)
s.set("title", stat.group)
s.set("name", stat_name)
s.set("color", "0x00000000")
s.set("key", "0x%08x" % stat.key)
s.set("type", stat_name)
s.set("event", "0x00000000")
if stat.per_cpu:
s.set("per_cpu", "yes")
else:
s.set("per_cpu", "no")
s.set("display", "")
s.set("units", "")
s.set("average_selection", "no")
s.set("description", stat.description)
writeXmlFile(xml, captured_file)
# Writes out Streamline cookies (unique IDs per process/thread)
def writeCookiesThreads(blob):
thread_list = []
for process in process_list:
if process.uid > 0:
print "cookie", process.task_name, process.uid
writeBinary(blob, cookieNameFrame(process.uid, process.task_name))
# pid and tgid need to be positive values -- no longer true?
for thread in process.children:
thread_list.append(thread)
# Threads need to be sorted in timestamp order
thread_list.sort(key = lambda x: x.tick)
for thread in thread_list:
print "thread", thread.task_name, (ticksToNs(thread.tick)),\
thread.tgid, thread.pid
writeBinary(blob, threadNameFrame(ticksToNs(thread.tick),\
thread.pid, thread.task_name))
# Writes context switch info as Streamline scheduling events
def writeSchedEvents(blob):
for cpu in range(num_cpus):
for event in event_list[cpu]:
timestamp = ticksToNs(event.tick)
pid = event.task.tgid
tid = event.task.pid
if process_dict.has_key(event.task.tgid):
cookie = process_dict[event.task.tgid].uid
else:
cookie = 0
# State:
# 0: waiting on other event besides I/O
# 1: Contention/pre-emption
# 2: Waiting on I/O
# 3: Waiting on mutex
# Hardcoding to 0 for now. Other states not implemented yet.
state = 0
if args.verbose:
print cpu, timestamp, pid, tid, cookie
writeBinary(blob,\
schedSwitchFrame(cpu, timestamp, pid, tid, cookie, state))
# Writes selected gem5 statistics as Streamline counters
def writeCounters(blob, stats):
timestamp_list = []
for tick in stats.tick_list:
if tick > end_tick:
break
timestamp_list.append(ticksToNs(tick))
for stat in stats.stats_list:
if stat.per_cpu:
stat_length = len(stat.values[0])
else:
stat_length = len(stat.values)
for n in range(len(timestamp_list)):
for stat in stats.stats_list:
if stat.per_cpu:
for i in range(num_cpus):
writeBinary(blob, counterFrame(timestamp_list[n], i, \
stat.key, int(float(stat.values[i][n]))))
else:
writeBinary(blob, counterFrame(timestamp_list[n], 0, \
stat.key, int(float(stat.values[n]))))
# Streamline can display LCD frame buffer dumps (gzipped bmp)
# This function converts the frame buffer dumps to the Streamline format
def writeVisualAnnotations(blob, input_path, output_path):
frame_path = input_path + "/frames_system.vncserver"
if not os.path.exists(frame_path):
return
frame_count = 0
file_list = os.listdir(frame_path)
file_list.sort()
re_fb = re.compile("fb\.(\d+)\.(\d+)\.bmp.gz")
# Use first non-negative pid to tag visual annotations
annotate_pid = -1
for e in unified_event_list:
pid = e.task.pid
if pid >= 0:
annotate_pid = pid
break
for fn in file_list:
m = re_fb.match(fn)
if m:
seq = m.group(1)
tick = int(m.group(2))
if tick > end_tick:
break
frame_count += 1
userspace_body = []
userspace_body += packed32(0x1C) # escape code
userspace_body += packed32(0x04) # visual code
text_annotation = "image_" + str(ticksToNs(tick)) + ".bmp.gz"
userspace_body += int16(len(text_annotation))
userspace_body += utf8StringList(text_annotation)
if gzipped_bmp_supported:
# copy gzipped bmp directly
bytes_read = open(frame_path + "/" + fn, "rb").read()
else:
# copy uncompressed bmp
bytes_read = gzip.open(frame_path + "/" + fn, "rb").read()
userspace_body += int32(len(bytes_read))
userspace_body += bytes_read
writeBinary(blob, annotateFrame(0, annotate_pid, ticksToNs(tick), \
len(userspace_body), userspace_body))
print "\nfound", frame_count, "frames for visual annotation.\n"
def createApcProject(input_path, output_path, stats):
initOutput(output_path)
blob = open(output_path + "/0000000000", "wb")
# Summary frame takes current system time and system uptime.
# Filling in with random values for now.
writeBinary(blob, summaryFrame(1234, 5678))
writeCookiesThreads(blob)
print "writing Events"
writeSchedEvents(blob)
print "writing Counters"
writeCounters(blob, stats)
print "writing Visual Annotations"
writeVisualAnnotations(blob, input_path, output_path)
doSessionXML(output_path)
doCapturedXML(output_path, stats)
blob.close()
#######################
# Main Routine
input_path = args.input_path
output_path = args.output_path
####
# Make sure input path exists
####
if not os.path.exists(input_path):
print "ERROR: Input path %s does not exist!" % input_path
sys.exit(1)
####
# Parse gem5 configuration file to find # of CPUs and L2s
####
(num_cpus, num_l2) = parseConfig(input_path + "/config.ini")
####
# Parse task file to find process/thread info
####
parseProcessInfo(input_path + "/system.tasks.txt")
####
# Parse stat config file and register stats
####
stat_config_file = args.stat_config_file
stats = registerStats(stat_config_file)
####
# Parse gem5 stats
####
# Check if both stats.txt and stats.txt.gz exist and warn if both exist
if os.path.exists(input_path + "/stats.txt") and \
os.path.exists(input_path + "/stats.txt.gz"):
print "WARNING: Both stats.txt.gz and stats.txt exist. \
Using stats.txt.gz by default."
gem5_stats_file = input_path + "/stats.txt.gz"
if not os.path.exists(gem5_stats_file):
gem5_stats_file = input_path + "/stats.txt"
if not os.path.exists(gem5_stats_file):
print "ERROR: stats.txt[.gz] file does not exist in %s!" % input_path
sys.exit(1)
readGem5Stats(stats, gem5_stats_file)
####
# Create Streamline .apc project folder
####
createApcProject(input_path, output_path, stats)
print "All done!"
| bsd-3-clause |
HybridF5/nova | nova/virt/libvirt/volume/remotefs.py | 24 | 13654 | # Copyright 2014 Cloudbase Solutions Srl
# 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 abc
import functools
import os
import tempfile
from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils
import six
from nova.i18n import _LE, _LW
from nova import utils
LOG = logging.getLogger(__name__)
libvirt_opts = [
cfg.StrOpt('remote_filesystem_transport',
default='ssh',
choices=('ssh', 'rsync'),
help='Use ssh or rsync transport for creating, copying, '
'removing files on the remote host.'),
]
CONF = cfg.CONF
CONF.register_opts(libvirt_opts, 'libvirt')
def mount_share(mount_path, export_path,
export_type, options=None):
"""Mount a remote export to mount_path.
:param mount_path: place where the remote export will be mounted
:param export_path: path of the export to be mounted
:export_type: remote export type (e.g. cifs, nfs, etc.)
:options: A list containing mount options
"""
utils.execute('mkdir', '-p', mount_path)
mount_cmd = ['mount', '-t', export_type]
if options is not None:
mount_cmd.extend(options)
mount_cmd.extend([export_path, mount_path])
try:
utils.execute(*mount_cmd, run_as_root=True)
except processutils.ProcessExecutionError as exc:
if 'Device or resource busy' in six.text_type(exc):
LOG.warn(_LW("%s is already mounted"), export_path)
else:
raise
def unmount_share(mount_path, export_path):
"""Unmount a remote share.
:param mount_path: remote export mount point
:param export_path: path of the remote export to be unmounted
"""
try:
utils.execute('umount', mount_path, run_as_root=True,
attempts=3, delay_on_retry=True)
except processutils.ProcessExecutionError as exc:
if 'target is busy' in six.text_type(exc):
LOG.debug("The share %s is still in use.", export_path)
else:
LOG.exception(_LE("Couldn't unmount the share %s"),
export_path)
class RemoteFilesystem(object):
"""Represents actions that can be taken on a remote host's filesystem."""
def __init__(self):
transport = CONF.libvirt.remote_filesystem_transport
cls_name = '.'.join([__name__, transport.capitalize()])
cls_name += 'Driver'
self.driver = importutils.import_object(cls_name)
def create_file(self, host, dst_path, on_execute=None,
on_completion=None):
LOG.debug("Creating file %s on remote host %s", dst_path, host)
self.driver.create_file(host, dst_path, on_execute=on_execute,
on_completion=on_completion)
def remove_file(self, host, dst_path, on_execute=None,
on_completion=None):
LOG.debug("Removing file %s on remote host %s", dst_path, host)
self.driver.remove_file(host, dst_path, on_execute=on_execute,
on_completion=on_completion)
def create_dir(self, host, dst_path, on_execute=None,
on_completion=None):
LOG.debug("Creating directory %s on remote host %s", dst_path, host)
self.driver.create_dir(host, dst_path, on_execute=on_execute,
on_completion=on_completion)
def remove_dir(self, host, dst_path, on_execute=None,
on_completion=None):
LOG.debug("Removing directory %s on remote host %s", dst_path, host)
self.driver.remove_dir(host, dst_path, on_execute=on_execute,
on_completion=on_completion)
def copy_file(self, src, dst, on_execute=None,
on_completion=None, compression=True):
LOG.debug("Copying file %s to %s", src, dst)
self.driver.copy_file(src, dst, on_execute=on_execute,
on_completion=on_completion,
compression=compression)
@six.add_metaclass(abc.ABCMeta)
class RemoteFilesystemDriver(object):
@abc.abstractmethod
def create_file(self, host, dst_path, on_execute, on_completion):
"""Create file on the remote system.
:param host: Remote host
:param dst_path: Destination path
:param on_execute: Callback method to store pid of process in cache
:param on_completion: Callback method to remove pid of process from
cache
"""
@abc.abstractmethod
def remove_file(self, host, dst_path, on_execute, on_completion):
"""Removes a file on a remote host.
:param host: Remote host
:param dst_path: Destination path
:param on_execute: Callback method to store pid of process in cache
:param on_completion: Callback method to remove pid of process from
cache
"""
@abc.abstractmethod
def create_dir(self, host, dst_path, on_execute, on_completion):
"""Create directory on the remote system.
:param host: Remote host
:param dst_path: Destination path
:param on_execute: Callback method to store pid of process in cache
:param on_completion: Callback method to remove pid of process from
cache
"""
@abc.abstractmethod
def remove_dir(self, host, dst_path, on_execute, on_completion):
"""Removes a directory on a remote host.
:param host: Remote host
:param dst_path: Destination path
:param on_execute: Callback method to store pid of process in cache
:param on_completion: Callback method to remove pid of process from
cache
"""
@abc.abstractmethod
def copy_file(self, src, dst, on_execute, on_completion):
"""Copy file to/from remote host.
Remote address must be specified in format:
REM_HOST_IP_ADDRESS:REM_HOST_PATH
For example:
192.168.1.10:/home/file
:param src: Source address
:param dst: Destination path
:param on_execute: Callback method to store pid of process in cache
:param on_completion: Callback method to remove pid of process from
"""
class SshDriver(RemoteFilesystemDriver):
def create_file(self, host, dst_path, on_execute, on_completion):
utils.execute('ssh', host, 'touch', dst_path,
on_execute=on_execute, on_completion=on_completion)
def remove_file(self, host, dst, on_execute, on_completion):
utils.execute('ssh', host, 'rm', dst,
on_execute=on_execute, on_completion=on_completion)
def create_dir(self, host, dst_path, on_execute, on_completion):
utils.execute('ssh', host, 'mkdir', '-p', dst_path,
on_execute=on_execute, on_completion=on_completion)
def remove_dir(self, host, dst, on_execute, on_completion):
utils.execute('ssh', host, 'rm', '-rf', dst,
on_execute=on_execute, on_completion=on_completion)
def copy_file(self, src, dst, on_execute, on_completion, compression):
utils.execute('scp', src, dst,
on_execute=on_execute, on_completion=on_completion)
def create_tmp_dir(function):
"""Creates temporary directory for rsync purposes.
Removes created directory in the end.
"""
@functools.wraps(function)
def decorated_function(*args, **kwargs):
# Create directory
tmp_dir_path = tempfile.mkdtemp()
kwargs['tmp_dir_path'] = tmp_dir_path
try:
return function(*args, **kwargs)
finally:
# Remove directory
utils.execute('rm', '-rf', tmp_dir_path)
return decorated_function
class RsyncDriver(RemoteFilesystemDriver):
@create_tmp_dir
def create_file(self, host, dst_path, on_execute, on_completion, **kwargs):
dir_path = os.path.dirname(os.path.normpath(dst_path))
# Create target dir inside temporary directory
local_tmp_dir = os.path.join(kwargs['tmp_dir_path'],
dir_path.strip(os.path.sep))
utils.execute('mkdir', '-p', local_tmp_dir,
on_execute=on_execute, on_completion=on_completion)
# Create file in directory
file_name = os.path.basename(os.path.normpath(dst_path))
local_tmp_file = os.path.join(local_tmp_dir, file_name)
utils.execute('touch', local_tmp_file,
on_execute=on_execute, on_completion=on_completion)
RsyncDriver._synchronize_object(kwargs['tmp_dir_path'],
host, dst_path,
on_execute=on_execute,
on_completion=on_completion)
@create_tmp_dir
def remove_file(self, host, dst, on_execute, on_completion, **kwargs):
# Delete file
RsyncDriver._remove_object(kwargs['tmp_dir_path'], host, dst,
on_execute=on_execute,
on_completion=on_completion)
@create_tmp_dir
def create_dir(self, host, dst_path, on_execute, on_completion, **kwargs):
dir_path = os.path.normpath(dst_path)
# Create target dir inside temporary directory
local_tmp_dir = os.path.join(kwargs['tmp_dir_path'],
dir_path.strip(os.path.sep))
utils.execute('mkdir', '-p', local_tmp_dir,
on_execute=on_execute, on_completion=on_completion)
RsyncDriver._synchronize_object(kwargs['tmp_dir_path'],
host, dst_path,
on_execute=on_execute,
on_completion=on_completion)
@create_tmp_dir
def remove_dir(self, host, dst, on_execute, on_completion, **kwargs):
# Remove remote directory's content
utils.execute('rsync', '--archive', '--delete-excluded',
kwargs['tmp_dir_path'] + os.path.sep,
'%s:%s' % (host, dst),
on_execute=on_execute, on_completion=on_completion)
# Delete empty directory
RsyncDriver._remove_object(kwargs['tmp_dir_path'], host, dst,
on_execute=on_execute,
on_completion=on_completion)
@staticmethod
def _remove_object(src, host, dst, on_execute, on_completion):
"""Removes a file or empty directory on a remote host.
:param src: Empty directory used for rsync purposes
:param host: Remote host
:param dst: Destination path
:param on_execute: Callback method to store pid of process in cache
:param on_completion: Callback method to remove pid of process from
cache
"""
utils.execute('rsync', '--archive', '--delete',
'--include', os.path.basename(os.path.normpath(dst)),
'--exclude', '*',
os.path.normpath(src) + os.path.sep,
'%s:%s' % (host, os.path.dirname(os.path.normpath(dst))),
on_execute=on_execute, on_completion=on_completion)
@staticmethod
def _synchronize_object(src, host, dst, on_execute, on_completion):
"""Creates a file or empty directory on a remote host.
:param src: Empty directory used for rsync purposes
:param host: Remote host
:param dst: Destination path
:param on_execute: Callback method to store pid of process in cache
:param on_completion: Callback method to remove pid of process from
cache
"""
# For creating path on the remote host rsync --relative path must
# be used. With a modern rsync on the sending side (beginning with
# 2.6.7), you can insert a dot and a slash into the source path,
# like this:
# rsync -avR /foo/./bar/baz.c remote:/tmp/
# That would create /tmp/bar/baz.c on the remote machine.
# (Note that the dot must be followed by a slash, so "/foo/."
# would not be abbreviated.)
relative_tmp_file_path = os.path.join(
src, './',
os.path.normpath(dst).strip(os.path.sep))
# Do relative rsync local directory with remote root directory
utils.execute('rsync', '--archive', '--relative', '--no-implied-dirs',
relative_tmp_file_path, '%s:%s' % (host, os.path.sep),
on_execute=on_execute, on_completion=on_completion)
def copy_file(self, src, dst, on_execute, on_completion, compression):
args = ['rsync', '--sparse', src, dst]
if compression:
args.append('--compress')
utils.execute(*args,
on_execute=on_execute, on_completion=on_completion)
| apache-2.0 |
dsedivec/ansible-plugins | action_plugins/load_gpg_vars.py | 1 | 2950 | # Copyright 2013 Dale Sedivec
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import subprocess
import collections
import itertools
import yaml
from ansible import utils, errors
from ansible.runner import return_data
class ActionModule (object):
BYPASS_HOST_LOOP = True
NEEDS_TMPPATH = False
def __init__(self, runner):
self.runner = runner
def run(self, conn, tmp, module_name, module_args, inject,
complex_args=None, **kwargs):
args = {}
if complex_args:
args.update(complex_args)
args.update(utils.parse_kv(module_args))
path = args.get("path")
if not path:
raise errors.AnsibleError('"path" is a required argument')
gpg_path = args.get("gpg", "gpg")
gpg = subprocess.Popen([gpg_path, "-q", "-d", path],
stdout=subprocess.PIPE)
stdout, _stderr = gpg.communicate()
if gpg.returncode != 0:
raise errors.AnsibleError("error calling gpg")
try:
gpg_vars = utils.parse_yaml(stdout)
except yaml.YAMLError, ex:
utils.process_yaml_error(ex, stdout, path)
if not callable(getattr(gpg_vars, "iteritems", None)):
raise errors.AnsibleError(
"GPG vars file must be a YAML associative array, not a %r" %
(gpg_vars.__class__.__name__,))
host_vars = collections.defaultdict(dict, gpg_vars.pop("hosts", ()))
# Here on is heavily cribbed from group_by.
runner = self.runner
inventory = runner.inventory
changed = False
for host_name in runner.host_set:
host = inventory.get_host(host_name)
all_vars = itertools.chain(gpg_vars.iteritems(),
host_vars[host_name].iteritems())
for key, value in all_vars:
if host.vars.get(key) != value:
host.set_variable(key, value)
changed = True
# Totally cribbed from group_by. Looks like this is
# necessary to invalidate the inventory's cached variables
# for the host.
del inventory._vars_per_host[host_name]
return return_data.ReturnData(conn=conn, comm_ok=True,
result={"changed": changed})
| gpl-3.0 |
hryamzik/ansible | lib/ansible/inventory/group.py | 57 | 7324 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.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/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError
from itertools import chain
class Group:
''' a group of ansible hosts '''
# __slots__ = [ 'name', 'hosts', 'vars', 'child_groups', 'parent_groups', 'depth', '_hosts_cache' ]
def __init__(self, name=None):
self.depth = 0
self.name = name
self.hosts = []
self._hosts = None
self.vars = {}
self.child_groups = []
self.parent_groups = []
self._hosts_cache = None
self.priority = 1
def __repr__(self):
return self.get_name()
def __str__(self):
return self.get_name()
def __getstate__(self):
return self.serialize()
def __setstate__(self, data):
return self.deserialize(data)
def serialize(self):
parent_groups = []
for parent in self.parent_groups:
parent_groups.append(parent.serialize())
self._hosts = None
result = dict(
name=self.name,
vars=self.vars.copy(),
parent_groups=parent_groups,
depth=self.depth,
hosts=self.hosts,
)
return result
def deserialize(self, data):
self.__init__()
self.name = data.get('name')
self.vars = data.get('vars', dict())
self.depth = data.get('depth', 0)
self.hosts = data.get('hosts', [])
self._hosts = None
parent_groups = data.get('parent_groups', [])
for parent_data in parent_groups:
g = Group()
g.deserialize(parent_data)
self.parent_groups.append(g)
def _walk_relationship(self, rel):
'''
Given `rel` that is an iterable property of Group,
consitituting a directed acyclic graph among all groups,
Returns a set of all groups in full tree
A B C
| / | /
| / | /
D -> E
| / vertical connections
| / are directed upward
F
Called on F, returns set of (A, B, C, D, E)
'''
seen = set([])
unprocessed = set(getattr(self, rel))
while unprocessed:
seen.update(unprocessed)
unprocessed = set(chain.from_iterable(
getattr(g, rel) for g in unprocessed
))
unprocessed.difference_update(seen)
return seen
def get_ancestors(self):
return self._walk_relationship('parent_groups')
def get_descendants(self):
return self._walk_relationship('child_groups')
@property
def host_names(self):
if self._hosts is None:
self._hosts = set(self.hosts)
return self._hosts
def get_name(self):
return self.name
def add_child_group(self, group):
if self == group:
raise Exception("can't add group to itself")
# don't add if it's already there
if group not in self.child_groups:
# prepare list of group's new ancestors this edge creates
start_ancestors = group.get_ancestors()
new_ancestors = self.get_ancestors()
if group in new_ancestors:
raise AnsibleError(
"Adding group '%s' as child to '%s' creates a recursive "
"dependency loop." % (group.name, self.name))
new_ancestors.add(self)
new_ancestors.difference_update(start_ancestors)
self.child_groups.append(group)
# update the depth of the child
group.depth = max([self.depth + 1, group.depth])
# update the depth of the grandchildren
group._check_children_depth()
# now add self to child's parent_groups list, but only if there
# isn't already a group with the same name
if self.name not in [g.name for g in group.parent_groups]:
group.parent_groups.append(self)
for h in group.get_hosts():
h.populate_ancestors(additions=new_ancestors)
self.clear_hosts_cache()
def _check_children_depth(self):
depth = self.depth
start_depth = self.depth # self.depth could change over loop
seen = set([])
unprocessed = set(self.child_groups)
while unprocessed:
seen.update(unprocessed)
depth += 1
to_process = unprocessed.copy()
unprocessed = set([])
for g in to_process:
if g.depth < depth:
g.depth = depth
unprocessed.update(g.child_groups)
if depth - start_depth > len(seen):
raise AnsibleError("The group named '%s' has a recursive dependency loop." % self.name)
def add_host(self, host):
if host.name not in self.host_names:
self.hosts.append(host)
self._hosts.add(host.name)
host.add_group(self)
self.clear_hosts_cache()
def remove_host(self, host):
if host.name in self.host_names:
self.hosts.remove(host)
self._hosts.remove(host.name)
host.remove_group(self)
self.clear_hosts_cache()
def set_variable(self, key, value):
if key == 'ansible_group_priority':
self.set_priority(int(value))
else:
self.vars[key] = value
def clear_hosts_cache(self):
self._hosts_cache = None
for g in self.get_ancestors():
g._hosts_cache = None
def get_hosts(self):
if self._hosts_cache is None:
self._hosts_cache = self._get_hosts()
return self._hosts_cache
def _get_hosts(self):
hosts = []
seen = {}
for kid in self.get_descendants():
kid_hosts = kid.hosts
for kk in kid_hosts:
if kk not in seen:
seen[kk] = 1
if self.name == 'all' and kk.implicit:
continue
hosts.append(kk)
for mine in self.hosts:
if mine not in seen:
seen[mine] = 1
if self.name == 'all' and mine.implicit:
continue
hosts.append(mine)
return hosts
def get_vars(self):
return self.vars.copy()
def set_priority(self, priority):
try:
self.priority = int(priority)
except TypeError:
# FIXME: warn about invalid priority
pass
| gpl-3.0 |
DirtyUnicorns/android_external_chromium-org | tools/perf/benchmarks/html5gaming.py | 26 | 1656 | # Copyright 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.
"""Impact HTML5 Gaming benchmark.
Tests one very specific use case: smooth running games rendered with the
<canvas> element. The score for the HTML5-Benchmark takes the total time the
browser spent rendering frames (formula is 1000000/(sqrt(totalTime) + lagTime *
0.1)). The benchmark automatically runs at a reasonable screen size. Final
score is a indicator for the browser's ability to smoothly run HTML5 games."""
import os
from telemetry import test
from telemetry.page import page_measurement
from telemetry.page import page_set
class _HTML5GamingMeasurement(page_measurement.PageMeasurement):
def MeasurePage(self, _, tab, results):
tab.ExecuteJavaScript('benchmark();')
# Default value of score element is 87485, its value is updated with actual
# score when test finish.
tab.WaitForJavaScriptExpression(
'document.getElementById("score").innerHTML != "87485"', 200)
result = int(tab.EvaluateJavaScript(
'document.getElementById("score").innerHTML'))
results.Add('Score', 'score', result)
class HTML5Gaming(test.Test):
"""Imapct HTML5 smooth running games benchmark suite."""
test = _HTML5GamingMeasurement
def CreatePageSet(self, options):
return page_set.PageSet.FromDict({
'archive_data_file': '../page_sets/data/html5gaming.json',
'make_javascript_deterministic': False,
'pages': [
{ 'url':
'http://html5-benchmark.com/'}
]
}, os.path.abspath(__file__))
| bsd-3-clause |
philippp/wave-todo | todo/waveapi/util.py | 1 | 6445 | #!/usr/bin/python2.4
#
# Copyright 2009 Google Inc. All Rights Reserved.
"""Utility library containing various helpers used by the API.
Contains miscellaneous functions used internally by the API.
"""
__author__ = 'davidbyttow@google.com (David Byttow)'
import document
CUSTOM_SERIALIZE_METHOD_NAME = 'Serialize'
def IsListOrDict(inst):
"""Returns whether or not this is a list, tuple, set or dict ."""
return hasattr(inst, '__iter__')
def IsDict(inst):
"""Returns whether or not the specified instance is a dict."""
return hasattr(inst, 'iteritems')
def IsInstance(obj):
"""Returns whether or not the specified instance is a user-defined type."""
# NOTE(davidbyttow): This seems like a reasonably safe hack for now...
# I'm not exactly sure how to test if something is a subclass of object.
# And no, "is InstanceType" does not work here. :(
return str(type(obj)).startswith('<class ')
def CollapseJavaCollections(data):
"""Collapses the unnecessary extra data structures in the wire format.
Currently the wire format is built from marshalling of Java objects. This
introduces overhead of extra key/value pairs with respect to collections and
superfluous fields. As such, this method attempts to collapse those structures
out of the data format by collapsing the collection objects and removing
the java class fields.
This preserves the data that is passed in and only removes the collection
types.
Args:
data: Some arbitrary dict, list or primitive type.
Returns:
The same data structure with the collapsed and unnecessary objects
removed.
"""
if IsDict(data):
java_class = data.get('javaClass')
if java_class:
del data['javaClass']
if java_class == 'java.util.HashMap':
return CollapseJavaCollections(data['map'])
elif java_class == 'java.util.ArrayList':
return CollapseJavaCollections(data['list'])
for key, val in data.iteritems():
data[key] = CollapseJavaCollections(val)
elif IsListOrDict(data):
for index in range(len(data)):
data[index] = CollapseJavaCollections(data[index])
return data
return data
def ToLowerCamelCase(s):
"""Converts a string to lower camel case.
Examples:
foo => foo
foo_bar => fooBar
foo__bar => fooBar
foo_bar_baz => fooBarBaz
Args:
s: The string to convert to lower camel case.
Returns:
The lower camel cased string.
"""
out = None
return reduce(lambda a, b: a + (a and b.capitalize() or b), s.split('_'))
def DefaultKeyWriter(key_name):
"""This key writer rewrites keys as lower camel case.
Expects that the input is formed by '_' delimited words.
Args:
key_name: Name of the key to serialize.
Returns:
Key name in lower camel-cased form.
"""
return ToLowerCamelCase(key_name)
def _SerializeAttributes(obj, key_writer=DefaultKeyWriter):
"""Serializes attributes of an instance.
Iterates all attributes of an object and invokes serialize if they are
public and not callable.
Args:
obj: The instance to serialize.
key_writer: Optional function that takes a string key and optionally mutates
it before serialization. For example:
def randomize(key_name):
return key_name += str(random.random())
Returns:
The serialized object.
"""
data = {}
for attr_name in dir(obj):
if attr_name.startswith('_'):
continue
attr = getattr(obj, attr_name)
if attr is None:
continue
if callable(attr):
continue
# Looks okay, serialize it.
data[key_writer(attr_name)] = Serialize(attr)
return data
def _SerializeList(l):
"""Invokes Serialize on all of its elements.
Args:
l: The list object to serialize.
Returns:
The serialized list.
"""
data = [Serialize(v) for v in l]
return {
'javaClass': 'java.util.ArrayList',
'list': data
}
def _SerializeDict(d, key_writer=DefaultKeyWriter):
"""Invokes serialize on all of its key/value pairs.
Args:
d: The dict instance to serialize.
key_writer: Optional key writer function.
Returns:
The serialized dict.
"""
data = {}
for k, v in d.iteritems():
data[key_writer(k)] = Serialize(v)
return {
'javaClass': 'java.util.HashMap',
'map': data
}
def Serialize(obj, key_writer=DefaultKeyWriter):
"""Serializes any instance.
If this is a user-defined instance
type, it will first check for a custom Serialize() function and use that
if it exists. Otherwise, it will invoke serialize all of its public
attributes. Lists and dicts are serialized trivially.
Args:
obj: The instance to serialize.
key_writer: Optional key writer function.
Returns:
The serialized object.
"""
if IsInstance(obj):
if obj and hasattr(obj, CUSTOM_SERIALIZE_METHOD_NAME):
method = getattr(obj, CUSTOM_SERIALIZE_METHOD_NAME)
if callable(method):
return method()
return _SerializeAttributes(obj, key_writer)
elif IsDict(obj):
return _SerializeDict(obj, key_writer)
elif IsListOrDict(obj):
return _SerializeList(obj)
return obj
def ClipRange(r, clip_range):
"""Clips one range to another.
Given a range to be clipped and a clipping range, will result in a list
of 0-2 new ranges. If the range is completely inside of the clipping range
then an empty list will be returned. If it is completely outside, then
a list with only the same range will be returned.
Otherwise, other permutations may result in a single clipped range or
two ranges that were the result of a split.
Args:
r: The range to be clipped.
clip_range: The range that is clipping the other.
Returns:
A list of 0-2 ranges as a result of performing the clip.
"""
# Check if completely outside the clipping range.
if r.end <= clip_range.start or r.start >= clip_range.end:
return [r]
# Check if completely clipped.
if r.start >= clip_range.start and r.end <= clip_range.end:
return []
# Check if split.
if clip_range.start >= r.start and clip_range.end <= r.end:
splits = []
if r.start < clip_range.start:
splits.append(document.Range(r.start, clip_range.start))
if clip_range.end < r.end:
splits.append(document.Range(clip_range.end, r.end))
return splits
# Just a trim.
if clip_range.start < r.start:
return [document.Range(clip_range.end, r.end)]
return [document.Range(r.start, clip_range.start)]
| apache-2.0 |
rahul67/hue | desktop/core/ext-py/Django-1.6.10/django/views/generic/edit.py | 106 | 8642 | import warnings
from django.forms import models as model_forms
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponseRedirect
from django.utils.encoding import force_text
from django.views.generic.base import TemplateResponseMixin, ContextMixin, View
from django.views.generic.detail import (SingleObjectMixin,
SingleObjectTemplateResponseMixin, BaseDetailView)
class FormMixin(ContextMixin):
"""
A mixin that provides a way to show and handle a form in a request.
"""
initial = {}
form_class = None
success_url = None
prefix = None
def get_initial(self):
"""
Returns the initial data to use for forms on this view.
"""
return self.initial.copy()
def get_prefix(self):
"""
Returns the prefix to use for forms on this view
"""
return self.prefix
def get_form_class(self):
"""
Returns the form class to use in this view
"""
return self.form_class
def get_form(self, form_class):
"""
Returns an instance of the form to be used in this view.
"""
return form_class(**self.get_form_kwargs())
def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = {
'initial': self.get_initial(),
'prefix': self.get_prefix(),
}
if self.request.method in ('POST', 'PUT'):
kwargs.update({
'data': self.request.POST,
'files': self.request.FILES,
})
return kwargs
def get_success_url(self):
"""
Returns the supplied success URL.
"""
if self.success_url:
# Forcing possible reverse_lazy evaluation
url = force_text(self.success_url)
else:
raise ImproperlyConfigured(
"No URL to redirect to. Provide a success_url.")
return url
def form_valid(self, form):
"""
If the form is valid, redirect to the supplied URL.
"""
return HttpResponseRedirect(self.get_success_url())
def form_invalid(self, form):
"""
If the form is invalid, re-render the context data with the
data-filled form and errors.
"""
return self.render_to_response(self.get_context_data(form=form))
class ModelFormMixin(FormMixin, SingleObjectMixin):
"""
A mixin that provides a way to show and handle a modelform in a request.
"""
fields = None
def get_form_class(self):
"""
Returns the form class to use in this view.
"""
if self.form_class:
return self.form_class
else:
if self.model is not None:
# If a model has been explicitly provided, use it
model = self.model
elif hasattr(self, 'object') and self.object is not None:
# If this view is operating on a single object, use
# the class of that object
model = self.object.__class__
else:
# Try to get a queryset and extract the model class
# from that
model = self.get_queryset().model
if self.fields is None:
warnings.warn("Using ModelFormMixin (base class of %s) without "
"the 'fields' attribute is deprecated." % self.__class__.__name__,
PendingDeprecationWarning)
return model_forms.modelform_factory(model, fields=self.fields)
def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = super(ModelFormMixin, self).get_form_kwargs()
kwargs.update({'instance': self.object})
return kwargs
def get_success_url(self):
"""
Returns the supplied URL.
"""
if self.success_url:
url = self.success_url % self.object.__dict__
else:
try:
url = self.object.get_absolute_url()
except AttributeError:
raise ImproperlyConfigured(
"No URL to redirect to. Either provide a url or define"
" a get_absolute_url method on the Model.")
return url
def form_valid(self, form):
"""
If the form is valid, save the associated model.
"""
self.object = form.save()
return super(ModelFormMixin, self).form_valid(form)
class ProcessFormView(View):
"""
A mixin that renders a form on GET and processes it on POST.
"""
def get(self, request, *args, **kwargs):
"""
Handles GET requests and instantiates a blank version of the form.
"""
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
def post(self, request, *args, **kwargs):
"""
Handles POST requests, instantiating a form instance with the passed
POST variables and then checked for validity.
"""
form_class = self.get_form_class()
form = self.get_form(form_class)
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
# PUT is a valid HTTP verb for creating (with a known URL) or editing an
# object, note that browsers only support POST for now.
def put(self, *args, **kwargs):
return self.post(*args, **kwargs)
class BaseFormView(FormMixin, ProcessFormView):
"""
A base view for displaying a form
"""
class FormView(TemplateResponseMixin, BaseFormView):
"""
A view for displaying a form, and rendering a template response.
"""
class BaseCreateView(ModelFormMixin, ProcessFormView):
"""
Base view for creating an new object instance.
Using this base class requires subclassing to provide a response mixin.
"""
def get(self, request, *args, **kwargs):
self.object = None
return super(BaseCreateView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = None
return super(BaseCreateView, self).post(request, *args, **kwargs)
class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView):
"""
View for creating a new object instance,
with a response rendered by template.
"""
template_name_suffix = '_form'
class BaseUpdateView(ModelFormMixin, ProcessFormView):
"""
Base view for updating an existing object.
Using this base class requires subclassing to provide a response mixin.
"""
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super(BaseUpdateView, self).get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super(BaseUpdateView, self).post(request, *args, **kwargs)
class UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView):
"""
View for updating an object,
with a response rendered by template.
"""
template_name_suffix = '_form'
class DeletionMixin(object):
"""
A mixin providing the ability to delete objects
"""
success_url = None
def delete(self, request, *args, **kwargs):
"""
Calls the delete() method on the fetched object and then
redirects to the success URL.
"""
self.object = self.get_object()
success_url = self.get_success_url()
self.object.delete()
return HttpResponseRedirect(success_url)
# Add support for browsers which only accept GET and POST for now.
def post(self, request, *args, **kwargs):
return self.delete(request, *args, **kwargs)
def get_success_url(self):
if self.success_url:
return self.success_url % self.object.__dict__
else:
raise ImproperlyConfigured(
"No URL to redirect to. Provide a success_url.")
class BaseDeleteView(DeletionMixin, BaseDetailView):
"""
Base view for deleting an object.
Using this base class requires subclassing to provide a response mixin.
"""
class DeleteView(SingleObjectTemplateResponseMixin, BaseDeleteView):
"""
View for deleting an object retrieved with `self.get_object()`,
with a response rendered by template.
"""
template_name_suffix = '_confirm_delete'
| apache-2.0 |
av8ramit/tensorflow | tensorflow/contrib/timeseries/python/timeseries/state_space_models/structural_ensemble.py | 94 | 13419 | # Copyright 2017 The TensorFlow Authors. 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.
# ==============================================================================
"""Implements a time series model with seasonality, trends, and transients."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.timeseries.python.timeseries.state_space_models import level_trend
from tensorflow.contrib.timeseries.python.timeseries.state_space_models import periodic
from tensorflow.contrib.timeseries.python.timeseries.state_space_models import state_space_model
from tensorflow.contrib.timeseries.python.timeseries.state_space_models import varma
from tensorflow.python.ops import variable_scope
from tensorflow.python.util import nest
def _replicate_level_trend_models(multivariate_configuration,
univariate_configuration):
"""Helper function to construct a multivariate level/trend component."""
with variable_scope.variable_scope("adder"):
# Construct a level and trend model for each feature, with correlated
# transition noise.
adder_features = []
for feature in range(multivariate_configuration.num_features):
with variable_scope.variable_scope("feature{}".format(feature)):
adder_features.append(level_trend.AdderStateSpaceModel(
configuration=univariate_configuration))
adder_part = state_space_model.StateSpaceCorrelatedFeaturesEnsemble(
ensemble_members=adder_features,
configuration=multivariate_configuration)
return adder_part
class StructuralEnsemble(state_space_model.StateSpaceIndependentEnsemble):
r"""A structural state space time series model.
In the spirit of:
Scott, Steven L., and Hal R. Varian. "Predicting the present with bayesian
structural time series." International Journal of Mathematical Modelling and
Numerical Optimisation 5.1-2 (2014): 4-23.
Without the spike-and-slab prior, and with point estimates of parameters
instead of sampling.
The model includes level, trend, seasonality, and a transient moving average.
An observation at time t is drawn according to:
observation_t = level_t + seasonality_t + moving_average_t
+ observation_noise_t
level_t = level_{t-1} + trend_{t-1} + level_noise_t
trend_t = trend_{t-1} + trend_noise_t
seasonality_t = -\sum_{n=1}^{num_seasons-1} seasonality_{t-n} +
seasonality_noise_t
moving_average_t = transient_t
+ \sum_{j=1}^{moving_average_order} ma_coefs_j * transient_{t - j}
`observation_noise`, `level_noise`, `trend noise`, `seasonality_noise`, and
`transient` are (typically scalar) Gaussian random variables whose variance is
learned from data, and that variance is not time dependent in this
implementation. Level noise is optional due to its similarity with observation
noise in some cases. Seasonality is enforced by constraining a full cycle of
seasonal variables to have zero expectation, allowing seasonality to adapt
over time. The moving average coefficients `ma_coefs` are learned.
When presented with a multivariate series (more than one "feature", here
referring to endogenous features of the series), the model is replicated
across these features (one copy per feature of each periodic component, and
one level/trend model per feature), and correlations in transition noise are
learned between these replicated components (see
StateSpaceCorrelatedFeaturesEnsemble). This is in addition to the learned
correlations in observation noise between features. While this is often the
most expressive thing to do with multiple features, it does mean that the
model grows quite quickly, creating and computing with square matrices with
each dimension equal to num_features * (sum(periodicities) +
moving_average_order + 3), meaning that some operations are approximately
cubic in this value.
"""
# TODO(allenl): Implement partial model replication/sharing for multivariate
# series (to save time/memory when the series presented can be modeled as a
# smaller number of underlying series). Likely just a modification of the
# observation model so that each feature of the series is a learned linear
# combination of the replicated models.
def __init__(self,
periodicities,
moving_average_order,
autoregressive_order,
use_level_noise=True,
configuration=state_space_model.StateSpaceModelConfiguration()):
"""Initialize the Basic Structural Time Series model.
Args:
periodicities: Number of time steps for cyclic behavior. May be a list, in
which case one periodic component is created for each element.
moving_average_order: The number of moving average coefficients to use,
which also defines the number of steps after which transient
deviations revert to the mean defined by periodic and level/trend
components.
autoregressive_order: The number of steps back for autoregression.
use_level_noise: Whether to model the time series as having level
noise. See level_noise in the model description above.
configuration: A StateSpaceModelConfiguration object.
"""
component_model_configuration = configuration._replace(
use_observation_noise=False)
univariate_component_model_configuration = (
component_model_configuration._replace(
num_features=1))
adder_part = _replicate_level_trend_models(
multivariate_configuration=component_model_configuration,
univariate_configuration=univariate_component_model_configuration)
with variable_scope.variable_scope("varma"):
varma_part = varma.VARMA(
autoregressive_order=autoregressive_order,
moving_average_order=moving_average_order,
configuration=component_model_configuration)
cycle_parts = []
periodicity_list = nest.flatten(periodicities)
for cycle_number, cycle_periodicity in enumerate(periodicity_list):
# For each specified periodicity, construct models for each feature with
# correlated noise.
with variable_scope.variable_scope("cycle{}".format(cycle_number)):
cycle_features = []
for feature in range(configuration.num_features):
with variable_scope.variable_scope("feature{}".format(feature)):
cycle_features.append(periodic.CycleStateSpaceModel(
periodicity=cycle_periodicity,
configuration=univariate_component_model_configuration))
cycle_parts.append(
state_space_model.StateSpaceCorrelatedFeaturesEnsemble(
ensemble_members=cycle_features,
configuration=component_model_configuration))
super(StructuralEnsemble, self).__init__(
ensemble_members=[adder_part, varma_part] + cycle_parts,
configuration=configuration)
# TODO(allenl): Implement a multi-resolution moving average component to
# decouple model size from the length of transient deviations.
class MultiResolutionStructuralEnsemble(
state_space_model.StateSpaceIndependentEnsemble):
"""A structural ensemble modeling arbitrary periods with a fixed model size.
See periodic.ResolutionCycleModel, which allows a fixed number of latent
values to cycle at multiple/variable resolutions, for more details on the
difference between MultiResolutionStructuralEnsemble and
StructuralEnsemble. With `cycle_num_latent_values` (controlling model size)
equal to `periodicities` (controlling the time over which these values
complete a full cycle), the models are
equivalent. MultiResolutionStructuralEnsemble allows `periodicities` to vary
while the model size remains fixed. Note that high `periodicities` without a
correspondingly high `cycle_num_latent_values` means that the modeled series
must have a relatively smooth periodic component.
Multiple features are handled the same way as in StructuralEnsemble (one
replication per feature, with correlations learned between the replicated
models). This strategy produces a very flexible model, but means that series
with many features may be slow to train.
Model size (the state dimension) is:
num_features * (sum(cycle_num_latent_values)
+ max(moving_average_order + 1, autoregressive_order) + 2)
"""
def __init__(self,
cycle_num_latent_values,
moving_average_order,
autoregressive_order,
periodicities,
use_level_noise=True,
configuration=state_space_model.StateSpaceModelConfiguration()):
"""Initialize the multi-resolution structural ensemble.
Args:
cycle_num_latent_values: Controls the model size and the number of latent
values cycled between (but not the periods over which they cycle).
Reducing this parameter can save significant amounts of memory, but
the tradeoff is with resolution: cycling between a smaller number of
latent values means that only smoother functions can be modeled. For
multivariate series, may either be a scalar integer (in which case it
is applied to all periodic components) or a list with length matching
`periodicities`.
moving_average_order: The number of moving average coefficients to use,
which also defines the number of steps after which transient
deviations revert to the mean defined by periodic and level/trend
components. Adds to model size.
autoregressive_order: The number of steps back for
autoregression. Learning autoregressive coefficients typically
requires more steps and a smaller step size than other components.
periodicities: Same meaning as for StructuralEnsemble: number of steps for
cyclic behavior. Floating point and Tensor values are supported. May
be a list of values, in which case one component is created for each
periodicity. If `periodicities` is a list while
`cycle_num_latent_values` is a scalar, its value is broadcast to each
periodic component. Otherwise they should be lists of the same length,
in which case they are paired.
use_level_noise: See StructuralEnsemble.
configuration: A StateSpaceModelConfiguration object.
Raises:
ValueError: If `cycle_num_latent_values` is neither a scalar nor agrees in
size with `periodicities`.
"""
component_model_configuration = configuration._replace(
use_observation_noise=False)
univariate_component_model_configuration = (
component_model_configuration._replace(
num_features=1))
adder_part = _replicate_level_trend_models(
multivariate_configuration=component_model_configuration,
univariate_configuration=univariate_component_model_configuration)
with variable_scope.variable_scope("varma"):
varma_part = varma.VARMA(
autoregressive_order=autoregressive_order,
moving_average_order=moving_average_order,
configuration=component_model_configuration)
cycle_parts = []
if periodicities is None:
periodicities = []
periodicity_list = nest.flatten(periodicities)
latent_values_list = nest.flatten(cycle_num_latent_values)
if len(periodicity_list) != len(latent_values_list):
if len(latent_values_list) != 1:
raise ValueError(
("`cycle_num_latent_values` must either be a list with the same "
"size as `periodicity` or a scalar. Received length {} "
"`cycle_num_latent_values`, while `periodicities` has length {}.")
.format(len(latent_values_list), len(periodicity_list)))
latent_values_list *= len(periodicity_list)
for cycle_number, (cycle_periodicity, num_latent_values) in enumerate(
zip(periodicity_list, latent_values_list)):
with variable_scope.variable_scope("cycle{}".format(cycle_number)):
cycle_features = []
for feature in range(configuration.num_features):
with variable_scope.variable_scope("feature{}".format(feature)):
cycle_features.append(
periodic.ResolutionCycleModel(
num_latent_values=num_latent_values,
periodicity=cycle_periodicity,
configuration=univariate_component_model_configuration))
cycle_parts.append(
state_space_model.StateSpaceCorrelatedFeaturesEnsemble(
ensemble_members=cycle_features,
configuration=component_model_configuration))
super(MultiResolutionStructuralEnsemble, self).__init__(
ensemble_members=[adder_part, varma_part] + cycle_parts,
configuration=configuration)
| apache-2.0 |
sheepray/volatility | volatility/plugins/addrspaces/amd64.py | 45 | 9551 | # Volatility
# Copyright (C) 2013 Volatility Foundation
#
# Authors:
# Mike Auty
#
# This file is part of Volatility.
#
# Volatility 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.
#
# Volatility 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 Volatility. If not, see <http://www.gnu.org/licenses/>.
#
import volatility.plugins.addrspaces.paged as paged
import volatility.obj as obj
import struct
ptrs_page = 2048
entry_size = 8
pde_shift = 21
ptrs_per_pde = 512
page_shift = 12
ptrs_per_pae_pgd = 512
ptrs_per_pae_pte = 512
class AMD64PagedMemory(paged.AbstractWritablePagedMemory):
""" Standard AMD 64-bit address space.
This class implements the AMD64/IA-32E paging address space. It is responsible
for translating each virtual (linear) address to a physical address.
This is accomplished using hierachical paging structures.
Every paging structure is 4096 bytes and is composed of entries.
Each entry is 64 bits. The first paging structure is located at the
physical address found in CR3 (dtb).
Additional Resources:
- Intel(R) 64 and IA-32 Architectures Software Developer's Manual
Volume 3A: System Programming Guide. Section 4.3
http://www.intel.com/products/processor/manuals/index.htm
- AMD64 Architecture Programmer's Manual Volume 2: System Programming
http://support.amd.com/us/Processor_TechDocs/24593_APM_v2.pdf
- N. Petroni, A. Walters, T. Fraser, and W. Arbaugh, "FATKit: A Framework
for the Extraction and Analysis of Digital Forensic Data from Volatile
System Memory" ,Digital Investigation Journal 3(4):197-210, December 2006.
(submitted February 2006)
- N. P. Maclean, "Acquisition and Analysis of Windows Memory,"
University of Strathclyde, Glasgow, April 2006.
- Russinovich, M., & Solomon, D., & Ionescu, A.
"Windows Internals, 5th Edition", Microsoft Press, 2009.
"""
order = 60
pae = False
checkname = 'AMD64ValidAS'
paging_address_space = True
minimum_size = 0x1000
alignment_gcd = 0x1000
def entry_present(self, entry):
if entry:
if (entry & 1):
return True
# The page is in transition and not a prototype.
# Thus, we will treat it as present.
if (entry & (1 << 11)) and not (entry & (1 << 10)):
return True
return False
def page_size_flag(self, entry):
if (entry & (1 << 7)) == (1 << 7):
return True
return False
def get_2MB_paddr(self, vaddr, pgd_entry):
paddr = (pgd_entry & 0xFFFFFFFE00000) | (vaddr & 0x00000001fffff)
return paddr
def is_valid_profile(self, profile):
'''
This method checks to make sure the address space is being
used with a supported profile.
'''
return profile.metadata.get('memory_model', '32bit') == '64bit' or profile.metadata.get('os', 'Unknown').lower() == 'mac'
def pml4e_index(self, vaddr):
'''
This method returns the Page Map Level 4 Entry Index
number from the given virtual address. The index number is
in bits 47:39.
'''
return (vaddr & 0xff8000000000) >> 39
def get_pml4e(self, vaddr):
'''
This method returns the Page Map Level 4 (PML4) entry for the
virtual address. Bits 47:39 are used to the select the
appropriate 8 byte entry in the Page Map Level 4 Table.
"Bits 51:12 are from CR3" [Intel]
"Bits 11:3 are bits 47:39 of the linear address" [Intel]
"Bits 2:0 are 0" [Intel]
'''
pml4e_paddr = (self.dtb & 0xffffffffff000) | ((vaddr & 0xff8000000000) >> 36)
return self.read_long_long_phys(pml4e_paddr)
def get_pdpi(self, vaddr, pml4e):
'''
This method returns the Page Directory Pointer entry for the
virtual address. Bits 32:30 are used to select the appropriate
8 byte entry in the Page Directory Pointer table.
"Bits 51:12 are from the PML4E" [Intel]
"Bits 11:3 are bits 38:30 of the linear address" [Intel]
"Bits 2:0 are all 0" [Intel]
'''
pdpte_paddr = (pml4e & 0xffffffffff000) | ((vaddr & 0x7FC0000000) >> 27)
return self.read_long_long_phys(pdpte_paddr)
def get_1GB_paddr(self, vaddr, pdpte):
'''
If the Page Directory Pointer Table entry represents a 1-GByte
page, this method extracts the physical address of the page.
"Bits 51:30 are from the PDPTE" [Intel]
"Bits 29:0 are from the original linear address" [Intel]
'''
return (pdpte & 0xfffffc0000000) | (vaddr & 0x3fffffff)
def pde_index(self, vaddr):
return (vaddr >> pde_shift) & (ptrs_per_pde - 1)
def pdba_base(self, pdpe):
return pdpe & 0xFFFFFFFFFF000
def get_pgd(self, vaddr, pdpe):
pgd_entry = self.pdba_base(pdpe) + self.pde_index(vaddr) * entry_size
return self.read_long_long_phys(pgd_entry)
def pte_index(self, vaddr):
return (vaddr >> page_shift) & (ptrs_per_pde - 1)
def ptba_base(self, pde):
return pde & 0xFFFFFFFFFF000
def get_pte(self, vaddr, pgd):
pgd_val = self.ptba_base(pgd) + self.pte_index(vaddr) * entry_size
return self.read_long_long_phys(pgd_val)
def pte_pfn(self, pte):
return pte & 0xFFFFFFFFFF000
def get_paddr(self, vaddr, pte):
return self.pte_pfn(pte) | (vaddr & ((1 << page_shift) - 1))
def vtop(self, vaddr):
'''
This method translates an address in the virtual
address space to its associated physical address.
Invalid entries should be handled with operating
system abstractions.
'''
vaddr = long(vaddr)
retVal = None
pml4e = self.get_pml4e(vaddr)
if not self.entry_present(pml4e):
return None
pdpe = self.get_pdpi(vaddr, pml4e)
if not self.entry_present(pdpe):
return retVal
if self.page_size_flag(pdpe):
return self.get_1GB_paddr(vaddr, pdpe)
pgd = self.get_pgd(vaddr, pdpe)
if self.entry_present(pgd):
if self.page_size_flag(pgd):
retVal = self.get_2MB_paddr(vaddr, pgd)
else:
pte = self.get_pte(vaddr, pgd)
if self.entry_present(pte):
retVal = self.get_paddr(vaddr, pte)
return retVal
def read_long_long_phys(self, addr):
'''
This method returns a 64-bit little endian
unsigned integer from the specified address in the
physical address space. If the address cannot be accessed,
then the method returns None.
This code was derived directly from legacyintel.py
'''
try:
string = self.base.read(addr, 8)
except IOError:
string = None
if not string:
return obj.NoneObject("Unable to read_long_long_phys at " + hex(addr))
(longlongval,) = struct.unpack('<Q', string)
return longlongval
def get_available_pages(self):
'''
This method generates a list of pages that are
available within the address space. The entries in
are composed of the virtual address of the page
and the size of the particular page (address, size).
It walks the 0x1000/0x8 (0x200) entries in each Page Map,
Page Directory, and Page Table to determine which pages
are accessible.
'''
for pml4e in range(0, 0x200):
vaddr = pml4e << 39
pml4e_value = self.get_pml4e(vaddr)
if not self.entry_present(pml4e_value):
continue
for pdpte in range(0, 0x200):
vaddr = (pml4e << 39) | (pdpte << 30)
pdpte_value = self.get_pdpi(vaddr, pml4e_value)
if not self.entry_present(pdpte_value):
continue
if self.page_size_flag(pdpte_value):
yield (vaddr, 0x40000000)
continue
pgd_curr = self.pdba_base(pdpte_value)
for j in range(0, ptrs_per_pae_pgd):
soffset = vaddr + (j * ptrs_per_pae_pgd * ptrs_per_pae_pte * 8)
entry = self.read_long_long_phys(pgd_curr)
pgd_curr = pgd_curr + 8
if self.entry_present(entry) and self.page_size_flag(entry):
yield (soffset, 0x200000)
elif self.entry_present(entry):
pte_curr = entry & 0xFFFFFFFFFF000
for k in range(0, ptrs_per_pae_pte):
pte_entry = self.read_long_long_phys(pte_curr)
pte_curr = pte_curr + 8
if self.entry_present(pte_entry):
yield (soffset + k * 0x1000, 0x1000)
@classmethod
def address_mask(cls, addr):
return addr & 0xffffffffffff
| gpl-2.0 |
yongshengwang/builthue | desktop/core/ext-py/MySQL-python-1.2.3c1/_mysql_exceptions.py | 16 | 2306 | """_mysql_exceptions: Exception classes for _mysql and MySQLdb.
These classes are dictated by the DB API v2.0:
http://www.python.org/topics/database/DatabaseAPI-2.0.html
"""
from exceptions import Exception, StandardError, Warning
class MySQLError(StandardError):
"""Exception related to operation with MySQL."""
class Warning(Warning, MySQLError):
"""Exception raised for important warnings like data truncations
while inserting, etc."""
class Error(MySQLError):
"""Exception that is the base class of all other error exceptions
(not Warning)."""
class InterfaceError(Error):
"""Exception raised for errors that are related to the database
interface rather than the database itself."""
class DatabaseError(Error):
"""Exception raised for errors that are related to the
database."""
class DataError(DatabaseError):
"""Exception raised for errors that are due to problems with the
processed data like division by zero, numeric value out of range,
etc."""
class OperationalError(DatabaseError):
"""Exception raised for errors that are related to the database's
operation and not necessarily under the control of the programmer,
e.g. an unexpected disconnect occurs, the data source name is not
found, a transaction could not be processed, a memory allocation
error occurred during processing, etc."""
class IntegrityError(DatabaseError):
"""Exception raised when the relational integrity of the database
is affected, e.g. a foreign key check fails, duplicate key,
etc."""
class InternalError(DatabaseError):
"""Exception raised when the database encounters an internal
error, e.g. the cursor is not valid anymore, the transaction is
out of sync, etc."""
class ProgrammingError(DatabaseError):
"""Exception raised for programming errors, e.g. table not found
or already exists, syntax error in the SQL statement, wrong number
of parameters specified, etc."""
class NotSupportedError(DatabaseError):
"""Exception raised in case a method or database API was used
which is not supported by the database, e.g. requesting a
.rollback() on a connection that does not support transaction or
has transactions turned off."""
del Exception, StandardError
| apache-2.0 |
wechatpy/wechatpy | wechatpy/messages.py | 2 | 6631 | # -*- coding: utf-8 -*-
"""
wechatpy.messages
~~~~~~~~~~~~~~~~~~
This module defines all the messages you can get from WeChat server
:copyright: (c) 2014 by messense.
:license: MIT, see LICENSE for more details.
"""
import copy
from wechatpy.fields import BaseField, DateTimeField, FieldDescriptor, IntegerField, StringField
MESSAGE_TYPES = {}
COMPONENT_MESSAGE_TYPES = {}
def register_message(msg_type):
def register(cls):
MESSAGE_TYPES[msg_type] = cls
return cls
return register
def register_component_message(msg_type):
def register(cls):
COMPONENT_MESSAGE_TYPES[msg_type] = cls
return cls
return register
class MessageMetaClass(type):
"""Metaclass for all messages"""
def __new__(mcs, name, bases, attrs):
for b in bases:
if not hasattr(b, "_fields"):
continue
for k, v in b.__dict__.items():
if k in attrs:
continue
if isinstance(v, FieldDescriptor):
attrs[k] = copy.deepcopy(v.field)
mcs = super().__new__(mcs, name, bases, attrs)
mcs._fields = {}
for name, field in mcs.__dict__.items():
if isinstance(field, BaseField):
field.add_to_class(mcs, name)
return mcs
class BaseMessage(metaclass=MessageMetaClass):
"""Base class for all messages and events"""
type = "unknown"
id = IntegerField("MsgId", 0)
source = StringField("FromUserName")
target = StringField("ToUserName")
create_time = DateTimeField("CreateTime")
time = IntegerField("CreateTime")
def __init__(self, message):
self._data = message
def __repr__(self):
return f"{self.__class__.__name__}({repr(self._data)})"
@register_message("text")
class TextMessage(BaseMessage):
"""
文本消息
详情请参阅
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
"""
type = "text"
content = StringField("Content")
@register_message("image")
class ImageMessage(BaseMessage):
"""
图片消息
详情请参阅
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
"""
type = "image"
media_id = StringField("MediaId")
image = StringField("PicUrl")
@register_message("voice")
class VoiceMessage(BaseMessage):
"""
语音消息
详情请参阅
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
"""
type = "voice"
media_id = StringField("MediaId")
format = StringField("Format")
recognition = StringField("Recognition")
@register_message("shortvideo")
class ShortVideoMessage(BaseMessage):
"""
短视频消息
详情请参阅
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
"""
type = "shortvideo"
media_id = StringField("MediaId")
thumb_media_id = StringField("ThumbMediaId")
@register_message("video")
class VideoMessage(BaseMessage):
"""
视频消息
详情请参阅
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
"""
type = "video"
media_id = StringField("MediaId")
thumb_media_id = StringField("ThumbMediaId")
@register_message("location")
class LocationMessage(BaseMessage):
"""
地理位置消息
详情请参阅
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
"""
type = "location"
location_x = StringField("Location_X")
location_y = StringField("Location_Y")
scale = StringField("Scale")
label = StringField("Label")
@property
def location(self):
return self.location_x, self.location_y
@register_message("link")
class LinkMessage(BaseMessage):
"""
链接消息
详情请参阅
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html
"""
type = "link"
title = StringField("Title")
description = StringField("Description")
url = StringField("Url")
@register_message("miniprogrampage")
class MiniProgramPageMessage(BaseMessage):
"""
小程序卡片消息
详情请参阅
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/customer-message/receive.html#小程序卡片消息
"""
type = "miniprogrampage"
app_id = StringField("AppId")
title = StringField("Title")
page_path = StringField("PagePath")
thumb_url = StringField("ThumbUrl")
thumb_media_id = StringField("ThumbMediaId")
class UnknownMessage(BaseMessage):
"""未知消息类型"""
pass
class BaseComponentMessage(metaclass=MessageMetaClass):
"""Base class for all component messages and events"""
type = "unknown"
appid = StringField("AppId")
create_time = DateTimeField("CreateTime")
def __init__(self, message):
self._data = message
def __repr__(self):
return f"{self.__class__.__name__}({repr(self._data)})"
@register_component_message("component_verify_ticket")
class ComponentVerifyTicketMessage(BaseComponentMessage):
"""
component_verify_ticket协议
"""
type = "component_verify_ticket"
verify_ticket = StringField("ComponentVerifyTicket")
@register_component_message("unauthorized")
class ComponentUnauthorizedMessage(BaseComponentMessage):
"""
取消授权通知
"""
type = "unauthorized"
authorizer_appid = StringField("AuthorizerAppid")
@register_component_message("authorized")
class ComponentAuthorizedMessage(BaseComponentMessage):
"""
新增授权通知
"""
type = "authorized"
authorizer_appid = StringField("AuthorizerAppid")
authorization_code = StringField("AuthorizationCode")
authorization_code_expired_time = StringField("AuthorizationCodeExpiredTime")
pre_auth_code = StringField("PreAuthCode")
@register_component_message("updateauthorized")
class ComponentUpdateAuthorizedMessage(BaseComponentMessage):
"""
更新授权通知
"""
type = "updateauthorized"
authorizer_appid = StringField("AuthorizerAppid")
authorization_code = StringField("AuthorizationCode")
authorization_code_expired_time = StringField("AuthorizationCodeExpiredTime")
pre_auth_code = StringField("PreAuthCode")
class ComponentUnknownMessage(BaseComponentMessage):
"""
未知通知
"""
type = "unknown"
| mit |
kivatu/kivy-bak | kivy/uix/listview.py | 5 | 40156 | '''
List View
===========
.. versionadded:: 1.5
.. warning::
This code is still experimental, and its API is subject to change in a
future version.
The :class:`~kivy.uix.listview.ListView` widget provides a scrollable/pannable
viewport that is clipped to the scrollview's bounding box which contains
list item view instances.
The :class:`~kivy.uix.listview.ListView` implements an :class:`AbstractView` as
a vertical, scrollable list. The :class:`AbstractView` has one property:
:class:`~kivy.adapters.adapter`.
The :class:`~kivy.uix.listview.ListView` sets an adapter to one of a
:class:`~kivy.adapters.simplelistadapter.SimpleListAdapter`,
:class:`~kivy.adapters.listadapter.ListAdapter` or a
:class:`~kivy.adapters.dictadapter.DictAdapter`.
Introduction
------------
Lists are central parts of many software projects. Kivy's approach to lists
includes providing solutions for simple lists, along with a substantial
framework for building lists of moderate to advanced complexity. For a new
user, it can be difficult to ramp up from simple to advanced. For
this reason, Kivy provides an extensive set of examples that you may wish to
run first, to get a taste of the range of functionality offered. You can tell
from the names of the examples that they illustrate the "ramping up" from
simple to advanced:
* kivy/examples/widgets/lists/list_simple.py
* kivy/examples/widgets/lists/list_simple_in_kv.py
* kivy/examples/widgets/lists/list_simple_in_kv_2.py
* kivy/examples/widgets/lists/list_master_detail.py
* kivy/examples/widgets/lists/list_two_up.py
* kivy/examples/widgets/lists/list_kv.py
* kivy/examples/widgets/lists/list_composite.py
* kivy/examples/widgets/lists/list_cascade.py
* kivy/examples/widgets/lists/list_cascade_dict.py
* kivy/examples/widgets/lists/list_cascade_images.py
* kivy/examples/widgets/lists/list_ops.py
Many of the examples feature selection, some restricting selection to single
selection, where only one item at at time can be selected, and others allowing
multiple item selection. Many of the examples illustrate how selection in one
list can be connected to actions and selections in another view or another list.
Find your own way of reading the documentation here, examining the source code
for the example apps and running the examples. Some may prefer to read the
documentation through first, others may want to run the examples and view their
code. No matter what you do, going back and forth will likely be needed.
Basic Example
-------------
In its simplest form, we make a listview with 100 items::
from kivy.uix.listview import ListView
from kivy.uix.gridlayout import GridLayout
class MainView(GridLayout):
def __init__(self, **kwargs):
kwargs['cols'] = 2
super(MainView, self).__init__(**kwargs)
list_view = ListView(
item_strings=[str(index) for index in range(100)])
self.add_widget(list_view)
if __name__ == '__main__':
from kivy.base import runTouchApp
runTouchApp(MainView(width=800))
Or, we could declare the listview using the kv language::
from kivy.uix.modalview import ModalView
from kivy.uix.listview import ListView
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
Builder.load_string("""
<ListViewModal>:
size_hint: None, None
size: 400, 400
ListView:
size_hint: .8, .8
item_strings: [str(index) for index in range(100)]
""")
class ListViewModal(ModalView):
def __init__(self, **kwargs):
super(ListViewModal, self).__init__(**kwargs)
class MainView(GridLayout):
def __init__(self, **kwargs):
kwargs['cols'] = 1
super(MainView, self).__init__(**kwargs)
listview_modal = ListViewModal()
self.add_widget(listview_modal)
if __name__ == '__main__':
from kivy.base import runTouchApp
runTouchApp(MainView(width=800))
Using an Adapter
-------------------
Behind the scenes, the basic example above uses the
:class:`~kivy.adapters.simplelistadapter.SimpleListAdapter`. When the
constructor for the :class:`~kivy.uix.listview.ListView` sees that only a list
of
strings is provided as an argument (called item_strings), it creates an instance
of :class:`~kivy.adapters.simplelistadapter.SimpleListAdapter` using the
list of strings.
Simple in :class:`~kivy.adapters.simplelistadapter.SimpleListAdapter` means:
*without selection support*. It is a scrollable list of items that does not
respond to touch events.
To use a :class:`SimpleListAdaper` explicitly when creating a ListView instance,
do::
simple_list_adapter = SimpleListAdapter(
data=["Item #{0}".format(i) for i in range(100)],
cls=Label)
list_view = ListView(adapter=simple_list_adapter)
The instance of :class:`~kivy.adapters.simplelistadapter.SimpleListAdapter` has
a required data argument which contains data items to use for instantiating
Label views for the list view (note the cls=Label argument). The data items are
strings. Each item string is set by the
:class:`~kivy.adapters.simplelistadapter.SimpleListAdapter` as the *text*
argument for each Label instantiation.
You can declare a ListView with an adapter in a kv file with special attention
given to the way longer python blocks are indented::
from kivy.uix.modalview import ModalView
from kivy.uix.listview import ListView
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder
from kivy.factory import Factory
# Note the special nature of indentation in the adapter declaration, where
# the adapter: is on one line, then the value side must be given at one
# level of indentation.
Builder.load_string("""
#:import label kivy.uix.label
#:import sla kivy.adapters.simplelistadapter
<ListViewModal>:
size_hint: None, None
size: 400, 400
ListView:
size_hint: .8, .8
adapter:
sla.SimpleListAdapter(
data=["Item #{0}".format(i) for i in range(100)],
cls=label.Label)
""")
class ListViewModal(ModalView):
def __init__(self, **kwargs):
super(ListViewModal, self).__init__(**kwargs)
class MainView(GridLayout):
def __init__(self, **kwargs):
kwargs['cols'] = 1
super(MainView, self).__init__(**kwargs)
listview_modal = ListViewModal()
self.add_widget(listview_modal)
if __name__ == '__main__':
from kivy.base import runTouchApp
runTouchApp(MainView(width=800))
ListAdapter and DictAdapter
---------------------------
For many uses of a list, the data is more than a simple list of strings.
Selection functionality is also often needed.
The :class:`~kivy.adapters.listadapter.ListAdapter` and
:class:`~kivy.adapters.dictadapter.DictAdapter` cover these more elaborate
needs.
The :class:`~kivy.adapters.listadapter.ListAdapter` is the base class for
:class:`~kivy.adapters.dictadapter.DictAdapter`, so we can start with it.
See the :class:`~kivy.adapters.listadapter.ListAdapter` docs for details, but
here are synopses of its arguments:
* *data*: strings, class instances, dicts, etc. that form the basis data
for instantiating views.
* *cls*: a Kivy view that is to be instantiated for each list item. There
are several built-in types available, including ListItemLabel and
ListItemButton, or you can make your own class that mixes in the
required :class:`~kivy.uix.listview.SelectableView`.
* *template*: the name of a Kivy language (kv) template that defines the
Kivy view for each list item.
.. note::
Pick only one, cls or template, to provide as an argument.
* *args_converter*: a function that takes a data item object as input and
uses it to build and return an args dict, ready
to be used in a call to instantiate item views using the item view cls
or template. In the case of cls, the args dict acts as a
kwargs object. For a template, it is treated as a context
(ctx) but is essentially similar in form to the kwargs usage.
* *selection_mode*: a string with the value 'single', 'multiple' or others
(See :attr:`~kivy.adapters.listadapter.ListAdapter.selection_mode` for
details).
* *allow_empty_selection*: a boolean, which if False (the default), forces
there to always be a selection if there is data
available. If True, selection happens only as a
result of user action.
In narrative, we can summarize as follows:
A listview's adapter takes data items and uses an args_converter
function to transform them into arguments for making list item view
instances, using either a cls or a kv template.
In a graphic, a summary of the relationship between a listview and its
list adapter, looks like this::
- ------------ ListAdapter or DictAdapter ------------
- | |
- | <list item views> (cls or template) <data items> |
- ListView --> | [args_converter] |
- | |
- | <<< selection handling >>> |
- | |
- ----------------------------------------------------
A :class:`~kivy.adapters.dictadapter.DictAdapter` has the same arguments and
requirements as :class:`~kivy.adapters.listadapter.ListAdapter` except for two
things:
1) There is an additional argument, sorted_keys, which must meet the
requirements of normal python dictionary keys.
2) The data argument is, as you would expect, a dict. Keys in the dict
must include the keys in the sorted_keys argument, but they may form a
superset of the keys in sorted_keys. Values may be strings, class
instances, dicts, etc. (The args_converter uses it accordingly).
Using an Args Converter
-----------------------
A :class:`~kivy.uix.listview.ListView` allows use of built-in list item views,
such as :class:`~kivy.uix.listview.ListItemButton`, your own custom item view
class or a custom kv template. Whichever type of list item view is used, an
args_converter function is needed to prepare, per list data item, args for
the cls or template.
.. note::
Only the ListItemLabel, ListItemButton or custom classes like them, and
neither the bare Label nor Button classes, are to be used in the listview
system.
.. warning::
ListItemButton inherits the `background_normal` and `background_down`
properties from the Button widget, so the `selected_color` and
`deselected_color` are not represented faithfully by default.
Here is an args_converter for use with the built-in
:class:`~kivy.uix.listview.ListItemButton` specified as a normal Python
function::
def args_converter(row_index, an_obj):
return {'text': an_obj.text,
'size_hint_y': None,
'height': 25}
and as a lambda:
args_converter = lambda row_index, an_obj: {'text': an_obj.text,
'size_hint_y': None,
'height': 25}
In the args converter example above, the data item is assumed to be an object
(class instance), hence the reference an_obj.text.
Here is an example of an args converter that works with list data items that
are dicts::
args_converter = lambda row_index, obj: {'text': obj['text'],
'size_hint_y': None,
'height': 25}
So, it is the responsibility of the developer to code the args_converter
according to the data at hand. The row_index argument can be useful in some
cases, such as when custom labels are needed.
An Example ListView
-------------------
Now, to some example code::
from kivy.adapters.listadapter import ListAdapter
from kivy.uix.listview import ListItemButton, ListView
data = [{'text': str(i), 'is_selected': False} for i in range(100)]
args_converter = lambda row_index, rec: {'text': rec['text'],
'size_hint_y': None,
'height': 25}
list_adapter = ListAdapter(data=data,
args_converter=args_converter,
cls=ListItemButton,
selection_mode='single',
allow_empty_selection=False)
list_view = ListView(adapter=list_adapter)
This listview will show 100 buttons with text of 0 to 100. The args converter
function works on dict items in the data. ListItemButton views will be
instantiated from the args converted by args_converter for each data item. The
listview will only allow single selection: additional touches will be
ignored. When the listview is first shown, the first item will already be
selected because allow_empty_selection is False.
The :class:`~kivy.uix.listview.ListItemLabel` works in much the same way as the
:class:`~kivy.uix.listview.ListItemButton`.
Using a Custom Item View Class
------------------------------
The data used in an adapter can be any of the normal Python types, such as
strings, class instances and dictionaries. They can also be custom classes, as
shown below. It is up to the programmer to assure that the args_converter
performs the appropriate conversions.
Here we make a simple DataItem class that has the required text and
is_selected properties::
from kivy.uix.listview import ListItemButton
from kivy.adapters.listadapter import ListAdapter
class DataItem(object):
def __init__(self, text='', is_selected=False):
self.text = text
self.is_selected = is_selected
data_items = []
data_items.append(DataItem(text='cat'))
data_items.append(DataItem(text='dog'))
data_items.append(DataItem(text='frog'))
list_item_args_converter = lambda row_index, obj: {'text': obj.text,
'size_hint_y': None,
'height': 25}
list_adapter = ListAdapter(data=data_items,
args_converter=list_item_args_converter,
selection_mode='single',
propagate_selection_to_data=True,
allow_empty_selection=False,
cls=ListItemButton)
list_view = ListView(adapter=list_adapter)
The data is set in a :class:`~kivy.adapters.listadapter.ListAdapter` along
with a list item args_converter function above (lambda) and arguments
concerning selection: only single selection is allowed, and selection in the
listview will propagate to the data items. The propagation setting means that
the is_selected property for each data item will be set and kept in sync with
the list item views. By having allow_empty_selection=False, when the listview
first appears, the first item, 'cat', will already be selected. The list
adapter will instantiate a :class:`~kivy.uix.listview.ListItemButton` class
instance for each data item, using the assigned args_converter.
The list_vew would be added to a view with add_widget() after the last line,
where it is created. See the basic example at the top of this documentation for
an example of add_widget() use in the context of a sample app.
You may also use the provided :class:`SelectableDataItem` mixin to make a
custom class. Instead of the "manually-constructed" DataItem class above,
we could do::
from kivy.adapters.models import SelectableDataItem
class DataItem(SelectableDataItem):
# Add properties here.
pass
:class:`SelectableDataItem` is a simple mixin class that has an is_selected
property.
Using an Item View Template
---------------------------
:class:`~kivy.uix.listview.SelectableView` is another simple mixin class that
has required properties for a list item: text, and is_selected. To make your
own template, mix it in as follows::
from kivy.uix.listview import ListItemButton
from kivy.uix.listview import SelectableView
Builder.load_string("""
[CustomListItem@SelectableView+BoxLayout]:
size_hint_y: ctx.size_hint_y
height: ctx.height
ListItemButton:
text: ctx.text
is_selected: ctx.is_selected
""")
A class called CustomListItem will be instantiated for each list item. Note
that it is a layout, BoxLayout, and is thus a kind of container. It contains a
:class:`~kivy.uix.listview.ListItemButton` instance.
Using the power of the Kivy language (kv), you can easily build composite list
items -- in addition to ListItemButton, you could have a ListItemLabel, or a
custom class you have defined and registered with the system.
An args_converter needs to be constructed that goes along with such a kv
template. For example, to use the kv template above::
list_item_args_converter = \
lambda row_index, rec: {'text': rec['text'],
'is_selected': rec['is_selected'],
'size_hint_y': None,
'height': 25}
integers_dict = \
{ str(i): {'text': str(i), 'is_selected': False} for i in range(100)}
dict_adapter = DictAdapter(sorted_keys=[str(i) for i in range(100)],
data=integers_dict,
args_converter=list_item_args_converter,
template='CustomListItem')
list_view = ListView(adapter=dict_adapter)
A dict adapter is created with 1..100 integer strings as sorted_keys, and an
integers_dict as data. integers_dict has the integer strings as keys and dicts
with text and is_selected properties. The CustomListItem defined above in the
Builder.load_string() call is set as the kv template for the list item views.
The list_item_args_converter lambda function will take each dict in
integers_dict and will return an args dict, ready for passing as the context
(ctx) for the template.
The list_vew would be added to a view with add_widget() after the last line,
where it is created. Again, see the basic example above for add_widget() use.
Using CompositeListItem
-----------------------
The class :class:`~kivy.uix.listview.CompositeListItem` is another option for
building advanced composite list items. The kv language approach has its
advantages, but here we build a composite list view using a straight Kivy
widget method::
args_converter = lambda row_index, rec: \
{'text': rec['text'],
'size_hint_y': None,
'height': 25,
'cls_dicts': [{'cls': ListItemButton,
'kwargs': {'text': rec['text']}},
{'cls': ListItemLabel,
'kwargs': {'text': "Middle-{0}".format(rec['text']),
'is_representing_cls': True}},
{'cls': ListItemButton,
'kwargs': {'text': rec['text']}}]}
item_strings = ["{0}".format(index) for index in range(100)]
integers_dict = \
{ str(i): {'text': str(i), 'is_selected': False} for i in range(100)}
dict_adapter = DictAdapter(sorted_keys=item_strings,
data=integers_dict,
args_converter=args_converter,
selection_mode='single',
allow_empty_selection=False,
cls=CompositeListItem)
list_view = ListView(adapter=dict_adapter)
The args_converter is somewhat complicated, so we should go through the
details. Observe in the :class:`~kivy.adapters.dictadapter.DictAdapter`
instantiation that :class:`~kivy.uix.listview.CompositeListItem` instance is
set as the cls to be instantiated for each list item. The args_converter will
make args dicts for this cls. In the args_converter, the first three items,
text, size_hint_y, and height, are arguments for CompositeListItem itself.
After that you see a cls_dicts list that contains argument sets for each of the
member widgets for this composite: :class:`~kivy.uix.listview.ListItemButton`
and :class:`~kivy.uix.listview.ListItemLabel`. This is a similar approach to
using a kv template described above.
The sorted_keys and data arguments for the dict adapter are the same as in the
previous code example.
For details on how :class:`~kivy.uix.listview.CompositeListItem` works,
examine the code, looking for how parsing of the cls_dicts list and kwargs
processing is done.
Uses for Selection
------------------
What can we do with selection? Combining selection with the system of bindings
in Kivy, we can build a wide range of user interface designs.
We could make data items that contain the names of dog breeds, and connect
the selection of dog breed to the display of details in another view, which
would update automatically on selection. This is done via a binding to the
on_selection_change event::
list_adapter.bind(on_selection_change=callback_function)
where callback_function() does whatever is needed for the update. See the
example called list_master_detail.py, and imagine that the list one the left
would be a list of dog breeds, and the detail view on the right would show
details for a selected dog breed.
In another example, we could set the selection_mode of a listview to
'multiple', and load it with a list of answers to a multiple-choice question.
The question could have several correct answers. A color swatch view could be
bound to selection change, as above, so that it turns green as soon as the
correct choices are made, unless the number of touches exeeds a limit, when the
answer session would be terminated. See the examples that feature thumbnail
images to get some ideas, e.g., list_cascade_dict.py.
In a more involved example, we could chain together three listviews, where
selection in the first controls the items shown in the second, and selection in
the second controls the items shown in the third. If allow_empty_selection were
set to False for these listviews, a dynamic system of selection "cascading"
from one list to the next, would result.
There are so many ways that listviews and Kivy bindings functionality can be
used, that we have only scratched the surface here. For on-disk examples, see
these::
kivy/examples/widgets/lists/list_*.py
Several examples show the "cascading" behavior described above. Others
demonstrate the use of kv templates and composite list views.
'''
__all__ = ('SelectableView', 'ListItemButton', 'ListItemLabel',
'CompositeListItem', 'ListView', )
from kivy.event import EventDispatcher
from kivy.clock import Clock
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.adapters.simplelistadapter import SimpleListAdapter
from kivy.uix.abstractview import AbstractView
from kivy.properties import ObjectProperty, DictProperty, \
NumericProperty, ListProperty, BooleanProperty
from kivy.lang import Builder
from math import ceil, floor
class SelectableView(object):
'''The :class:`~kivy.uix.listview.SelectableView` mixin is used to design
list item and other classes that are to be instantiated by an adapter to be
used in a listview. The :class:`~kivy.adapters.listadapter.ListAdapter`
and :class:`~kivy.adapters.dictadapter.DictAdapter` adapters are
selection-enabled. select() and deselect() are to be overridden with
display code to mark items as selected or not, if desired.
'''
index = NumericProperty(-1)
'''The index into the underlying data list or the data item this view
represents.
:attr:`index` is a :class:`~kivy.properties.NumericProperty`, default
to -1.
'''
is_selected = BooleanProperty(False)
'''A SelectableView instance carries this property, which should be kept
in sync with the equivalent property in the data item it represents.
:attr:`is_selected` is a :class:`~kivy.properties.BooleanProperty`, default
to False.
'''
def __init__(self, **kwargs):
super(SelectableView, self).__init__(**kwargs)
def select(self, *args):
'''The list item is responsible for updating the display for
being selected, if desired.
'''
self.is_selected = True
def deselect(self, *args):
'''The list item is responsible for updating the display for
being unselected, if desired.
'''
self.is_selected = False
class ListItemButton(SelectableView, Button):
''':class:`~kivy.uix.listview.ListItemButton` mixes
:class:`~kivy.uix.listview.SelectableView` with
:class:`~kivy.uix.button.Button` to produce a button suitable for use in
:class:`~kivy.uix.listview.ListView`.
'''
selected_color = ListProperty([1., 0., 0., 1])
'''
:attr:`selected_color` is a :class:`~kivy.properties.ListProperty` and
defaults to [1., 0., 0., 1].
'''
deselected_color = ListProperty([0., 1., 0., 1])
'''
:attr:`selected_color` is a :class:`~kivy.properties.ListProperty` and
defaults to [0., 1., 0., 1].
'''
def __init__(self, **kwargs):
super(ListItemButton, self).__init__(**kwargs)
# Set Button bg color to be deselected_color.
self.background_color = self.deselected_color
def select(self, *args):
self.background_color = self.selected_color
if isinstance(self.parent, CompositeListItem):
self.parent.select_from_child(self, *args)
def deselect(self, *args):
self.background_color = self.deselected_color
if isinstance(self.parent, CompositeListItem):
self.parent.deselect_from_child(self, *args)
def select_from_composite(self, *args):
self.background_color = self.selected_color
def deselect_from_composite(self, *args):
self.background_color = self.deselected_color
def __repr__(self):
return '<%s text=%s>' % (self.__class__.__name__, self.text)
# [TODO] Why does this mix in SelectableView -- that makes it work like
# button, which is redundant.
class ListItemLabel(SelectableView, Label):
''':class:`~kivy.uix.listview.ListItemLabel` mixes
:class:`~kivy.uix.listview.SelectableView` with
:class:`~kivy.uix.label.Label` to produce a label suitable for use in
:class:`~kivy.uix.listview.ListView`.
'''
def __init__(self, **kwargs):
super(ListItemLabel, self).__init__(**kwargs)
def select(self, *args):
self.bold = True
if isinstance(self.parent, CompositeListItem):
self.parent.select_from_child(self, *args)
def deselect(self, *args):
self.bold = False
if isinstance(self.parent, CompositeListItem):
self.parent.deselect_from_child(self, *args)
def select_from_composite(self, *args):
self.bold = True
def deselect_from_composite(self, *args):
self.bold = False
def __repr__(self):
return '<%s text=%s>' % (self.__class__.__name__, self.text)
class CompositeListItem(SelectableView, BoxLayout):
''':class:`~kivy.uix.listview.CompositeListItem` mixes
:class:`~kivy.uix.listview.SelectableView` with :class:`BoxLayout` for a
generic container-style list item, to be used in
:class:`~kivy.uix.listview.ListView`.
'''
background_color = ListProperty([1, 1, 1, 1])
'''ListItem sublasses Button, which has background_color, but
for a composite list item, we must add this property.
:attr:`background_color` is a :class:`~kivy.properties.ListProperty` and
defaults to [1, 1, 1, 1].
'''
selected_color = ListProperty([1., 0., 0., 1])
'''
:attr:`selected_color` is a :class:`~kivy.properties.ListProperty` and
defaults to [1., 0., 0., 1].
'''
deselected_color = ListProperty([.33, .33, .33, 1])
'''
:attr:`deselected_color` is a :class:`~kivy.properties.ListProperty` and
defaults to [.33, .33, .33, 1].
'''
representing_cls = ObjectProperty(None)
'''Which component view class, if any, should represent for the
composite list item in __repr__()?
:attr:`representing_cls` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
def __init__(self, **kwargs):
super(CompositeListItem, self).__init__(**kwargs)
# Example data:
#
# 'cls_dicts': [{'cls': ListItemButton,
# 'kwargs': {'text': "Left"}},
# 'cls': ListItemLabel,
# 'kwargs': {'text': "Middle",
# 'is_representing_cls': True}},
# 'cls': ListItemButton,
# 'kwargs': {'text': "Right"}]
# There is an index to the data item this composite list item view
# represents. Get it from kwargs and pass it along to children in the
# loop below.
index = kwargs['index']
for cls_dict in kwargs['cls_dicts']:
cls = cls_dict['cls']
cls_kwargs = cls_dict.get('kwargs', None)
if cls_kwargs:
cls_kwargs['index'] = index
if 'selection_target' not in cls_kwargs:
cls_kwargs['selection_target'] = self
if 'text' not in cls_kwargs:
cls_kwargs['text'] = kwargs['text']
if 'is_representing_cls' in cls_kwargs:
self.representing_cls = cls
self.add_widget(cls(**cls_kwargs))
else:
cls_kwargs = {}
cls_kwargs['index'] = index
if 'text' in kwargs:
cls_kwargs['text'] = kwargs['text']
self.add_widget(cls(**cls_kwargs))
def select(self, *args):
self.background_color = self.selected_color
def deselect(self, *args):
self.background_color = self.deselected_color
def select_from_child(self, child, *args):
for c in self.children:
if c is not child:
c.select_from_composite(*args)
def deselect_from_child(self, child, *args):
for c in self.children:
if c is not child:
c.deselect_from_composite(*args)
def __repr__(self):
if self.representing_cls is not None:
return '<%r>, representing <%s>' % (
self.representing_cls, self.__class__.__name__)
else:
return '<%s>' % (self.__class__.__name__)
Builder.load_string('''
<ListView>:
container: container
ScrollView:
pos: root.pos
on_scroll_y: root._scroll(args[1])
do_scroll_x: False
GridLayout:
cols: 1
id: container
size_hint_y: None
''')
class ListView(AbstractView, EventDispatcher):
''':class:`~kivy.uix.listview.ListView` is a primary high-level widget,
handling the common task of presenting items in a scrolling list.
Flexibility is afforded by use of a variety of adapters to interface with
data.
The adapter property comes via the mixed in
:class:`~kivy.uix.abstractview.AbstractView` class.
:class:`~kivy.uix.listview.ListView` also subclasses
:class:`EventDispatcher` for scrolling. The event *on_scroll_complete* is
used in refreshing the main view.
For a simple list of string items, without selection, use
:class:`~kivy.adapters.simplelistadapter.SimpleListAdapter`. For list items
that respond to selection, ranging from simple items to advanced
composites, use :class:`~kivy.adapters.listadapter.ListAdapter`. For an
alternate powerful adapter, use
:class:`~kivy.adapters.dictadapter.DictAdapter`, rounding out the choice
for designing highly interactive lists.
:Events:
`on_scroll_complete`: (boolean, )
Fired when scrolling completes.
'''
divider = ObjectProperty(None)
'''[TODO] Not used.
'''
divider_height = NumericProperty(2)
'''[TODO] Not used.
'''
container = ObjectProperty(None)
'''The container is a :class:`~kivy.uix.gridlayout.GridLayout` widget held
within a :class:`~kivy.uix.scrollview.ScrollView` widget. (See the
associated kv block in the Builder.load_string() setup). Item view
instances managed and provided by the adapter are added to this container.
The container is cleared with a call to clear_widgets() when the list is
rebuilt by the populate() method. A padding
:class:`~kivy.uix.widget.Widget` instance is also added as needed,
depending on the row height calculations.
:attr:`container` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None.
'''
row_height = NumericProperty(None)
'''The row_height property is calculated on the basis of the height of the
container and the count of items.
:attr:`row_height` is a :class:`~kivy.properties.NumericProperty` and
defaults to None.
'''
item_strings = ListProperty([])
'''If item_strings is provided, create an instance of
:class:`~kivy.adapters.simplelistadapter.SimpleListAdapter` with this list
of strings, and use it to manage a no-selection list.
:attr:`item_strings` is a :class:`~kivy.properties.ListProperty` and
defaults to [].
'''
scrolling = BooleanProperty(False)
'''If the scroll_to() method is called while scrolling operations are
happening, a call recursion error can occur. scroll_to() checks to see that
scrolling is False before calling populate(). scroll_to() dispatches a
scrolling_complete event, which sets scrolling back to False.
:attr:`scrolling` is a :class:`~kivy.properties.BooleanProperty` and
defaults to False.
'''
_index = NumericProperty(0)
_sizes = DictProperty({})
_count = NumericProperty(0)
_wstart = NumericProperty(0)
_wend = NumericProperty(-1)
__events__ = ('on_scroll_complete', )
def __init__(self, **kwargs):
# Check for an adapter argument. If it doesn't exist, we
# check for item_strings in use with SimpleListAdapter
# to make a simple list.
if 'adapter' not in kwargs:
if 'item_strings' not in kwargs:
# Could be missing, or it could be that the ListView is
# declared in a kv file. If kv is in use, and item_strings is
# declared there, then item_strings will not be set until after
# __init__(). So, the data=[] set will temporarily serve for
# SimpleListAdapter instantiation, with the binding to
# item_strings_changed() handling the eventual set of the
# item_strings property from the application of kv rules.
list_adapter = SimpleListAdapter(data=[],
cls=Label)
else:
list_adapter = SimpleListAdapter(data=kwargs['item_strings'],
cls=Label)
kwargs['adapter'] = list_adapter
super(ListView, self).__init__(**kwargs)
self._trigger_populate = Clock.create_trigger(self._spopulate, -1)
self._trigger_reset_populate = \
Clock.create_trigger(self._reset_spopulate, -1)
self.bind(size=self._trigger_populate,
pos=self._trigger_populate,
item_strings=self.item_strings_changed,
adapter=self._trigger_populate)
# The bindings setup above sets self._trigger_populate() to fire
# when the adapter changes, but we also need this binding for when
# adapter.data and other possible triggers change for view updating.
# We don't know that these are, so we ask the adapter to set up the
# bindings back to the view updating function here.
self.adapter.bind_triggers_to_view(self._trigger_reset_populate)
# Added to set data when item_strings is set in a kv template, but it will
# be good to have also if item_strings is reset generally.
def item_strings_changed(self, *args):
self.adapter.data = self.item_strings
def _scroll(self, scroll_y):
if self.row_height is None:
return
self._scroll_y = scroll_y
scroll_y = 1 - min(1, max(scroll_y, 0))
container = self.container
mstart = (container.height - self.height) * scroll_y
mend = mstart + self.height
# convert distance to index
rh = self.row_height
istart = int(ceil(mstart / rh))
iend = int(floor(mend / rh))
istart = max(0, istart - 1)
iend = max(0, iend - 1)
if istart < self._wstart:
rstart = max(0, istart - 10)
self.populate(rstart, iend)
self._wstart = rstart
self._wend = iend
elif iend > self._wend:
self.populate(istart, iend + 10)
self._wstart = istart
self._wend = iend + 10
def _spopulate(self, *args):
self.populate()
def _reset_spopulate(self, *args):
self._wend = -1
self.populate()
# simulate the scroll again, only if we already scrolled before
# the position might not be the same, mostly because we don't know the
# size of the new item.
if hasattr(self, '_scroll_y'):
self._scroll(self._scroll_y)
def populate(self, istart=None, iend=None):
container = self.container
sizes = self._sizes
rh = self.row_height
# ensure we know what we want to show
if istart is None:
istart = self._wstart
iend = self._wend
# clear the view
container.clear_widgets()
# guess only ?
if iend is not None and iend != -1:
# fill with a "padding"
fh = 0
for x in range(istart):
fh += sizes[x] if x in sizes else rh
container.add_widget(Widget(size_hint_y=None, height=fh))
# now fill with real item_view
index = istart
while index <= iend:
item_view = self.adapter.get_view(index)
index += 1
if item_view is None:
continue
sizes[index] = item_view.height
container.add_widget(item_view)
else:
available_height = self.height
real_height = 0
index = self._index
count = 0
while available_height > 0:
item_view = self.adapter.get_view(index)
if item_view is None:
break
sizes[index] = item_view.height
index += 1
count += 1
container.add_widget(item_view)
available_height -= item_view.height
real_height += item_view.height
self._count = count
# extrapolate the full size of the container from the size
# of view instances in the adapter
if count:
container.height = \
real_height / count * self.adapter.get_count()
if self.row_height is None:
self.row_height = real_height / count
def scroll_to(self, index=0):
if not self.scrolling:
self.scrolling = True
self._index = index
self.populate()
self.dispatch('on_scroll_complete')
def on_scroll_complete(self, *args):
self.scrolling = False
| mit |
yongshengwang/hue | desktop/core/ext-py/Babel-0.9.6/babel/tests/core.py | 61 | 1726 | # -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://babel.edgewall.org/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.
import doctest
import os
import unittest
from babel import core
from babel.core import default_locale
class DefaultLocaleTest(unittest.TestCase):
def setUp(self):
self._old_locale_settings = self._current_locale_settings()
def tearDown(self):
self._set_locale_settings(self._old_locale_settings)
def _current_locale_settings(self):
settings = {}
for name in ('LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG'):
settings[name] = os.environ[name]
return settings
def _set_locale_settings(self, settings):
for name, value in settings.items():
os.environ[name] = value
def test_ignore_invalid_locales_in_lc_ctype(self):
# This is a regression test specifically for a bad LC_CTYPE setting on
# MacOS X 10.6 (#200)
os.environ['LC_CTYPE'] = 'UTF-8'
# must not throw an exception
default_locale('LC_CTYPE')
def suite():
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(core))
suite.addTest(unittest.makeSuite(DefaultLocaleTest))
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| apache-2.0 |
wdaher/zulip | zerver/tornadoviews.py | 120 | 4177 | from __future__ import absolute_import
from django.views.decorators.csrf import csrf_exempt
from zerver.models import get_client
from zerver.decorator import asynchronous, \
authenticated_json_post_view, internal_notify_view, RespondAsynchronously, \
has_request_variables, REQ
from zerver.lib.response import json_success, json_error
from zerver.lib.validator import check_bool, check_list, check_string
from zerver.lib.event_queue import allocate_client_descriptor, get_client_descriptor, \
process_notification
from zerver.lib.narrow import check_supported_events_narrow_filter
import ujson
import logging
from zerver.lib.rest import rest_dispatch as _rest_dispatch
rest_dispatch = csrf_exempt((lambda request, *args, **kwargs: _rest_dispatch(request, globals(), *args, **kwargs)))
@internal_notify_view
def notify(request):
process_notification(ujson.loads(request.POST['data']))
return json_success()
@has_request_variables
def cleanup_event_queue(request, user_profile, queue_id=REQ()):
client = get_client_descriptor(queue_id)
if client is None:
return json_error("Bad event queue id: %s" % (queue_id,))
if user_profile.id != client.user_profile_id:
return json_error("You are not authorized to access this queue")
request._log_data['extra'] = "[%s]" % (queue_id,)
client.cleanup()
return json_success()
@authenticated_json_post_view
def json_get_events(request, user_profile):
return get_events_backend(request, user_profile, apply_markdown=True)
@asynchronous
@has_request_variables
def get_events_backend(request, user_profile, handler = None,
user_client = REQ(converter=get_client, default=None),
last_event_id = REQ(converter=int, default=None),
queue_id = REQ(default=None),
apply_markdown = REQ(default=False, validator=check_bool),
all_public_streams = REQ(default=False, validator=check_bool),
event_types = REQ(default=None, validator=check_list(check_string)),
dont_block = REQ(default=False, validator=check_bool),
narrow = REQ(default=[], validator=check_list(None)),
lifespan_secs = REQ(default=0, converter=int)):
if user_client is None:
user_client = request.client
was_connected = False
orig_queue_id = queue_id
if queue_id is None:
if dont_block:
client = allocate_client_descriptor(user_profile.id, user_profile.realm.id,
event_types, user_client, apply_markdown,
all_public_streams, lifespan_secs,
narrow=narrow)
queue_id = client.event_queue.id
else:
return json_error("Missing 'queue_id' argument")
else:
if last_event_id is None:
return json_error("Missing 'last_event_id' argument")
client = get_client_descriptor(queue_id)
if client is None:
return json_error("Bad event queue id: %s" % (queue_id,))
if user_profile.id != client.user_profile_id:
return json_error("You are not authorized to get events from this queue")
client.event_queue.prune(last_event_id)
was_connected = client.finish_current_handler()
if not client.event_queue.empty() or dont_block:
ret = {'events': client.event_queue.contents()}
if orig_queue_id is None:
ret['queue_id'] = queue_id
request._log_data['extra'] = "[%s/%s]" % (queue_id, len(ret["events"]))
if was_connected:
request._log_data['extra'] += " [was connected]"
return json_success(ret)
handler._request = request
if was_connected:
logging.info("Disconnected handler for queue %s (%s/%s)" % (queue_id, user_profile.email,
user_client.name))
client.connect_handler(handler)
# runtornado recognizes this special return value.
return RespondAsynchronously
| apache-2.0 |
ibm-research/SwiftHLM | tests/test_hlm.py | 1 | 5793 | # 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 json
import random
import subprocess
import unittest
import requests
import mock
from swift.common.swob import Request
from swifthlm import middleware as swifthlm
class FakeApp(object):
def __init__(self, headers=None):
if headers:
self.headers = headers
else:
self.headers = {}
def __call__(self, env, start_response):
start_response('200 OK', self.headers)
return []
class TestSwiftHLM(unittest.TestCase):
def setUp(self):
self.app = swifthlm.HlmMiddleware(FakeApp(), {})
def test_migrate(self):
subprocess.check_call = mock.Mock()
random.choice = mock.Mock(return_value='0')
environ = {'REQUEST_METHOD': 'POST'}
req = Request.blank('/v1/a/c?MIGRATE', environ=environ,
headers={'X-Storage-Token': 'AUTH_t=='})
resp = req.get_response(self.app)
subprocess.check_call.assert_called_with(
['/opt/ibm/swift-hlm-backend/migrate', 'a/c', '000000000000'])
self.assertEquals(resp.status_int, 200)
self.assertEquals(resp.body, 'Submitted MIGRATE requests.\n')
def test_recall(self):
subprocess.check_call = mock.Mock()
random.choice = mock.Mock(return_value='0')
environ = {'REQUEST_METHOD': 'POST'}
req = Request.blank('/v1/a/c?RECALL', environ=environ,
headers={'X-Storage-Token': 'AUTH_t=='})
resp = req.get_response(self.app)
subprocess.check_call.assert_called_with(
['/opt/ibm/swift-hlm-backend/recall', 'a/c', '000000000000'])
self.assertEquals(resp.status_int, 200)
self.assertEquals(resp.body, 'Submitted RECALL requests.\n')
def test_get_objectstatus(self):
subprocess.check_output = mock.Mock(
return_value='{"object": "/a/c/o", "status": "resident"}')
random.choice = mock.Mock(return_value='0')
req = Request.blank('/v1/a/c/o?STATUS')
resp = req.get_response(self.app)
subprocess.check_output.assert_called_with(
['/opt/ibm/swift-hlm-backend/status', 'a/c/o', '000000000000',
'STATUS'])
self.assertEquals(resp.status_int, 200)
self.assertIn('{"object": "/a/c/o", "status": "resident', resp.body)
def test_get_container_status(self):
class MockResponse:
def __init__(self, headers, content, status_code):
self.headers = headers
self.content = content
def content(self):
return self.content
def headers(self):
return self.headers
subprocess.check_output = mock.Mock(
return_value='{"object": "/a/c/o", "status": "resident"}')
random.choice = mock.Mock(return_value='0')
swifthlm.requests.get = mock.Mock(
return_value=MockResponse({"key1": "value1"}, "o\n", 200))
req = Request.blank('/v1/a/c?STATUS',
headers={'X-Storage-Token': 'AUTH_t=='})
resp = req.get_response(self.app)
subprocess.check_output.assert_called_with(
['/opt/ibm/swift-hlm-backend/status', 'a/c/o', '000000000000',
'STATUS'])
self.assertEquals(resp.status_int, 200)
self.assertIn('{"object": "/a/c/o", "status": "resident', resp.body)
def test_invalid_get_status_POST(self):
subprocess.check_output = mock.Mock(return_value='status output')
random.choice = mock.Mock(return_value='0')
environ = {'REQUEST_METHOD': 'POST'}
req = Request.blank('/v1/a/c/o?STATUS', environ=environ)
resp = req.get_response(self.app)
self.assertEquals(resp.status_int, 200)
self.assertEquals(resp.body, '')
def test_invalid_migrate_GET(self):
subprocess.call = mock.Mock()
random.choice = mock.Mock(return_value='0')
req = Request.blank('/v1/a/c?MIGRATE')
resp = req.get_response(self.app)
self.assertEquals(resp.status_int, 200)
self.assertEquals(resp.body, '')
def test_invalid_get_status_exception(self):
subprocess.check_output = mock.Mock(
side_effect=subprocess.CalledProcessError(1, 'cmd', 'boom!'))
random.choice = mock.Mock(return_value='0')
req = Request.blank('/v1/a/c/o?STATUS')
resp = req.get_response(self.app)
subprocess.check_output.assert_called_with(
['/opt/ibm/swift-hlm-backend/status', 'a/c/o', '000000000000',
'STATUS'])
self.assertEquals(resp.status_int, 200)
self.assertEquals(resp.body, '{"object": "/a/c/o", "status": ""}\n')
def test_filter_factory(self):
factory = swifthlm.filter_factory({'migrate_backend': '/a/b/c/migrate',
'recall_backend': '/d/e/f/recall',
'status_backend': '/g/h/i/status'})
thehlm = factory('myapp')
self.assertEqual(thehlm.migrate_backend, '/a/b/c/migrate')
self.assertEqual(thehlm.recall_backend, '/d/e/f/recall')
self.assertEqual(thehlm.status_backend, '/g/h/i/status')
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
rmfitzpatrick/ansible | lib/ansible/plugins/callback/context_demo.py | 25 | 1791 | # (C) 2012, Michael DeHaan, <michael.dehaan@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 = '''
callback: context_demo
type: aggregate
short_description: demo callback that adds play/task context
description:
- Displays some play and task context along with normal output
- This is mostly for demo purposes
version_added: "2.1"
requirements:
- whitelist in configuration
'''
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
"""
This is a very trivial example of how any callback function can get at play and task objects.
play will be 'None' for runner invocations, and task will be None for 'setup' invocations.
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'context_demo'
CALLBACK_NEEDS_WHITELIST = True
def __init__(self, *args, **kwargs):
super(CallbackModule, self).__init__(*args, **kwargs)
self.task = None
self.play = None
def v2_on_any(self, *args, **kwargs):
self._display.display("--- play: {} task: {} ---".format(getattr(self.play, 'name', None), self.task))
self._display.display(" --- ARGS ")
for i, a in enumerate(args):
self._display.display(' %s: %s' % (i, a))
self._display.display(" --- KWARGS ")
for k in kwargs:
self._display.display(' %s: %s' % (k, kwargs[k]))
def v2_playbook_on_play_start(self, play):
self.play = play
def v2_playbook_on_task_start(self, task, is_conditional):
self.task = task
| gpl-3.0 |
alephu5/Soundbyte | environment/lib/python3.3/site-packages/IPython/config/loader.py | 7 | 28718 | """A simple configuration system.
Inheritance diagram:
.. inheritance-diagram:: IPython.config.loader
:parts: 3
Authors
-------
* Brian Granger
* Fernando Perez
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import argparse
import copy
import logging
import os
import re
import sys
import json
from IPython.utils.path import filefind, get_ipython_dir
from IPython.utils import py3compat
from IPython.utils.encoding import DEFAULT_ENCODING
from IPython.utils.py3compat import unicode_type, iteritems
from IPython.utils.traitlets import HasTraits, List, Any, TraitError
#-----------------------------------------------------------------------------
# Exceptions
#-----------------------------------------------------------------------------
class ConfigError(Exception):
pass
class ConfigLoaderError(ConfigError):
pass
class ConfigFileNotFound(ConfigError):
pass
class ArgumentError(ConfigLoaderError):
pass
#-----------------------------------------------------------------------------
# Argparse fix
#-----------------------------------------------------------------------------
# Unfortunately argparse by default prints help messages to stderr instead of
# stdout. This makes it annoying to capture long help screens at the command
# line, since one must know how to pipe stderr, which many users don't know how
# to do. So we override the print_help method with one that defaults to
# stdout and use our class instead.
class ArgumentParser(argparse.ArgumentParser):
"""Simple argparse subclass that prints help to stdout by default."""
def print_help(self, file=None):
if file is None:
file = sys.stdout
return super(ArgumentParser, self).print_help(file)
print_help.__doc__ = argparse.ArgumentParser.print_help.__doc__
#-----------------------------------------------------------------------------
# Config class for holding config information
#-----------------------------------------------------------------------------
class LazyConfigValue(HasTraits):
"""Proxy object for exposing methods on configurable containers
Exposes:
- append, extend, insert on lists
- update on dicts
- update, add on sets
"""
_value = None
# list methods
_extend = List()
_prepend = List()
def append(self, obj):
self._extend.append(obj)
def extend(self, other):
self._extend.extend(other)
def prepend(self, other):
"""like list.extend, but for the front"""
self._prepend[:0] = other
_inserts = List()
def insert(self, index, other):
if not isinstance(index, int):
raise TypeError("An integer is required")
self._inserts.append((index, other))
# dict methods
# update is used for both dict and set
_update = Any()
def update(self, other):
if self._update is None:
if isinstance(other, dict):
self._update = {}
else:
self._update = set()
self._update.update(other)
# set methods
def add(self, obj):
self.update({obj})
def get_value(self, initial):
"""construct the value from the initial one
after applying any insert / extend / update changes
"""
if self._value is not None:
return self._value
value = copy.deepcopy(initial)
if isinstance(value, list):
for idx, obj in self._inserts:
value.insert(idx, obj)
value[:0] = self._prepend
value.extend(self._extend)
elif isinstance(value, dict):
if self._update:
value.update(self._update)
elif isinstance(value, set):
if self._update:
value.update(self._update)
self._value = value
return value
def to_dict(self):
"""return JSONable dict form of my data
Currently update as dict or set, extend, prepend as lists, and inserts as list of tuples.
"""
d = {}
if self._update:
d['update'] = self._update
if self._extend:
d['extend'] = self._extend
if self._prepend:
d['prepend'] = self._prepend
elif self._inserts:
d['inserts'] = self._inserts
return d
def _is_section_key(key):
"""Is a Config key a section name (does it start with a capital)?"""
if key and key[0].upper()==key[0] and not key.startswith('_'):
return True
else:
return False
class Config(dict):
"""An attribute based dict that can do smart merges."""
def __init__(self, *args, **kwds):
dict.__init__(self, *args, **kwds)
self._ensure_subconfig()
def _ensure_subconfig(self):
"""ensure that sub-dicts that should be Config objects are
casts dicts that are under section keys to Config objects,
which is necessary for constructing Config objects from dict literals.
"""
for key in self:
obj = self[key]
if _is_section_key(key) \
and isinstance(obj, dict) \
and not isinstance(obj, Config):
setattr(self, key, Config(obj))
def _merge(self, other):
"""deprecated alias, use Config.merge()"""
self.merge(other)
def merge(self, other):
"""merge another config object into this one"""
to_update = {}
for k, v in iteritems(other):
if k not in self:
to_update[k] = copy.deepcopy(v)
else: # I have this key
if isinstance(v, Config) and isinstance(self[k], Config):
# Recursively merge common sub Configs
self[k].merge(v)
else:
# Plain updates for non-Configs
to_update[k] = copy.deepcopy(v)
self.update(to_update)
def __contains__(self, key):
# allow nested contains of the form `"Section.key" in config`
if '.' in key:
first, remainder = key.split('.', 1)
if first not in self:
return False
return remainder in self[first]
return super(Config, self).__contains__(key)
# .has_key is deprecated for dictionaries.
has_key = __contains__
def _has_section(self, key):
return _is_section_key(key) and key in self
def copy(self):
return type(self)(dict.copy(self))
def __copy__(self):
return self.copy()
def __deepcopy__(self, memo):
import copy
return type(self)(copy.deepcopy(list(self.items())))
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
if _is_section_key(key):
c = Config()
dict.__setitem__(self, key, c)
return c
elif not key.startswith('_'):
# undefined, create lazy value, used for container methods
v = LazyConfigValue()
dict.__setitem__(self, key, v)
return v
else:
raise KeyError
def __setitem__(self, key, value):
if _is_section_key(key):
if not isinstance(value, Config):
raise ValueError('values whose keys begin with an uppercase '
'char must be Config instances: %r, %r' % (key, value))
dict.__setitem__(self, key, value)
def __getattr__(self, key):
if key.startswith('__'):
return dict.__getattr__(self, key)
try:
return self.__getitem__(key)
except KeyError as e:
raise AttributeError(e)
def __setattr__(self, key, value):
if key.startswith('__'):
return dict.__setattr__(self, key, value)
try:
self.__setitem__(key, value)
except KeyError as e:
raise AttributeError(e)
def __delattr__(self, key):
if key.startswith('__'):
return dict.__delattr__(self, key)
try:
dict.__delitem__(self, key)
except KeyError as e:
raise AttributeError(e)
#-----------------------------------------------------------------------------
# Config loading classes
#-----------------------------------------------------------------------------
class ConfigLoader(object):
"""A object for loading configurations from just about anywhere.
The resulting configuration is packaged as a :class:`Config`.
Notes
-----
A :class:`ConfigLoader` does one thing: load a config from a source
(file, command line arguments) and returns the data as a :class:`Config` object.
There are lots of things that :class:`ConfigLoader` does not do. It does
not implement complex logic for finding config files. It does not handle
default values or merge multiple configs. These things need to be
handled elsewhere.
"""
def _log_default(self):
from IPython.config.application import Application
if Application.initialized():
return Application.instance().log
else:
return logging.getLogger()
def __init__(self, log=None):
"""A base class for config loaders.
log : instance of :class:`logging.Logger` to use.
By default loger of :meth:`IPython.config.application.Application.instance()`
will be used
Examples
--------
>>> cl = ConfigLoader()
>>> config = cl.load_config()
>>> config
{}
"""
self.clear()
if log is None:
self.log = self._log_default()
self.log.debug('Using default logger')
else:
self.log = log
def clear(self):
self.config = Config()
def load_config(self):
"""Load a config from somewhere, return a :class:`Config` instance.
Usually, this will cause self.config to be set and then returned.
However, in most cases, :meth:`ConfigLoader.clear` should be called
to erase any previous state.
"""
self.clear()
return self.config
class FileConfigLoader(ConfigLoader):
"""A base class for file based configurations.
As we add more file based config loaders, the common logic should go
here.
"""
def __init__(self, filename, path=None, **kw):
"""Build a config loader for a filename and path.
Parameters
----------
filename : str
The file name of the config file.
path : str, list, tuple
The path to search for the config file on, or a sequence of
paths to try in order.
"""
super(FileConfigLoader, self).__init__(**kw)
self.filename = filename
self.path = path
self.full_filename = ''
def _find_file(self):
"""Try to find the file by searching the paths."""
self.full_filename = filefind(self.filename, self.path)
class JSONFileConfigLoader(FileConfigLoader):
"""A Json file loader for config"""
def load_config(self):
"""Load the config from a file and return it as a Config object."""
self.clear()
try:
self._find_file()
except IOError as e:
raise ConfigFileNotFound(str(e))
dct = self._read_file_as_dict()
self.config = self._convert_to_config(dct)
return self.config
def _read_file_as_dict(self):
with open(self.full_filename) as f:
return json.load(f)
def _convert_to_config(self, dictionary):
if 'version' in dictionary:
version = dictionary.pop('version')
else:
version = 1
self.log.warn("Unrecognized JSON config file version, assuming version {}".format(version))
if version == 1:
return Config(dictionary)
else:
raise ValueError('Unknown version of JSON config file: {version}'.format(version=version))
class PyFileConfigLoader(FileConfigLoader):
"""A config loader for pure python files.
This is responsible for locating a Python config file by filename and
path, then executing it to construct a Config object.
"""
def load_config(self):
"""Load the config from a file and return it as a Config object."""
self.clear()
try:
self._find_file()
except IOError as e:
raise ConfigFileNotFound(str(e))
self._read_file_as_dict()
return self.config
def _read_file_as_dict(self):
"""Load the config file into self.config, with recursive loading."""
# This closure is made available in the namespace that is used
# to exec the config file. It allows users to call
# load_subconfig('myconfig.py') to load config files recursively.
# It needs to be a closure because it has references to self.path
# and self.config. The sub-config is loaded with the same path
# as the parent, but it uses an empty config which is then merged
# with the parents.
# If a profile is specified, the config file will be loaded
# from that profile
def load_subconfig(fname, profile=None):
# import here to prevent circular imports
from IPython.core.profiledir import ProfileDir, ProfileDirError
if profile is not None:
try:
profile_dir = ProfileDir.find_profile_dir_by_name(
get_ipython_dir(),
profile,
)
except ProfileDirError:
return
path = profile_dir.location
else:
path = self.path
loader = PyFileConfigLoader(fname, path)
try:
sub_config = loader.load_config()
except ConfigFileNotFound:
# Pass silently if the sub config is not there. This happens
# when a user s using a profile, but not the default config.
pass
else:
self.config.merge(sub_config)
# Again, this needs to be a closure and should be used in config
# files to get the config being loaded.
def get_config():
return self.config
namespace = dict(
load_subconfig=load_subconfig,
get_config=get_config,
__file__=self.full_filename,
)
fs_encoding = sys.getfilesystemencoding() or 'ascii'
conf_filename = self.full_filename.encode(fs_encoding)
py3compat.execfile(conf_filename, namespace)
class CommandLineConfigLoader(ConfigLoader):
"""A config loader for command line arguments.
As we add more command line based loaders, the common logic should go
here.
"""
def _exec_config_str(self, lhs, rhs):
"""execute self.config.<lhs> = <rhs>
* expands ~ with expanduser
* tries to assign with raw eval, otherwise assigns with just the string,
allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not*
equivalent are `--C.a=4` and `--C.a='4'`.
"""
rhs = os.path.expanduser(rhs)
try:
# Try to see if regular Python syntax will work. This
# won't handle strings as the quote marks are removed
# by the system shell.
value = eval(rhs)
except (NameError, SyntaxError):
# This case happens if the rhs is a string.
value = rhs
exec(u'self.config.%s = value' % lhs)
def _load_flag(self, cfg):
"""update self.config from a flag, which can be a dict or Config"""
if isinstance(cfg, (dict, Config)):
# don't clobber whole config sections, update
# each section from config:
for sec,c in iteritems(cfg):
self.config[sec].update(c)
else:
raise TypeError("Invalid flag: %r" % cfg)
# raw --identifier=value pattern
# but *also* accept '-' as wordsep, for aliases
# accepts: --foo=a
# --Class.trait=value
# --alias-name=value
# rejects: -foo=value
# --foo
# --Class.trait
kv_pattern = re.compile(r'\-\-[A-Za-z][\w\-]*(\.[\w\-]+)*\=.*')
# just flags, no assignments, with two *or one* leading '-'
# accepts: --foo
# -foo-bar-again
# rejects: --anything=anything
# --two.word
flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$')
class KeyValueConfigLoader(CommandLineConfigLoader):
"""A config loader that loads key value pairs from the command line.
This allows command line options to be gives in the following form::
ipython --profile="foo" --InteractiveShell.autocall=False
"""
def __init__(self, argv=None, aliases=None, flags=None, **kw):
"""Create a key value pair config loader.
Parameters
----------
argv : list
A list that has the form of sys.argv[1:] which has unicode
elements of the form u"key=value". If this is None (default),
then sys.argv[1:] will be used.
aliases : dict
A dict of aliases for configurable traits.
Keys are the short aliases, Values are the resolved trait.
Of the form: `{'alias' : 'Configurable.trait'}`
flags : dict
A dict of flags, keyed by str name. Vaues can be Config objects,
dicts, or "key=value" strings. If Config or dict, when the flag
is triggered, The flag is loaded as `self.config.update(m)`.
Returns
-------
config : Config
The resulting Config object.
Examples
--------
>>> from IPython.config.loader import KeyValueConfigLoader
>>> cl = KeyValueConfigLoader()
>>> d = cl.load_config(["--A.name='brian'","--B.number=0"])
>>> sorted(d.items())
[('A', {'name': 'brian'}), ('B', {'number': 0})]
"""
super(KeyValueConfigLoader, self).__init__(**kw)
if argv is None:
argv = sys.argv[1:]
self.argv = argv
self.aliases = aliases or {}
self.flags = flags or {}
def clear(self):
super(KeyValueConfigLoader, self).clear()
self.extra_args = []
def _decode_argv(self, argv, enc=None):
"""decode argv if bytes, using stin.encoding, falling back on default enc"""
uargv = []
if enc is None:
enc = DEFAULT_ENCODING
for arg in argv:
if not isinstance(arg, unicode_type):
# only decode if not already decoded
arg = arg.decode(enc)
uargv.append(arg)
return uargv
def load_config(self, argv=None, aliases=None, flags=None):
"""Parse the configuration and generate the Config object.
After loading, any arguments that are not key-value or
flags will be stored in self.extra_args - a list of
unparsed command-line arguments. This is used for
arguments such as input files or subcommands.
Parameters
----------
argv : list, optional
A list that has the form of sys.argv[1:] which has unicode
elements of the form u"key=value". If this is None (default),
then self.argv will be used.
aliases : dict
A dict of aliases for configurable traits.
Keys are the short aliases, Values are the resolved trait.
Of the form: `{'alias' : 'Configurable.trait'}`
flags : dict
A dict of flags, keyed by str name. Values can be Config objects
or dicts. When the flag is triggered, The config is loaded as
`self.config.update(cfg)`.
"""
self.clear()
if argv is None:
argv = self.argv
if aliases is None:
aliases = self.aliases
if flags is None:
flags = self.flags
# ensure argv is a list of unicode strings:
uargv = self._decode_argv(argv)
for idx,raw in enumerate(uargv):
# strip leading '-'
item = raw.lstrip('-')
if raw == '--':
# don't parse arguments after '--'
# this is useful for relaying arguments to scripts, e.g.
# ipython -i foo.py --matplotlib=qt -- args after '--' go-to-foo.py
self.extra_args.extend(uargv[idx+1:])
break
if kv_pattern.match(raw):
lhs,rhs = item.split('=',1)
# Substitute longnames for aliases.
if lhs in aliases:
lhs = aliases[lhs]
if '.' not in lhs:
# probably a mistyped alias, but not technically illegal
self.log.warn("Unrecognized alias: '%s', it will probably have no effect.", raw)
try:
self._exec_config_str(lhs, rhs)
except Exception:
raise ArgumentError("Invalid argument: '%s'" % raw)
elif flag_pattern.match(raw):
if item in flags:
cfg,help = flags[item]
self._load_flag(cfg)
else:
raise ArgumentError("Unrecognized flag: '%s'"%raw)
elif raw.startswith('-'):
kv = '--'+item
if kv_pattern.match(kv):
raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv))
else:
raise ArgumentError("Invalid argument: '%s'"%raw)
else:
# keep all args that aren't valid in a list,
# in case our parent knows what to do with them.
self.extra_args.append(item)
return self.config
class ArgParseConfigLoader(CommandLineConfigLoader):
"""A loader that uses the argparse module to load from the command line."""
def __init__(self, argv=None, aliases=None, flags=None, log=None, *parser_args, **parser_kw):
"""Create a config loader for use with argparse.
Parameters
----------
argv : optional, list
If given, used to read command-line arguments from, otherwise
sys.argv[1:] is used.
parser_args : tuple
A tuple of positional arguments that will be passed to the
constructor of :class:`argparse.ArgumentParser`.
parser_kw : dict
A tuple of keyword arguments that will be passed to the
constructor of :class:`argparse.ArgumentParser`.
Returns
-------
config : Config
The resulting Config object.
"""
super(CommandLineConfigLoader, self).__init__(log=log)
self.clear()
if argv is None:
argv = sys.argv[1:]
self.argv = argv
self.aliases = aliases or {}
self.flags = flags or {}
self.parser_args = parser_args
self.version = parser_kw.pop("version", None)
kwargs = dict(argument_default=argparse.SUPPRESS)
kwargs.update(parser_kw)
self.parser_kw = kwargs
def load_config(self, argv=None, aliases=None, flags=None):
"""Parse command line arguments and return as a Config object.
Parameters
----------
args : optional, list
If given, a list with the structure of sys.argv[1:] to parse
arguments from. If not given, the instance's self.argv attribute
(given at construction time) is used."""
self.clear()
if argv is None:
argv = self.argv
if aliases is None:
aliases = self.aliases
if flags is None:
flags = self.flags
self._create_parser(aliases, flags)
self._parse_args(argv)
self._convert_to_config()
return self.config
def get_extra_args(self):
if hasattr(self, 'extra_args'):
return self.extra_args
else:
return []
def _create_parser(self, aliases=None, flags=None):
self.parser = ArgumentParser(*self.parser_args, **self.parser_kw)
self._add_arguments(aliases, flags)
def _add_arguments(self, aliases=None, flags=None):
raise NotImplementedError("subclasses must implement _add_arguments")
def _parse_args(self, args):
"""self.parser->self.parsed_data"""
# decode sys.argv to support unicode command-line options
enc = DEFAULT_ENCODING
uargs = [py3compat.cast_unicode(a, enc) for a in args]
self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
def _convert_to_config(self):
"""self.parsed_data->self.config"""
for k, v in iteritems(vars(self.parsed_data)):
exec("self.config.%s = v"%k, locals(), globals())
class KVArgParseConfigLoader(ArgParseConfigLoader):
"""A config loader that loads aliases and flags with argparse,
but will use KVLoader for the rest. This allows better parsing
of common args, such as `ipython -c 'print 5'`, but still gets
arbitrary config with `ipython --InteractiveShell.use_readline=False`"""
def _add_arguments(self, aliases=None, flags=None):
self.alias_flags = {}
# print aliases, flags
if aliases is None:
aliases = self.aliases
if flags is None:
flags = self.flags
paa = self.parser.add_argument
for key,value in iteritems(aliases):
if key in flags:
# flags
nargs = '?'
else:
nargs = None
if len(key) is 1:
paa('-'+key, '--'+key, type=unicode_type, dest=value, nargs=nargs)
else:
paa('--'+key, type=unicode_type, dest=value, nargs=nargs)
for key, (value, help) in iteritems(flags):
if key in self.aliases:
#
self.alias_flags[self.aliases[key]] = value
continue
if len(key) is 1:
paa('-'+key, '--'+key, action='append_const', dest='_flags', const=value)
else:
paa('--'+key, action='append_const', dest='_flags', const=value)
def _convert_to_config(self):
"""self.parsed_data->self.config, parse unrecognized extra args via KVLoader."""
# remove subconfigs list from namespace before transforming the Namespace
if '_flags' in self.parsed_data:
subcs = self.parsed_data._flags
del self.parsed_data._flags
else:
subcs = []
for k, v in iteritems(vars(self.parsed_data)):
if v is None:
# it was a flag that shares the name of an alias
subcs.append(self.alias_flags[k])
else:
# eval the KV assignment
self._exec_config_str(k, v)
for subc in subcs:
self._load_flag(subc)
if self.extra_args:
sub_parser = KeyValueConfigLoader(log=self.log)
sub_parser.load_config(self.extra_args)
self.config.merge(sub_parser.config)
self.extra_args = sub_parser.extra_args
def load_pyconfig_files(config_files, path):
"""Load multiple Python config files, merging each of them in turn.
Parameters
==========
config_files : list of str
List of config files names to load and merge into the config.
path : unicode
The full path to the location of the config files.
"""
config = Config()
for cf in config_files:
loader = PyFileConfigLoader(cf, path=path)
try:
next_config = loader.load_config()
except ConfigFileNotFound:
pass
except:
raise
else:
config.merge(next_config)
return config
| gpl-3.0 |
tadamic/sokoenginepy | src/sokoenginepy/input_output/sok_file_format.py | 1 | 17681 | import os
import re
from enum import Enum
from .. import utilities
from ..board import VariantBoard
from ..snapshot import Snapshot
from ..tessellation import Tessellation
from .puzzle import Puzzle, PuzzleSnapshot
class SOKFileFormat:
@classmethod
def read(cls, src_stream, dest_collection, tessellation_hint=Tessellation.SOKOBAN):
SOKReader(src_stream, dest_collection, tessellation_hint).read()
@classmethod
def write(cls, puzzle_or_collection, dest_stream):
SOKWriter(dest_stream).write(puzzle_or_collection)
class SOKTags(str, Enum):
AUTHOR = "Author"
TITLE = "Title"
GOALORDER = "goalorder"
BOXORDER = "boxorder"
SOLVER = "Solver"
VARIANT = "Game"
CREATED_AT = "Date created"
SNAPSHOT_CREATED_AT = "Date"
UPDATED_AT = "Date of last change"
DURATION = "Time"
RAW_FILE_NOTES = "::"
TAG_DELIMITERS = "=:"
class SOKReader:
def __init__(self, src_stream, dest_collection, tessellation_hint):
self.coll_header_tessellation_hint = None
self.src_stream = src_stream
self.dest_collection = dest_collection
self.supplied_tessellation_hint = str(
Tessellation.instance_from(tessellation_hint).value
).lower()
def read(self):
self.src_stream.seek(0, 0)
self.dest_collection.clear()
self._split_input(self.src_stream.readlines())
self._parse_title_lines()
self._parse_collection_notes()
self._parse_puzzles()
def _split_input(self, input_lines):
first_board_line = utilities.first_index_of(
input_lines, VariantBoard.is_board_string
)
if first_board_line is not None:
self.dest_collection.notes = input_lines[:first_board_line]
remaining_lines = input_lines[first_board_line:]
else:
self.dest_collection.notes = input_lines
remaining_lines = []
self._split_puzzle_chunks(remaining_lines)
self._split_snapshot_chunks()
def _split_puzzle_chunks(self, lines):
remaining_lines = lines
while len(remaining_lines) > 0:
puzzle = Puzzle()
first_note_line = utilities.first_index_of(
remaining_lines, lambda x: not VariantBoard.is_board_string(x)
)
if first_note_line is not None:
puzzle.board = "".join(remaining_lines[:first_note_line])
remaining_lines = remaining_lines[first_note_line:]
else:
puzzle.board = "".join(remaining_lines)
remaining_lines = []
if len(remaining_lines) > 0:
first_board_line = utilities.first_index_of(
remaining_lines, VariantBoard.is_board_string
)
if first_board_line is not None:
puzzle.notes = remaining_lines[:first_board_line]
remaining_lines = remaining_lines[first_board_line:]
else:
puzzle.notes = remaining_lines
remaining_lines = []
else:
puzzle.notes = []
self.dest_collection.puzzles.append(puzzle)
def _split_snapshot_chunks(self):
for puzzle in self.dest_collection.puzzles:
remaining_lines = puzzle.notes
first_moves_line = utilities.first_index_of(
remaining_lines, Snapshot.is_snapshot_string
)
if first_moves_line is not None:
puzzle.notes = remaining_lines[:first_moves_line]
remaining_lines = remaining_lines[first_moves_line:]
else:
puzzle.notes = remaining_lines
remaining_lines = []
puzzle.snapshots = []
while len(remaining_lines) > 0:
snap = PuzzleSnapshot()
first_note_line = utilities.first_index_of(
remaining_lines, lambda x: not Snapshot.is_snapshot_string(x)
)
if first_note_line is not None:
snap.moves = "".join(
moves_line.strip()
for moves_line in remaining_lines[:first_note_line]
)
remaining_lines = remaining_lines[first_note_line:]
else:
snap.moves = "".join(
moves_line.strip() for moves_line in remaining_lines
)
remaining_lines = []
if len(remaining_lines) > 0:
first_moves_line = utilities.first_index_of(
remaining_lines, Snapshot.is_snapshot_string
)
if first_moves_line is not None:
snap.notes = remaining_lines[:first_moves_line]
remaining_lines = remaining_lines[first_moves_line:]
else:
snap.notes = remaining_lines
remaining_lines = []
else:
snap.notes = []
puzzle.snapshots.append(snap)
_tag_splitter = re.compile("|".join(map(re.escape, list(SOKTags.TAG_DELIMITERS))))
def _get_tag_data(self, tag, line):
# TODO: If tag data contains split char, it will not get collected
# ie. "Date created: 2015-02-03 13:42:32"
components = self._tag_splitter.split(str(line))
if components[0].strip().lower() == tag.strip().lower():
return components[1].strip()
return None
@staticmethod
def _is_tagged_as(tag, line):
return any(
chr in list(SOKTags.TAG_DELIMITERS) for chr in line
) and line.lstrip().lower().startswith(tag.strip().lower())
def _is_collection_tag_line(self, line):
return any(
self._is_tagged_as(tag, line)
for tag in (
SOKTags.AUTHOR,
SOKTags.TITLE,
SOKTags.VARIANT,
SOKTags.CREATED_AT,
SOKTags.UPDATED_AT,
)
)
def _is_puzzle_tag_line(self, line):
return any(
self._is_tagged_as(tag, line)
for tag in (
SOKTags.AUTHOR,
SOKTags.VARIANT,
SOKTags.TITLE,
SOKTags.BOXORDER,
SOKTags.GOALORDER,
)
)
def _is_snapshot_tag_line(self, line):
return any(
self._is_tagged_as(tag, line)
for tag in (
SOKTags.AUTHOR,
SOKTags.SOLVER,
SOKTags.CREATED_AT,
SOKTags.SNAPSHOT_CREATED_AT,
SOKTags.DURATION,
)
)
@staticmethod
def _is_raw_file_notes_line(line):
return line.lstrip().startswith(SOKTags.RAW_FILE_NOTES)
def _notes_before_puzzle(self, puzzle_index):
if puzzle_index == 0:
return self.dest_collection.notes
prevoius_puzzle = self.dest_collection.puzzles[puzzle_index - 1]
if len(prevoius_puzzle.snapshots) > 0:
return prevoius_puzzle.snapshots[-1].notes
return prevoius_puzzle.notes
def _notes_before_snapshot(self, puzzle_index, snapshot_index):
puzzle = self.dest_collection.puzzles[puzzle_index]
if snapshot_index == 0:
return puzzle.notes
return puzzle.snapshots[snapshot_index - 1].notes
@staticmethod
def _get_and_remove_title_line(notes):
"""
:: Titles ::
:: A title line is the last non-blank text line before ::
:: a puzzle or a game, provided the line is preceded ::
:: by a blank line or it is the only text line at this ::
:: position in the file. ::
:: ::
:: Title lines are optional unless a single or a last ::
:: text line from a preceding puzzle, game, or file ::
:: header can be mistaken for a title line. ::
"""
candidate_index = utilities.last_index_of(
notes, lambda x: not utilities.is_blank(x)
)
if candidate_index is None:
return ""
preceeding_index = None
if candidate_index > 0:
preceeding_index = candidate_index - 1
following_index = None
if candidate_index < len(notes) - 1:
following_index = candidate_index + 1
preceeding_ok = (
utilities.is_blank(notes[preceeding_index]) if preceeding_index else True
)
following_ok = (
utilities.is_blank(notes[following_index]) if following_index else True
)
if preceeding_ok and following_ok:
title_line = notes[candidate_index].strip()
del notes[candidate_index]
return title_line
return ""
def _parse_title_lines(self):
for puzzle_index, puzzle in enumerate(self.dest_collection.puzzles):
puzzle.title = self._get_and_remove_title_line(
self._notes_before_puzzle(puzzle_index)
)
for snapshot_index, snap in enumerate(puzzle.snapshots):
snap.title = self._get_and_remove_title_line(
self._notes_before_snapshot(puzzle_index, snapshot_index)
)
def _parse_collection_notes(self):
self.coll_header_tessellation_hint = None
remaining_lines = []
for line in self.dest_collection.notes:
if self._is_collection_tag_line(line):
self.coll_header_tessellation_hint = (
self.coll_header_tessellation_hint
or self._get_tag_data(SOKTags.VARIANT, line)
)
self.dest_collection.title = (
self.dest_collection.title
or self._get_tag_data(SOKTags.TITLE, line)
)
self.dest_collection.author = (
self.dest_collection.author
or self._get_tag_data(SOKTags.AUTHOR, line)
)
self.dest_collection.created_at = (
self.dest_collection.created_at
or self._get_tag_data(SOKTags.CREATED_AT, line)
)
self.dest_collection.updated_at = (
self.dest_collection.updated_at
or self._get_tag_data(SOKTags.UPDATED_AT, line)
)
elif not self._is_raw_file_notes_line(line):
remaining_lines.append(line)
if self.coll_header_tessellation_hint:
self.coll_header_tessellation_hint = (
self.coll_header_tessellation_hint.strip().lower()
)
self.dest_collection.notes = self._cleanup_whitespace(remaining_lines)
def _parse_puzzles(self):
for puzzle in self.dest_collection.puzzles:
remaining_lines = []
tess = None
for line in puzzle.notes:
if self._is_puzzle_tag_line(line):
tess = tess or self._get_tag_data(SOKTags.VARIANT, line)
puzzle.title = puzzle.title or self._get_tag_data(
SOKTags.TITLE, line
)
puzzle.author = puzzle.author or self._get_tag_data(
SOKTags.AUTHOR, line
)
puzzle.boxorder = puzzle.boxorder or self._get_tag_data(
SOKTags.BOXORDER, line
)
puzzle.goalorder = puzzle.goalorder or self._get_tag_data(
SOKTags.GOALORDER, line
)
else:
remaining_lines.append(line)
puzzle.notes = self._cleanup_whitespace(remaining_lines)
if tess is not None:
puzzle.tessellation = tess
elif self.coll_header_tessellation_hint is not None:
puzzle.tessellation = self.coll_header_tessellation_hint
elif self.supplied_tessellation_hint is not None:
puzzle.tessellation = self.supplied_tessellation_hint
self._parse_snapshots(puzzle)
def _parse_snapshots(self, puzzle):
for snap in puzzle.snapshots:
remaining_lines = []
for line in snap.notes:
if self._is_snapshot_tag_line(line):
snap.solver = snap.solver or self._get_tag_data(
SOKTags.AUTHOR, line
)
snap.solver = snap.solver or self._get_tag_data(
SOKTags.SOLVER, line
)
snap.created_at = snap.created_at or self._get_tag_data(
SOKTags.CREATED_AT, line
)
snap.duration = snap.duration or self._get_tag_data(
SOKTags.DURATION, line
)
snap.created_at = snap.created_at or self._get_tag_data(
SOKTags.SNAPSHOT_CREATED_AT, line
)
else:
remaining_lines.append(line)
snap.notes = self._cleanup_whitespace(remaining_lines)
snap.tessellation = puzzle.tessellation
@staticmethod
def _cleanup_whitespace(lst):
i = utilities.first_index_of(lst, lambda x: not utilities.is_blank(x))
if i is None:
return ""
lst = lst[i:]
i = utilities.last_index_of(lst, lambda x: not utilities.is_blank(x))
if i is not None:
lst = lst[: i + 1]
return "\n".join(line.strip() for line in lst)
class SOKWriter:
def __init__(self, dest_stream):
self.dest_stream = dest_stream
def write(self, puzzle_or_collection):
if isinstance(puzzle_or_collection, Puzzle):
self._write_puzzle(puzzle_or_collection)
else:
self._write_collection(puzzle_or_collection)
def _write_collection(self, puzzle_collection):
self._write_collection_header(puzzle_collection)
for puzzle in puzzle_collection.puzzles:
self._write_puzzle(puzzle)
def _write_puzzle(self, puzzle):
if utilities.is_blank(puzzle.board):
return
if not utilities.is_blank(puzzle.title):
self.dest_stream.write(puzzle.title.strip() + "\n\n")
self.dest_stream.write(puzzle.board.rstrip() + "\n\n")
written = False
if puzzle.tessellation != Tessellation.SOKOBAN:
written = (
self._write_tagged(SOKTags.VARIANT, str(puzzle.tessellation)) or written
)
if not utilities.is_blank(puzzle.boxorder) and not utilities.is_blank(
puzzle.goalorder
):
written = self._write_tagged(SOKTags.BOXORDER, puzzle.boxorder) or written
written = self._write_tagged(SOKTags.GOALORDER, puzzle.goalorder) or written
if not utilities.is_blank(puzzle.notes):
self.dest_stream.write(puzzle.notes.rstrip() + "\n")
written = True
if written:
self.dest_stream.write("\n")
for snap in puzzle.snapshots:
self._write_snapshot(snap)
def _write_collection_header(self, puzzle_collection):
for line in open(
os.path.join(utilities.RESOURCES_ROOT, "SOK_format_specification.txt")
):
self.dest_stream.write(line.rstrip() + "\n")
self._write_tagged(
SOKTags.CREATED_AT,
puzzle_collection.created_at.strip() or utilities.utcnow().isoformat(),
)
self._write_tagged(
SOKTags.UPDATED_AT,
puzzle_collection.updated_at.strip() or utilities.utcnow().isoformat(),
)
self.dest_stream.write(
"::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::" + "\n\n"
)
written = False
written = (
self._write_tagged(SOKTags.AUTHOR, puzzle_collection.author) or written
)
written = self._write_tagged(SOKTags.TITLE, puzzle_collection.title) or written
if not utilities.is_blank(puzzle_collection.notes):
self.dest_stream.write(puzzle_collection.notes.rstrip() + "\n")
written = True
if written:
self.dest_stream.write("\n")
def _write_snapshot(self, snap):
if utilities.is_blank(snap.moves):
return
if not utilities.is_blank(snap.title):
self.dest_stream.write(snap.title.strip() + "\n\n")
self.dest_stream.write(snap.moves.strip() + "\n\n")
written = True
written = self._write_tagged(SOKTags.SOLVER, snap.solver) or written
written = (
self._write_tagged(SOKTags.SNAPSHOT_CREATED_AT, snap.created_at) or written
)
written = self._write_tagged(SOKTags.DURATION, snap.duration) or written
if not utilities.is_blank(snap.notes):
self.dest_stream.write(snap.notes.rstrip() + "\n")
written = True
if written:
self.dest_stream.write("\n")
def _write_tagged(self, tag, content):
if utilities.is_blank(content) or utilities.is_blank(tag):
return False
self.dest_stream.write(tag.strip() + ": " + content.rstrip() + "\n")
return True
| gpl-3.0 |
d3banjan/polyamide | webdev/lib/python2.7/site-packages/django/http/response.py | 82 | 18349 | from __future__ import unicode_literals
import datetime
import json
import re
import sys
import time
from email.header import Header
from django.conf import settings
from django.core import signals, signing
from django.core.exceptions import DisallowedRedirect
from django.core.serializers.json import DjangoJSONEncoder
from django.http.cookie import SimpleCookie
from django.utils import six, timezone
from django.utils.encoding import (
force_bytes, force_str, force_text, iri_to_uri,
)
from django.utils.http import cookie_date
from django.utils.six.moves import map
from django.utils.six.moves.urllib.parse import urlparse
# See http://www.iana.org/assignments/http-status-codes
REASON_PHRASES = {
100: 'CONTINUE',
101: 'SWITCHING PROTOCOLS',
102: 'PROCESSING',
200: 'OK',
201: 'CREATED',
202: 'ACCEPTED',
203: 'NON-AUTHORITATIVE INFORMATION',
204: 'NO CONTENT',
205: 'RESET CONTENT',
206: 'PARTIAL CONTENT',
207: 'MULTI-STATUS',
208: 'ALREADY REPORTED',
226: 'IM USED',
300: 'MULTIPLE CHOICES',
301: 'MOVED PERMANENTLY',
302: 'FOUND',
303: 'SEE OTHER',
304: 'NOT MODIFIED',
305: 'USE PROXY',
306: 'RESERVED',
307: 'TEMPORARY REDIRECT',
308: 'PERMANENT REDIRECT',
400: 'BAD REQUEST',
401: 'UNAUTHORIZED',
402: 'PAYMENT REQUIRED',
403: 'FORBIDDEN',
404: 'NOT FOUND',
405: 'METHOD NOT ALLOWED',
406: 'NOT ACCEPTABLE',
407: 'PROXY AUTHENTICATION REQUIRED',
408: 'REQUEST TIMEOUT',
409: 'CONFLICT',
410: 'GONE',
411: 'LENGTH REQUIRED',
412: 'PRECONDITION FAILED',
413: 'REQUEST ENTITY TOO LARGE',
414: 'REQUEST-URI TOO LONG',
415: 'UNSUPPORTED MEDIA TYPE',
416: 'REQUESTED RANGE NOT SATISFIABLE',
417: 'EXPECTATION FAILED',
418: "I'M A TEAPOT",
422: 'UNPROCESSABLE ENTITY',
423: 'LOCKED',
424: 'FAILED DEPENDENCY',
426: 'UPGRADE REQUIRED',
428: 'PRECONDITION REQUIRED',
429: 'TOO MANY REQUESTS',
431: 'REQUEST HEADER FIELDS TOO LARGE',
500: 'INTERNAL SERVER ERROR',
501: 'NOT IMPLEMENTED',
502: 'BAD GATEWAY',
503: 'SERVICE UNAVAILABLE',
504: 'GATEWAY TIMEOUT',
505: 'HTTP VERSION NOT SUPPORTED',
506: 'VARIANT ALSO NEGOTIATES',
507: 'INSUFFICIENT STORAGE',
508: 'LOOP DETECTED',
510: 'NOT EXTENDED',
511: 'NETWORK AUTHENTICATION REQUIRED',
}
_charset_from_content_type_re = re.compile(r';\s*charset=(?P<charset>[^\s;]+)', re.I)
class BadHeaderError(ValueError):
pass
class HttpResponseBase(six.Iterator):
"""
An HTTP response base class with dictionary-accessed headers.
This class doesn't handle content. It should not be used directly.
Use the HttpResponse and StreamingHttpResponse subclasses instead.
"""
status_code = 200
reason_phrase = None # Use default reason phrase for status code.
def __init__(self, content_type=None, status=None, reason=None, charset=None):
# _headers is a mapping of the lower-case name to the original case of
# the header (required for working with legacy systems) and the header
# value. Both the name of the header and its value are ASCII strings.
self._headers = {}
self._closable_objects = []
# This parameter is set by the handler. It's necessary to preserve the
# historical behavior of request_finished.
self._handler_class = None
self.cookies = SimpleCookie()
self.closed = False
if status is not None:
self.status_code = status
if reason is not None:
self.reason_phrase = reason
elif self.reason_phrase is None:
self.reason_phrase = REASON_PHRASES.get(self.status_code,
'UNKNOWN STATUS CODE')
self._charset = charset
if content_type is None:
content_type = '%s; charset=%s' % (settings.DEFAULT_CONTENT_TYPE,
self.charset)
self['Content-Type'] = content_type
@property
def charset(self):
if self._charset is not None:
return self._charset
content_type = self.get('Content-Type', '')
matched = _charset_from_content_type_re.search(content_type)
if matched:
# Extract the charset and strip its double quotes
return matched.group('charset').replace('"', '')
return settings.DEFAULT_CHARSET
@charset.setter
def charset(self, value):
self._charset = value
def serialize_headers(self):
"""HTTP headers as a bytestring."""
def to_bytes(val, encoding):
return val if isinstance(val, bytes) else val.encode(encoding)
headers = [
(b': '.join([to_bytes(key, 'ascii'), to_bytes(value, 'latin-1')]))
for key, value in self._headers.values()
]
return b'\r\n'.join(headers)
if six.PY3:
__bytes__ = serialize_headers
else:
__str__ = serialize_headers
def _convert_to_charset(self, value, charset, mime_encode=False):
"""Converts headers key/value to ascii/latin-1 native strings.
`charset` must be 'ascii' or 'latin-1'. If `mime_encode` is True and
`value` can't be represented in the given charset, MIME-encoding
is applied.
"""
if not isinstance(value, (bytes, six.text_type)):
value = str(value)
if ((isinstance(value, bytes) and (b'\n' in value or b'\r' in value)) or
isinstance(value, six.text_type) and ('\n' in value or '\r' in value)):
raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
try:
if six.PY3:
if isinstance(value, str):
# Ensure string is valid in given charset
value.encode(charset)
else:
# Convert bytestring using given charset
value = value.decode(charset)
else:
if isinstance(value, str):
# Ensure string is valid in given charset
value.decode(charset)
else:
# Convert unicode string to given charset
value = value.encode(charset)
except UnicodeError as e:
if mime_encode:
# Wrapping in str() is a workaround for #12422 under Python 2.
value = str(Header(value, 'utf-8', maxlinelen=sys.maxsize).encode())
else:
e.reason += ', HTTP response headers must be in %s format' % charset
raise
return value
def __setitem__(self, header, value):
header = self._convert_to_charset(header, 'ascii')
value = self._convert_to_charset(value, 'latin-1', mime_encode=True)
self._headers[header.lower()] = (header, value)
def __delitem__(self, header):
try:
del self._headers[header.lower()]
except KeyError:
pass
def __getitem__(self, header):
return self._headers[header.lower()][1]
def has_header(self, header):
"""Case-insensitive check for a header."""
return header.lower() in self._headers
__contains__ = has_header
def items(self):
return self._headers.values()
def get(self, header, alternate=None):
return self._headers.get(header.lower(), (None, alternate))[1]
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
domain=None, secure=False, httponly=False):
"""
Sets a cookie.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then ``max_age`` will be calculated.
"""
value = force_str(value)
self.cookies[key] = value
if expires is not None:
if isinstance(expires, datetime.datetime):
if timezone.is_aware(expires):
expires = timezone.make_naive(expires, timezone.utc)
delta = expires - expires.utcnow()
# Add one second so the date matches exactly (a fraction of
# time gets lost between converting to a timedelta and
# then the date string).
delta = delta + datetime.timedelta(seconds=1)
# Just set max_age - the max_age logic will set expires.
expires = None
max_age = max(0, delta.days * 86400 + delta.seconds)
else:
self.cookies[key]['expires'] = expires
if max_age is not None:
self.cookies[key]['max-age'] = max_age
# IE requires expires, so set it if hasn't been already.
if not expires:
self.cookies[key]['expires'] = cookie_date(time.time() +
max_age)
if path is not None:
self.cookies[key]['path'] = path
if domain is not None:
self.cookies[key]['domain'] = domain
if secure:
self.cookies[key]['secure'] = True
if httponly:
self.cookies[key]['httponly'] = True
def setdefault(self, key, value):
"""Sets a header unless it has already been set."""
if key not in self:
self[key] = value
def set_signed_cookie(self, key, value, salt='', **kwargs):
value = signing.get_cookie_signer(salt=key + salt).sign(value)
return self.set_cookie(key, value, **kwargs)
def delete_cookie(self, key, path='/', domain=None):
self.set_cookie(key, max_age=0, path=path, domain=domain,
expires='Thu, 01-Jan-1970 00:00:00 GMT')
# Common methods used by subclasses
def make_bytes(self, value):
"""Turn a value into a bytestring encoded in the output charset."""
# Per PEP 3333, this response body must be bytes. To avoid returning
# an instance of a subclass, this function returns `bytes(value)`.
# This doesn't make a copy when `value` already contains bytes.
# Handle string types -- we can't rely on force_bytes here because:
# - under Python 3 it attempts str conversion first
# - when self._charset != 'utf-8' it re-encodes the content
if isinstance(value, bytes):
return bytes(value)
if isinstance(value, six.text_type):
return bytes(value.encode(self.charset))
# Handle non-string types (#16494)
return force_bytes(value, self.charset)
# These methods partially implement the file-like object interface.
# See http://docs.python.org/lib/bltin-file-objects.html
# The WSGI server must call this method upon completion of the request.
# See http://blog.dscpl.com.au/2012/10/obligations-for-calling-close-on.html
def close(self):
for closable in self._closable_objects:
try:
closable.close()
except Exception:
pass
self.closed = True
signals.request_finished.send(sender=self._handler_class)
def write(self, content):
raise IOError("This %s instance is not writable" % self.__class__.__name__)
def flush(self):
pass
def tell(self):
raise IOError("This %s instance cannot tell its position" % self.__class__.__name__)
# These methods partially implement a stream-like object interface.
# See https://docs.python.org/library/io.html#io.IOBase
def writable(self):
return False
def writelines(self, lines):
raise IOError("This %s instance is not writable" % self.__class__.__name__)
class HttpResponse(HttpResponseBase):
"""
An HTTP response class with a string as content.
This content that can be read, appended to or replaced.
"""
streaming = False
def __init__(self, content=b'', *args, **kwargs):
super(HttpResponse, self).__init__(*args, **kwargs)
# Content is a bytestring. See the `content` property methods.
self.content = content
def serialize(self):
"""Full HTTP message, including headers, as a bytestring."""
return self.serialize_headers() + b'\r\n\r\n' + self.content
if six.PY3:
__bytes__ = serialize
else:
__str__ = serialize
@property
def content(self):
return b''.join(self._container)
@content.setter
def content(self, value):
# Consume iterators upon assignment to allow repeated iteration.
if hasattr(value, '__iter__') and not isinstance(value, (bytes, six.string_types)):
if hasattr(value, 'close'):
self._closable_objects.append(value)
value = b''.join(self.make_bytes(chunk) for chunk in value)
else:
value = self.make_bytes(value)
# Create a list of properly encoded bytestrings to support write().
self._container = [value]
def __iter__(self):
return iter(self._container)
def write(self, content):
self._container.append(self.make_bytes(content))
def tell(self):
return len(self.content)
def getvalue(self):
return self.content
def writable(self):
return True
def writelines(self, lines):
for line in lines:
self.write(line)
class StreamingHttpResponse(HttpResponseBase):
"""
A streaming HTTP response class with an iterator as content.
This should only be iterated once, when the response is streamed to the
client. However, it can be appended to or replaced with a new iterator
that wraps the original content (or yields entirely new content).
"""
streaming = True
def __init__(self, streaming_content=(), *args, **kwargs):
super(StreamingHttpResponse, self).__init__(*args, **kwargs)
# `streaming_content` should be an iterable of bytestrings.
# See the `streaming_content` property methods.
self.streaming_content = streaming_content
@property
def content(self):
raise AttributeError("This %s instance has no `content` attribute. "
"Use `streaming_content` instead." % self.__class__.__name__)
@property
def streaming_content(self):
return map(self.make_bytes, self._iterator)
@streaming_content.setter
def streaming_content(self, value):
self._set_streaming_content(value)
def _set_streaming_content(self, value):
# Ensure we can never iterate on "value" more than once.
self._iterator = iter(value)
if hasattr(value, 'close'):
self._closable_objects.append(value)
def __iter__(self):
return self.streaming_content
def getvalue(self):
return b''.join(self.streaming_content)
class FileResponse(StreamingHttpResponse):
"""
A streaming HTTP response class optimized for files.
"""
block_size = 4096
def _set_streaming_content(self, value):
if hasattr(value, 'read'):
self.file_to_stream = value
filelike = value
if hasattr(filelike, 'close'):
self._closable_objects.append(filelike)
value = iter(lambda: filelike.read(self.block_size), b'')
else:
self.file_to_stream = None
super(FileResponse, self)._set_streaming_content(value)
class HttpResponseRedirectBase(HttpResponse):
allowed_schemes = ['http', 'https', 'ftp']
def __init__(self, redirect_to, *args, **kwargs):
parsed = urlparse(force_text(redirect_to))
if parsed.scheme and parsed.scheme not in self.allowed_schemes:
raise DisallowedRedirect("Unsafe redirect to URL with protocol '%s'" % parsed.scheme)
super(HttpResponseRedirectBase, self).__init__(*args, **kwargs)
self['Location'] = iri_to_uri(redirect_to)
url = property(lambda self: self['Location'])
class HttpResponseRedirect(HttpResponseRedirectBase):
status_code = 302
class HttpResponsePermanentRedirect(HttpResponseRedirectBase):
status_code = 301
class HttpResponseNotModified(HttpResponse):
status_code = 304
def __init__(self, *args, **kwargs):
super(HttpResponseNotModified, self).__init__(*args, **kwargs)
del self['content-type']
@HttpResponse.content.setter
def content(self, value):
if value:
raise AttributeError("You cannot set content to a 304 (Not Modified) response")
self._container = []
class HttpResponseBadRequest(HttpResponse):
status_code = 400
class HttpResponseNotFound(HttpResponse):
status_code = 404
class HttpResponseForbidden(HttpResponse):
status_code = 403
class HttpResponseNotAllowed(HttpResponse):
status_code = 405
def __init__(self, permitted_methods, *args, **kwargs):
super(HttpResponseNotAllowed, self).__init__(*args, **kwargs)
self['Allow'] = ', '.join(permitted_methods)
class HttpResponseGone(HttpResponse):
status_code = 410
class HttpResponseServerError(HttpResponse):
status_code = 500
class Http404(Exception):
pass
class JsonResponse(HttpResponse):
"""
An HTTP response class that consumes data to be serialized to JSON.
:param data: Data to be dumped into json. By default only ``dict`` objects
are allowed to be passed due to a security flaw before EcmaScript 5. See
the ``safe`` parameter for more information.
:param encoder: Should be an json encoder class. Defaults to
``django.core.serializers.json.DjangoJSONEncoder``.
:param safe: Controls if only ``dict`` objects may be serialized. Defaults
to ``True``.
"""
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError('In order to allow non-dict objects to be '
'serialized set the safe parameter to False')
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder)
super(JsonResponse, self).__init__(content=data, **kwargs)
| bsd-2-clause |
espadrine/opera | chromium/src/third_party/trace-viewer/third_party/pywebsocket/src/example/echo_client.py | 30 | 38662 | #!/usr/bin/env python
#
# Copyright 2011, 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.
"""Simple WebSocket client named echo_client just because of historical reason.
mod_pywebsocket directory must be in PYTHONPATH.
Example Usage:
# server setup
% cd $pywebsocket
% PYTHONPATH=$cwd/src python ./mod_pywebsocket/standalone.py -p 8880 \
-d $cwd/src/example
# run client
% PYTHONPATH=$cwd/src python ./src/example/echo_client.py -p 8880 \
-s localhost \
-o http://localhost -r /echo -m test
or
# run echo client to test IETF HyBi 00 protocol
run with --protocol-version=hybi00
or
# server setup to test Hixie 75 protocol
run with --allow-draft75
# run echo client to test Hixie 75 protocol
run with --protocol-version=hixie75
"""
import base64
import codecs
import logging
from optparse import OptionParser
import os
import random
import re
import socket
import struct
import sys
from mod_pywebsocket import common
from mod_pywebsocket.extensions import DeflateFrameExtensionProcessor
from mod_pywebsocket.stream import Stream
from mod_pywebsocket.stream import StreamHixie75
from mod_pywebsocket.stream import StreamOptions
from mod_pywebsocket import util
_TIMEOUT_SEC = 10
_UNDEFINED_PORT = -1
_UPGRADE_HEADER = 'Upgrade: websocket\r\n'
_UPGRADE_HEADER_HIXIE75 = 'Upgrade: WebSocket\r\n'
_CONNECTION_HEADER = 'Connection: Upgrade\r\n'
# Special message that tells the echo server to start closing handshake
_GOODBYE_MESSAGE = 'Goodbye'
_PROTOCOL_VERSION_HYBI13 = 'hybi13'
_PROTOCOL_VERSION_HYBI08 = 'hybi08'
_PROTOCOL_VERSION_HYBI00 = 'hybi00'
_PROTOCOL_VERSION_HIXIE75 = 'hixie75'
class ClientHandshakeError(Exception):
pass
def _build_method_line(resource):
return 'GET %s HTTP/1.1\r\n' % resource
def _origin_header(header, origin):
# 4.1 13. concatenation of the string "Origin:", a U+0020 SPACE character,
# and the /origin/ value, converted to ASCII lowercase, to /fields/.
return '%s: %s\r\n' % (header, origin.lower())
def _format_host_header(host, port, secure):
# 4.1 9. Let /hostport/ be an empty string.
# 4.1 10. Append the /host/ value, converted to ASCII lowercase, to
# /hostport/
hostport = host.lower()
# 4.1 11. If /secure/ is false, and /port/ is not 80, or if /secure/
# is true, and /port/ is not 443, then append a U+003A COLON character
# (:) followed by the value of /port/, expressed as a base-ten integer,
# to /hostport/
if ((not secure and port != common.DEFAULT_WEB_SOCKET_PORT) or
(secure and port != common.DEFAULT_WEB_SOCKET_SECURE_PORT)):
hostport += ':' + str(port)
# 4.1 12. concatenation of the string "Host:", a U+0020 SPACE
# character, and /hostport/, to /fields/.
return '%s: %s\r\n' % (common.HOST_HEADER, hostport)
def _receive_bytes(socket, length):
bytes = []
remaining = length
while remaining > 0:
received_bytes = socket.recv(remaining)
if not received_bytes:
raise IOError(
'Connection closed before receiving requested length '
'(requested %d bytes but received only %d bytes)' %
(length, length - remaining))
bytes.append(received_bytes)
remaining -= len(received_bytes)
return ''.join(bytes)
def _get_mandatory_header(fields, name):
"""Gets the value of the header specified by name from fields.
This function expects that there's only one header with the specified name
in fields. Otherwise, raises an ClientHandshakeError.
"""
values = fields.get(name.lower())
if values is None or len(values) == 0:
raise ClientHandshakeError(
'%s header not found: %r' % (name, values))
if len(values) > 1:
raise ClientHandshakeError(
'Multiple %s headers found: %r' % (name, values))
return values[0]
def _validate_mandatory_header(fields, name,
expected_value, case_sensitive=False):
"""Gets and validates the value of the header specified by name from
fields.
If expected_value is specified, compares expected value and actual value
and raises an ClientHandshakeError on failure. You can specify case
sensitiveness in this comparison by case_sensitive parameter. This function
expects that there's only one header with the specified name in fields.
Otherwise, raises an ClientHandshakeError.
"""
value = _get_mandatory_header(fields, name)
if ((case_sensitive and value != expected_value) or
(not case_sensitive and value.lower() != expected_value.lower())):
raise ClientHandshakeError(
'Illegal value for header %s: %r (expected) vs %r (actual)' %
(name, expected_value, value))
class _TLSSocket(object):
"""Wrapper for a TLS connection."""
def __init__(self, raw_socket):
self._ssl = socket.ssl(raw_socket)
def send(self, bytes):
return self._ssl.write(bytes)
def recv(self, size=-1):
return self._ssl.read(size)
def close(self):
# Nothing to do.
pass
class ClientHandshakeBase(object):
"""A base class for WebSocket opening handshake processors for each
protocol version.
"""
def __init__(self):
self._logger = util.get_class_logger(self)
def _read_fields(self):
# 4.1 32. let /fields/ be a list of name-value pairs, initially empty.
fields = {}
while True: # "Field"
# 4.1 33. let /name/ and /value/ be empty byte arrays
name = ''
value = ''
# 4.1 34. read /name/
name = self._read_name()
if name is None:
break
# 4.1 35. read spaces
# TODO(tyoshino): Skip only one space as described in the spec.
ch = self._skip_spaces()
# 4.1 36. read /value/
value = self._read_value(ch)
# 4.1 37. read a byte from the server
ch = _receive_bytes(self._socket, 1)
if ch != '\n': # 0x0A
raise ClientHandshakeError(
'Expected LF but found %r while reading value %r for '
'header %r' % (ch, value, name))
self._logger.debug('Received %r header', name)
# 4.1 38. append an entry to the /fields/ list that has the name
# given by the string obtained by interpreting the /name/ byte
# array as a UTF-8 stream and the value given by the string
# obtained by interpreting the /value/ byte array as a UTF-8 byte
# stream.
fields.setdefault(name, []).append(value)
# 4.1 39. return to the "Field" step above
return fields
def _read_name(self):
# 4.1 33. let /name/ be empty byte arrays
name = ''
while True:
# 4.1 34. read a byte from the server
ch = _receive_bytes(self._socket, 1)
if ch == '\r': # 0x0D
return None
elif ch == '\n': # 0x0A
raise ClientHandshakeError(
'Unexpected LF when reading header name %r' % name)
elif ch == ':': # 0x3A
return name
elif ch >= 'A' and ch <= 'Z': # Range 0x31 to 0x5A
ch = chr(ord(ch) + 0x20)
name += ch
else:
name += ch
def _skip_spaces(self):
# 4.1 35. read a byte from the server
while True:
ch = _receive_bytes(self._socket, 1)
if ch == ' ': # 0x20
continue
return ch
def _read_value(self, ch):
# 4.1 33. let /value/ be empty byte arrays
value = ''
# 4.1 36. read a byte from server.
while True:
if ch == '\r': # 0x0D
return value
elif ch == '\n': # 0x0A
raise ClientHandshakeError(
'Unexpected LF when reading header value %r' % value)
else:
value += ch
ch = _receive_bytes(self._socket, 1)
class ClientHandshakeProcessor(ClientHandshakeBase):
"""WebSocket opening handshake processor for
draft-ietf-hybi-thewebsocketprotocol-06 and later.
"""
def __init__(self, socket, options):
super(ClientHandshakeProcessor, self).__init__()
self._socket = socket
self._options = options
self._logger = util.get_class_logger(self)
def handshake(self):
"""Performs opening handshake on the specified socket.
Raises:
ClientHandshakeError: handshake failed.
"""
request_line = _build_method_line(self._options.resource)
self._logger.debug('Client\'s opening handshake Request-Line: %r',
request_line)
self._socket.sendall(request_line)
fields = []
fields.append(_format_host_header(
self._options.server_host,
self._options.server_port,
self._options.use_tls))
fields.append(_UPGRADE_HEADER)
fields.append(_CONNECTION_HEADER)
if self._options.origin is not None:
if self._options.protocol_version == _PROTOCOL_VERSION_HYBI08:
fields.append(_origin_header(
common.SEC_WEBSOCKET_ORIGIN_HEADER,
self._options.origin))
else:
fields.append(_origin_header(common.ORIGIN_HEADER,
self._options.origin))
original_key = os.urandom(16)
self._key = base64.b64encode(original_key)
self._logger.debug(
'%s: %r (%s)',
common.SEC_WEBSOCKET_KEY_HEADER,
self._key,
util.hexify(original_key))
fields.append(
'%s: %s\r\n' % (common.SEC_WEBSOCKET_KEY_HEADER, self._key))
if self._options.version_header > 0:
fields.append('%s: %d\r\n' % (common.SEC_WEBSOCKET_VERSION_HEADER,
self._options.version_header))
elif self._options.protocol_version == _PROTOCOL_VERSION_HYBI08:
fields.append('%s: %d\r\n' % (common.SEC_WEBSOCKET_VERSION_HEADER,
common.VERSION_HYBI08))
else:
fields.append('%s: %d\r\n' % (common.SEC_WEBSOCKET_VERSION_HEADER,
common.VERSION_HYBI_LATEST))
extensions_to_request = []
if self._options.deflate_stream:
extensions_to_request.append(
common.ExtensionParameter(
common.DEFLATE_STREAM_EXTENSION))
if self._options.deflate_frame:
extensions_to_request.append(
common.ExtensionParameter(common.DEFLATE_FRAME_EXTENSION))
if len(extensions_to_request) != 0:
fields.append(
'%s: %s\r\n' %
(common.SEC_WEBSOCKET_EXTENSIONS_HEADER,
common.format_extensions(extensions_to_request)))
for field in fields:
self._socket.sendall(field)
self._socket.sendall('\r\n')
self._logger.debug('Sent client\'s opening handshake headers: %r',
fields)
self._logger.debug('Start reading Status-Line')
status_line = ''
while True:
ch = _receive_bytes(self._socket, 1)
status_line += ch
if ch == '\n':
break
m = re.match('HTTP/\\d+\.\\d+ (\\d\\d\\d) .*\r\n', status_line)
if m is None:
raise ClientHandshakeError(
'Wrong status line format: %r' % status_line)
status_code = m.group(1)
if status_code != '101':
self._logger.debug('Unexpected status code %s with following '
'headers: %r', status_code, self._read_fields())
raise ClientHandshakeError(
'Expected HTTP status code 101 but found %r' % status_code)
self._logger.debug('Received valid Status-Line')
self._logger.debug('Start reading headers until we see an empty line')
fields = self._read_fields()
ch = _receive_bytes(self._socket, 1)
if ch != '\n': # 0x0A
raise ClientHandshakeError(
'Expected LF but found %r while reading value %r for header '
'name %r' % (ch, value, name))
self._logger.debug('Received an empty line')
self._logger.debug('Server\'s opening handshake headers: %r', fields)
_validate_mandatory_header(
fields,
common.UPGRADE_HEADER,
common.WEBSOCKET_UPGRADE_TYPE,
False)
_validate_mandatory_header(
fields,
common.CONNECTION_HEADER,
common.UPGRADE_CONNECTION_TYPE,
False)
accept = _get_mandatory_header(
fields, common.SEC_WEBSOCKET_ACCEPT_HEADER)
# Validate
try:
binary_accept = base64.b64decode(accept)
except TypeError, e:
raise HandshakeError(
'Illegal value for header %s: %r' %
(common.SEC_WEBSOCKET_ACCEPT_HEADER, accept))
if len(binary_accept) != 20:
raise ClientHandshakeError(
'Decoded value of %s is not 20-byte long' %
common.SEC_WEBSOCKET_ACCEPT_HEADER)
self._logger.debug(
'Response for challenge : %r (%s)',
accept, util.hexify(binary_accept))
binary_expected_accept = util.sha1_hash(
self._key + common.WEBSOCKET_ACCEPT_UUID).digest()
expected_accept = base64.b64encode(binary_expected_accept)
self._logger.debug(
'Expected response for challenge: %r (%s)',
expected_accept, util.hexify(binary_expected_accept))
if accept != expected_accept:
raise ClientHandshakeError(
'Invalid %s header: %r (expected: %s)' %
(common.SEC_WEBSOCKET_ACCEPT_HEADER, accept, expected_accept))
deflate_stream_accepted = False
deflate_frame_accepted = False
extensions_header = fields.get(
common.SEC_WEBSOCKET_EXTENSIONS_HEADER.lower())
accepted_extensions = []
if extensions_header is not None and len(extensions_header) != 0:
accepted_extensions = common.parse_extensions(extensions_header[0])
# TODO(bashi): Support the new style perframe compression extension.
for extension in accepted_extensions:
extension_name = extension.name()
if (extension_name == common.DEFLATE_STREAM_EXTENSION and
len(extension.get_parameter_names()) == 0 and
self._options.deflate_stream):
deflate_stream_accepted = True
continue
if (extension_name == common.DEFLATE_FRAME_EXTENSION and
self._options.deflate_frame):
deflate_frame_accepted = True
processor = DeflateFrameExtensionProcessor(extension)
unused_extension_response = processor.get_extension_response()
self._options.deflate_frame = processor
continue
raise ClientHandshakeError(
'Unexpected extension %r' % extension_name)
if (self._options.deflate_stream and not deflate_stream_accepted):
raise ClientHandshakeError(
'Requested %s, but the server rejected it' %
common.DEFLATE_STREAM_EXTENSION)
if (self._options.deflate_frame and not deflate_frame_accepted):
raise ClientHandshakeError(
'Requested %s, but the server rejected it' %
common.DEFLATE_FRAME_EXTENSION)
# TODO(tyoshino): Handle Sec-WebSocket-Protocol
# TODO(tyoshino): Handle Cookie, etc.
class ClientHandshakeProcessorHybi00(ClientHandshakeBase):
"""WebSocket opening handshake processor for
draft-ietf-hybi-thewebsocketprotocol-00 (equivalent to
draft-hixie-thewebsocketprotocol-76).
"""
def __init__(self, socket, options):
super(ClientHandshakeProcessorHybi00, self).__init__()
self._socket = socket
self._options = options
self._logger = util.get_class_logger(self)
def handshake(self):
"""Performs opening handshake on the specified socket.
Raises:
ClientHandshakeError: handshake failed.
"""
# 4.1 5. send request line.
self._socket.sendall(_build_method_line(self._options.resource))
# 4.1 6. Let /fields/ be an empty list of strings.
fields = []
# 4.1 7. Add the string "Upgrade: WebSocket" to /fields/.
fields.append(_UPGRADE_HEADER_HIXIE75)
# 4.1 8. Add the string "Connection: Upgrade" to /fields/.
fields.append(_CONNECTION_HEADER)
# 4.1 9-12. Add Host: field to /fields/.
fields.append(_format_host_header(
self._options.server_host,
self._options.server_port,
self._options.use_tls))
# 4.1 13. Add Origin: field to /fields/.
if not self._options.origin:
raise ClientHandshakeError(
'Specify the origin of the connection by --origin flag')
fields.append(_origin_header(common.ORIGIN_HEADER,
self._options.origin))
# TODO: 4.1 14 Add Sec-WebSocket-Protocol: field to /fields/.
# TODO: 4.1 15 Add cookie headers to /fields/.
# 4.1 16-23. Add Sec-WebSocket-Key<n> to /fields/.
self._number1, key1 = self._generate_sec_websocket_key()
self._logger.debug('Number1: %d', self._number1)
fields.append('%s: %s\r\n' % (common.SEC_WEBSOCKET_KEY1_HEADER, key1))
self._number2, key2 = self._generate_sec_websocket_key()
self._logger.debug('Number2: %d', self._number2)
fields.append('%s: %s\r\n' % (common.SEC_WEBSOCKET_KEY2_HEADER, key2))
fields.append('%s: 0\r\n' % common.SEC_WEBSOCKET_DRAFT_HEADER)
# 4.1 24. For each string in /fields/, in a random order: send the
# string, encoded as UTF-8, followed by a UTF-8 encoded U+000D CARRIAGE
# RETURN U+000A LINE FEED character pair (CRLF).
random.shuffle(fields)
for field in fields:
self._socket.sendall(field)
# 4.1 25. send a UTF-8-encoded U+000D CARRIAGE RETURN U+000A LINE FEED
# character pair (CRLF).
self._socket.sendall('\r\n')
# 4.1 26. let /key3/ be a string consisting of eight random bytes (or
# equivalently, a random 64 bit integer encoded in a big-endian order).
self._key3 = self._generate_key3()
# 4.1 27. send /key3/ to the server.
self._socket.sendall(self._key3)
self._logger.debug(
'Key3: %r (%s)', self._key3, util.hexify(self._key3))
self._logger.info('Sent handshake')
# 4.1 28. Read bytes from the server until either the connection
# closes, or a 0x0A byte is read. let /field/ be these bytes, including
# the 0x0A bytes.
field = ''
while True:
ch = _receive_bytes(self._socket, 1)
field += ch
if ch == '\n':
break
# if /field/ is not at least seven bytes long, or if the last
# two bytes aren't 0x0D and 0x0A respectively, or if it does not
# contain at least two 0x20 bytes, then fail the WebSocket connection
# and abort these steps.
if len(field) < 7 or not field.endswith('\r\n'):
raise ClientHandshakeError('Wrong status line: %r' % field)
m = re.match('[^ ]* ([^ ]*) .*', field)
if m is None:
raise ClientHandshakeError(
'No HTTP status code found in status line: %r' % field)
# 4.1 29. let /code/ be the substring of /field/ that starts from the
# byte after the first 0x20 byte, and ends with the byte before the
# second 0x20 byte.
code = m.group(1)
# 4.1 30. if /code/ is not three bytes long, or if any of the bytes in
# /code/ are not in the range 0x30 to 0x90, then fail the WebSocket
# connection and abort these steps.
if not re.match('[0-9][0-9][0-9]', code):
raise ClientHandshakeError(
'HTTP status code %r is not three digit in status line: %r' %
(code, field))
# 4.1 31. if /code/, interpreted as UTF-8, is "101", then move to the
# next step.
if code != '101':
raise ClientHandshakeError(
'Expected HTTP status code 101 but found %r in status line: '
'%r' % (code, field))
# 4.1 32-39. read fields into /fields/
fields = self._read_fields()
# 4.1 40. _Fields processing_
# read a byte from server
ch = _receive_bytes(self._socket, 1)
if ch != '\n': # 0x0A
raise ClientHandshakeError('Expected LF but found %r' % ch)
# 4.1 41. check /fields/
# TODO(ukai): protocol
# if the entry's name is "upgrade"
# if the value is not exactly equal to the string "WebSocket",
# then fail the WebSocket connection and abort these steps.
_validate_mandatory_header(
fields,
common.UPGRADE_HEADER,
common.WEBSOCKET_UPGRADE_TYPE_HIXIE75,
True)
# if the entry's name is "connection"
# if the value, converted to ASCII lowercase, is not exactly equal
# to the string "upgrade", then fail the WebSocket connection and
# abort these steps.
_validate_mandatory_header(
fields,
common.CONNECTION_HEADER,
common.UPGRADE_CONNECTION_TYPE,
False)
origin = _get_mandatory_header(
fields, common.SEC_WEBSOCKET_ORIGIN_HEADER)
location = _get_mandatory_header(
fields, common.SEC_WEBSOCKET_LOCATION_HEADER)
# TODO(ukai): check origin, location, cookie, ..
# 4.1 42. let /challenge/ be the concatenation of /number_1/,
# expressed as a big endian 32 bit integer, /number_2/, expressed
# as big endian 32 bit integer, and the eight bytes of /key_3/ in the
# order they were sent on the wire.
challenge = struct.pack('!I', self._number1)
challenge += struct.pack('!I', self._number2)
challenge += self._key3
self._logger.debug(
'Challenge: %r (%s)', challenge, util.hexify(challenge))
# 4.1 43. let /expected/ be the MD5 fingerprint of /challenge/ as a
# big-endian 128 bit string.
expected = util.md5_hash(challenge).digest()
self._logger.debug(
'Expected challenge response: %r (%s)',
expected, util.hexify(expected))
# 4.1 44. read sixteen bytes from the server.
# let /reply/ be those bytes.
reply = _receive_bytes(self._socket, 16)
self._logger.debug(
'Actual challenge response: %r (%s)', reply, util.hexify(reply))
# 4.1 45. if /reply/ does not exactly equal /expected/, then fail
# the WebSocket connection and abort these steps.
if expected != reply:
raise ClientHandshakeError(
'Bad challenge response: %r (expected) != %r (actual)' %
(expected, reply))
# 4.1 46. The *WebSocket connection is established*.
def _generate_sec_websocket_key(self):
# 4.1 16. let /spaces_n/ be a random integer from 1 to 12 inclusive.
spaces = random.randint(1, 12)
# 4.1 17. let /max_n/ be the largest integer not greater than
# 4,294,967,295 divided by /spaces_n/.
maxnum = 4294967295 / spaces
# 4.1 18. let /number_n/ be a random integer from 0 to /max_n/
# inclusive.
number = random.randint(0, maxnum)
# 4.1 19. let /product_n/ be the result of multiplying /number_n/ and
# /spaces_n/ together.
product = number * spaces
# 4.1 20. let /key_n/ be a string consisting of /product_n/, expressed
# in base ten using the numerals in the range U+0030 DIGIT ZERO (0) to
# U+0039 DIGIT NINE (9).
key = str(product)
# 4.1 21. insert between one and twelve random characters from the
# range U+0021 to U+002F and U+003A to U+007E into /key_n/ at random
# positions.
available_chars = range(0x21, 0x2f + 1) + range(0x3a, 0x7e + 1)
n = random.randint(1, 12)
for _ in xrange(n):
ch = random.choice(available_chars)
pos = random.randint(0, len(key))
key = key[0:pos] + chr(ch) + key[pos:]
# 4.1 22. insert /spaces_n/ U+0020 SPACE characters into /key_n/ at
# random positions other than start or end of the string.
for _ in xrange(spaces):
pos = random.randint(1, len(key) - 1)
key = key[0:pos] + ' ' + key[pos:]
return number, key
def _generate_key3(self):
# 4.1 26. let /key3/ be a string consisting of eight random bytes (or
# equivalently, a random 64 bit integer encoded in a big-endian order).
return ''.join([chr(random.randint(0, 255)) for _ in xrange(8)])
class ClientHandshakeProcessorHixie75(object):
"""WebSocket opening handshake processor for
draft-hixie-thewebsocketprotocol-75.
"""
_EXPECTED_RESPONSE = (
'HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
_UPGRADE_HEADER_HIXIE75 +
_CONNECTION_HEADER)
def __init__(self, socket, options):
self._socket = socket
self._options = options
self._logger = util.get_class_logger(self)
def _skip_headers(self):
terminator = '\r\n\r\n'
pos = 0
while pos < len(terminator):
received = _receive_bytes(self._socket, 1)
if received == terminator[pos]:
pos += 1
elif received == terminator[0]:
pos = 1
else:
pos = 0
def handshake(self):
"""Performs opening handshake on the specified socket.
Raises:
ClientHandshakeError: handshake failed.
"""
self._socket.sendall(_build_method_line(self._options.resource))
self._socket.sendall(_UPGRADE_HEADER_HIXIE75)
self._socket.sendall(_CONNECTION_HEADER)
self._socket.sendall(_format_host_header(
self._options.server_host,
self._options.server_port,
self._options.use_tls))
if not self._options.origin:
raise ClientHandshakeError(
'Specify the origin of the connection by --origin flag')
self._socket.sendall(_origin_header(common.ORIGIN_HEADER,
self._options.origin))
self._socket.sendall('\r\n')
self._logger.info('Sent handshake')
for expected_char in (
ClientHandshakeProcessorHixie75._EXPECTED_RESPONSE):
received = _receive_bytes(self._socket, 1)
if expected_char != received:
raise ClientHandshakeError('Handshake failure')
# We cut corners and skip other headers.
self._skip_headers()
class ClientConnection(object):
"""A wrapper for socket object to provide the mp_conn interface.
mod_pywebsocket library is designed to be working on Apache mod_python's
mp_conn object.
"""
def __init__(self, socket):
self._socket = socket
def write(self, data):
self._socket.sendall(data)
def read(self, n):
return self._socket.recv(n)
def get_remote_addr(self):
return self._socket.getpeername()
remote_addr = property(get_remote_addr)
class ClientRequest(object):
"""A wrapper class just to make it able to pass a socket object to
functions that expect a mp_request object.
"""
def __init__(self, socket):
self._logger = util.get_class_logger(self)
self._socket = socket
self.connection = ClientConnection(socket)
def _drain_received_data(self):
"""Drains unread data in the receive buffer."""
drained_data = util.drain_received_data(self._socket)
if drained_data:
self._logger.debug(
'Drained data following close frame: %r', drained_data)
class EchoClient(object):
"""WebSocket echo client."""
def __init__(self, options):
self._options = options
self._socket = None
self._logger = util.get_class_logger(self)
def run(self):
"""Run the client.
Shake hands and then repeat sending message and receiving its echo.
"""
self._socket = socket.socket()
self._socket.settimeout(self._options.socket_timeout)
try:
self._socket.connect((self._options.server_host,
self._options.server_port))
if self._options.use_tls:
self._socket = _TLSSocket(self._socket)
version = self._options.protocol_version
if (version == _PROTOCOL_VERSION_HYBI08 or
version == _PROTOCOL_VERSION_HYBI13):
self._handshake = ClientHandshakeProcessor(
self._socket, self._options)
elif version == _PROTOCOL_VERSION_HYBI00:
self._handshake = ClientHandshakeProcessorHybi00(
self._socket, self._options)
elif version == _PROTOCOL_VERSION_HIXIE75:
self._handshake = ClientHandshakeProcessorHixie75(
self._socket, self._options)
else:
raise ValueError(
'Invalid --protocol-version flag: %r' % version)
self._handshake.handshake()
self._logger.info('Connection established')
request = ClientRequest(self._socket)
version_map = {
_PROTOCOL_VERSION_HYBI08: common.VERSION_HYBI08,
_PROTOCOL_VERSION_HYBI13: common.VERSION_HYBI13,
_PROTOCOL_VERSION_HYBI00: common.VERSION_HYBI00,
_PROTOCOL_VERSION_HIXIE75: common.VERSION_HIXIE75}
request.ws_version = version_map[version]
if (version == _PROTOCOL_VERSION_HYBI08 or
version == _PROTOCOL_VERSION_HYBI13):
stream_option = StreamOptions()
stream_option.mask_send = True
stream_option.unmask_receive = False
if self._options.deflate_stream:
stream_option.deflate_stream = True
if self._options.deflate_frame is not False:
processor = self._options.deflate_frame
processor.setup_stream_options(stream_option)
self._stream = Stream(request, stream_option)
elif version == _PROTOCOL_VERSION_HYBI00:
self._stream = StreamHixie75(request, True)
elif version == _PROTOCOL_VERSION_HIXIE75:
self._stream = StreamHixie75(request)
for line in self._options.message.split(','):
self._stream.send_message(line)
if self._options.verbose:
print 'Send: %s' % line
try:
received = self._stream.receive_message()
if self._options.verbose:
print 'Recv: %s' % received
except Exception, e:
if self._options.verbose:
print 'Error: %s' % e
raise
if version != _PROTOCOL_VERSION_HIXIE75:
self._do_closing_handshake()
finally:
self._socket.close()
def _do_closing_handshake(self):
"""Perform closing handshake using the specified closing frame."""
if self._options.message.split(',')[-1] == _GOODBYE_MESSAGE:
# requested server initiated closing handshake, so
# expecting closing handshake message from server.
self._logger.info('Wait for server-initiated closing handshake')
message = self._stream.receive_message()
if message is None:
print 'Recv close'
print 'Send ack'
self._logger.info(
'Received closing handshake and sent ack')
return
print 'Send close'
self._stream.close_connection()
self._logger.info('Sent closing handshake')
print 'Recv ack'
self._logger.info('Received ack')
def main():
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
parser = OptionParser()
# We accept --command_line_flag style flags which is the same as Google
# gflags in addition to common --command-line-flag style flags.
parser.add_option('-s', '--server-host', '--server_host',
dest='server_host', type='string',
default='localhost', help='server host')
parser.add_option('-p', '--server-port', '--server_port',
dest='server_port', type='int',
default=_UNDEFINED_PORT, help='server port')
parser.add_option('-o', '--origin', dest='origin', type='string',
default=None, help='origin')
parser.add_option('-r', '--resource', dest='resource', type='string',
default='/echo', help='resource path')
parser.add_option('-m', '--message', dest='message', type='string',
help=('comma-separated messages to send. '
'%s will force close the connection from server.' %
_GOODBYE_MESSAGE))
parser.add_option('-q', '--quiet', dest='verbose', action='store_false',
default=True, help='suppress messages')
parser.add_option('-t', '--tls', dest='use_tls', action='store_true',
default=False, help='use TLS (wss://)')
parser.add_option('-k', '--socket-timeout', '--socket_timeout',
dest='socket_timeout', type='int', default=_TIMEOUT_SEC,
help='Timeout(sec) for sockets')
parser.add_option('--draft75', dest='draft75',
action='store_true', default=False,
help='use the Hixie 75 protocol. This overrides '
'protocol-version flag')
parser.add_option('--protocol-version', '--protocol_version',
dest='protocol_version',
type='string', default=_PROTOCOL_VERSION_HYBI13,
help='WebSocket protocol version to use. One of \'' +
_PROTOCOL_VERSION_HYBI13 + '\', \'' +
_PROTOCOL_VERSION_HYBI08 + '\', \'' +
_PROTOCOL_VERSION_HYBI00 + '\', \'' +
_PROTOCOL_VERSION_HIXIE75 + '\'')
parser.add_option('--version-header', '--version_header',
dest='version_header',
type='int', default=-1,
help='specify Sec-WebSocket-Version header value')
parser.add_option('--deflate-stream', '--deflate_stream',
dest='deflate_stream',
action='store_true', default=False,
help='use deflate-stream extension. This value will be '
'ignored if used with protocol version that doesn\'t '
'support deflate-stream.')
parser.add_option('--deflate-frame', '--deflate_frame',
dest='deflate_frame',
action='store_true', default=False,
help='use deflate-frame extension. This value will be '
'ignored if used with protocol version that doesn\'t '
'support deflate-frame.')
parser.add_option('--log-level', '--log_level', type='choice',
dest='log_level', default='warn',
choices=['debug', 'info', 'warn', 'error', 'critical'],
help='Log level.')
(options, unused_args) = parser.parse_args()
logging.basicConfig(level=logging.getLevelName(options.log_level.upper()))
if options.draft75:
options.protocol_version = _PROTOCOL_VERSION_HIXIE75
# Default port number depends on whether TLS is used.
if options.server_port == _UNDEFINED_PORT:
if options.use_tls:
options.server_port = common.DEFAULT_WEB_SOCKET_SECURE_PORT
else:
options.server_port = common.DEFAULT_WEB_SOCKET_PORT
# optparse doesn't seem to handle non-ascii default values.
# Set default message here.
if not options.message:
options.message = u'Hello,\u65e5\u672c' # "Japan" in Japanese
EchoClient(options).run()
if __name__ == '__main__':
main()
# vi:sts=4 sw=4 et
| bsd-3-clause |
LucidBlue/mykeepon-storyteller | src/realtime_audio_capture.py | 1 | 3120 | #! /usr/bin/env python
from __future__ import division
import pyaudio
import wave
import sys
import scipy
import numpy as np
import struct
CHUNK = 2**10
#from scikits.audiolab import flacread
from numpy.fft import rfft, irfft
from numpy import argmax, sqrt, mean, diff, log
import matplotlib
from scipy.signal import blackmanharris, fftconvolve
from time import time
from parabolic import parabolic
def freq_power_from_fft(sig, fs):
# Compute Fourier transform of windowed signal
windowed = sig * blackmanharris(CHUNK)
fftData = abs(rfft(windowed))
# powerData = 20*log10(fftData)
# Find the index of the peak and interpolate to get a more accurate peak
i = argmax(fftData) # Just use this for less-accurate, naive version
# make sure i is not an endpoint of the bin
if i != len(fftData)-1 and i != 0:
#print("data: " + str(parabolic(log(abs(fftData)), i)))
true_i,logmag = parabolic(log(abs(fftData)), i)
# Convert to equivalent frequency
freq= fs * true_i / len(windowed)
#print("frequency="+ str(freq) + " log of magnitude=" + str(logmag))
if logmag < 0:
logmag = 0
return freq,logmag
else:
freq = fs * i / len(windowed)
logmag = log(abs(fftData))[i]
if logmag < 0:
logmag = 0
#print("frequency="+ str(freq) + "log of magnitude not interp=" + str(logmag))
return freq,logmag
def main():
#open wav file
wf = wave.open(sys.argv[1], 'rb')
(channels,sample_width,rate,frames,comptype,compname) = wf.getparams()
FPS = 25.0
trimby = 10
divby = 100
#print("channels: %d sample width: %d rate: %d frames: %d chunk: %d" %(channels, sample_width, rate, frames, chunk))
# instantiate PyAudio
p = pyaudio.PyAudio()
stream = p.open(format = p.get_format_from_width(sample_width),
channels = channels,
rate = rate,
output = True)
data = wf.readframes(CHUNK)
freq_sum = 0.0
freq_count = 0
freq_max = 0.0
freq_min = 999999999999
while len(data) == CHUNK*sample_width:
# unpack data
indata = np.array(wave.struct.unpack("%dh"%(len(data)/sample_width),data))
#remainder of calculations
frequency,logmag = freq_power_from_fft(indata, rate)
print("frequency: " + str(frequency) + " logMagnitude: " + str(logmag))
"""
if frequency < 1000 and frequency > 500:
print "frequency: %f Hz" % (frequency)
"""
if frequency < 1000 and frequency > 0:
#print "frequency: %f Hz" % (frequency)
freq_sum += frequency
freq_count += 1
if frequency < freq_min:
freq_min = frequency
if frequency > freq_max:
freq_max = frequency
#print("freq count: " + str(freq_count))
# write data out to the audio stream after first round of calculations
stream.write(data)
# read some more data
data = wf.readframes(CHUNK)
avg_freq = freq_sum/freq_count
print("Average frequency for this clip: %f" %(avg_freq))
print("Min frequency for this clip: %f" %(freq_min))
print("Max frequency for this clip: %f" %(freq_max))
if data:
stream.write(data)
wf.close()
stream.stop_stream()
stream.close()
p.terminate()
if __name__ == "__main__":
main()
| bsd-3-clause |
bennettp123/CouchPotatoServer | couchpotato/core/notifications/notifymyandroid/main.py | 5 | 1064 | from couchpotato.core.helpers.variable import splitString
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
import pynma
import six
log = CPLog(__name__)
class NotifyMyAndroid(Notification):
def notify(self, message = '', data = None, listener = None):
if not data: data = {}
nma = pynma.PyNMA()
keys = splitString(self.conf('api_key'))
nma.addkey(keys)
nma.developerkey(self.conf('dev_key'))
response = nma.push(
application = self.default_title,
event = message.split(' ')[0],
description = message,
priority = self.conf('priority'),
batch_mode = len(keys) > 1
)
successful = 0
for key in keys:
if not response[str(key)]['code'] == six.u('200'):
log.error('Could not send notification to NotifyMyAndroid (%s). %s', (key, response[key]['message']))
else:
successful += 1
return successful == len(keys)
| gpl-3.0 |
aranb/linux | tools/perf/scripts/python/syscall-counts-by-pid.py | 1996 | 2105 | # system call counts, by pid
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Displays system-wide system call totals, broken down by syscall.
# If a [comm] arg is specified, only syscalls called by [comm] are displayed.
import os, 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 syscall_name
usage = "perf script -s syscall-counts-by-pid.py [comm]\n";
for_comm = None
for_pid = None
if len(sys.argv) > 2:
sys.exit(usage)
if len(sys.argv) > 1:
try:
for_pid = int(sys.argv[1])
except:
for_comm = sys.argv[1]
syscalls = autodict()
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
print_syscall_totals()
def raw_syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
common_callchain, id, args):
if (for_comm and common_comm != for_comm) or \
(for_pid and common_pid != for_pid ):
return
try:
syscalls[common_comm][common_pid][id] += 1
except TypeError:
syscalls[common_comm][common_pid][id] = 1
def syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, args):
raw_syscalls__sys_enter(**locals())
def print_syscall_totals():
if for_comm is not None:
print "\nsyscall events for %s:\n\n" % (for_comm),
else:
print "\nsyscall events by comm/pid:\n\n",
print "%-40s %10s\n" % ("comm [pid]/syscalls", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"----------"),
comm_keys = syscalls.keys()
for comm in comm_keys:
pid_keys = syscalls[comm].keys()
for pid in pid_keys:
print "\n%s [%d]\n" % (comm, pid),
id_keys = syscalls[comm][pid].keys()
for id, val in sorted(syscalls[comm][pid].iteritems(), \
key = lambda(k, v): (v, k), reverse = True):
print " %-38s %10d\n" % (syscall_name(id), val),
| gpl-2.0 |
mpharrigan/msmbuilder | MSMBuilder/assigning.py | 2 | 9840 | from __future__ import print_function, absolute_import, division
from mdtraj.utils.six.moves import xrange
import os
import mdtraj as md
import numpy as np
import tables
import warnings
from mdtraj import io
import logging
logger = logging.getLogger(__name__)
def _setup_containers(project, assignments_fn, distances_fn):
"""
Setup the files on disk (Assignments.h5 and Assignments.h5.distances) that
results will be sent to.
Check to ensure that if they exist (and contain partial results), the
containers are not corrupted
Parameters
----------
project : msmbuilder.Project
The msmbuilder project file. Only the n_trajs and traj_lengths are
actully used.
assignments_fn : string
distances_fn : string
Returns
-------
f_assignments : tables.File
pytables handle to the assignments file, open in 'append' mode
f_distances : tables.File
pytables handle to the assignments file, open in 'append' mode
"""
def save_container(filename, dtype):
io.saveh(filename, arr_0=-1 * np.ones((project.n_trajs, np.max(project.traj_lengths)), dtype=dtype),
completed_trajs=np.zeros((project.n_trajs), dtype=np.bool))
def check_container(filename):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
fh = tables.openFile(filename, 'r')
if fh.root.arr_0.shape != (project.n_trajs, np.max(project.traj_lengths)):
raise ValueError('Shape error 1')
if fh.root.completed_trajs.shape != (project.n_trajs,):
raise ValueError('Shape error 2')
fh.close()
# save assignments container
if (not os.path.exists(assignments_fn)) \
and (not os.path.exists(distances_fn)):
save_container(assignments_fn, np.int)
save_container(distances_fn, np.float32)
elif os.path.exists(assignments_fn) and os.path.exists(distances_fn):
check_container(assignments_fn)
check_container(distances_fn)
else:
raise ValueError("You're missing one of the containers")
# append mode is read and write
with warnings.catch_warnings():
warnings.simplefilter('ignore')
f_assignments = tables.openFile(assignments_fn, mode='a')
f_distances = tables.openFile(distances_fn, mode='a')
return f_assignments, f_distances
def assign_in_memory(metric, generators, project, atom_indices_to_load=None):
"""
Assign every frame to its closest generator
This code does everything in memory, and does not checkpoint. It also does
not save any results to disk.
Parameters
----------
metric : msmbuilder.metrics.AbstractDistanceMetric
A distance metric used to define "closest"
project : msmbuilder.Project
Used to load the trajectories
generators : msmbuilder.Trajectory
A trajectory containing the structures of all of the cluster centers
atom_indices_to_load : {None, list}
The indices of the atoms to load for each trajectory chunk. Note that
this method is responsible for loading up atoms from the project, but
does NOT load up the generators. Those are passed in as a trajectory
object (above). So if the generators are already subsampled to a restricted
set of atom indices, but the trajectories on disk are NOT, you'll
need to pass in a set of indices here to resolve the difference.
See Also
--------
assign_with_checkpoint
"""
n_trajs, max_traj_length = project.n_trajs, np.max(project.traj_lengths)
assignments = -1 * np.ones((n_trajs, max_traj_length), dtype='int')
distances = -1 * np.ones((n_trajs, max_traj_length), dtype='float32')
pgens = metric.prepare_trajectory(generators)
for i in xrange(n_trajs):
traj = project.load_traj(i, atom_indices=atom_indices_to_load)
if traj['XYZList'].shape[1] != generators['XYZList'].shape[1]:
raise ValueError('Number of atoms in generators does not match '
'traj we\'re trying to assign! Maybe check atom indices?')
ptraj = metric.prepare_trajectory(traj)
for j in xrange(len(traj)):
d = metric.one_to_all(ptraj, pgens, j)
assignments[i, j] = np.argmin(d)
distances[i, j] = d[assignments[i, j]]
return assignments, distances
def assign_with_checkpoint(metric, project, generators, assignments_path,
distances_path, chunk_size=10000, atom_indices_to_load=None):
"""
Assign every frame to its closest generator
The results will be checkpointed along the way, trajectory by trajectory.
If the process is killed, it should be able to roughly pick up where it
left off.
Parameters
----------
metric : msmbuilder.metrics.AbstractDistanceMetric
A distance metric used to define "closest"
project : msmbuilder.Project
Used to load the trajectories
generators : msmbuilder.Trajectory
A trajectory containing the structures of all of the cluster centers
assignments_path : str
Path to a file that contains/will contain the assignments, as a 2D array
of integers in hdf5 format
distances_path : str
Path to a file that contains/will contain the assignments, as a 2D array
of integers in hdf5 format
chunk_size : int
The number of frames to load and process per step. The optimal number
here depends on your system memory -- it should probably be roughly
the number of frames you can fit in memory at any one time. Note, this
is only important if your trajectories are long, as the effective chunk_size
is really `min(traj_length, chunk_size)`
atom_indices_to_load : {None, list}
The indices of the atoms to load for each trajectory chunk. Note that
this method is responsible for loading up atoms from the project, but
does NOT load up the generators. Those are passed in as a trajectory
object (above). So if the generators are already subsampled to a restricted
set of atom indices, but the trajectories on disk are NOT, you'll
need to pass in a set of indices here to resolve the difference.
See Also
--------
assign_in_memory
"""
pgens = metric.prepare_trajectory(generators)
# setup the file handles
fh_a, fh_d = _setup_containers(project, assignments_path, distances_path)
for i in xrange(project.n_trajs):
if fh_a.root.completed_trajs[i] and fh_d.root.completed_trajs[i]:
logger.info('Skipping trajectory %s -- already assigned', i)
continue
if fh_a.root.completed_trajs[i] or fh_d.root.completed_trajs[i]:
logger.warn("Re-assigning trajectory even though some data is"
" available...")
fh_a.root.completed_trajs[i] = False
fh_d.root.completed_trajs[i] = False
logger.info('Assigning trajectory %s', i)
# pointer to the position in the total trajectory where
# the current chunk starts, so we know where in the Assignments
# array to put each batch of data
start_index = 0
filename = project.traj_filename(i)
chunkiter = md.iterload(filename, chunk=chunk_size, atom_indices=atom_indices_to_load)
for tchunk in chunkiter:
if tchunk.n_atoms != generators.n_atoms:
msg = ("Number of atoms in generators does not match "
"traj we're trying to assign! Maybe check atom indices?")
raise ValueError(msg)
ptchunk = metric.prepare_trajectory(tchunk)
this_length = len(ptchunk)
distances = np.empty(this_length, dtype=np.float32)
assignments = np.empty(this_length, dtype=np.int)
for j in xrange(this_length):
d = metric.one_to_all(ptchunk, pgens, j)
ind = np.argmin(d)
assignments[j] = ind
distances[j] = d[ind]
end_index = start_index + this_length
fh_a.root.arr_0[i, start_index:end_index] = assignments
fh_d.root.arr_0[i, start_index:end_index] = distances
# i'm not sure exactly what the optimal flush frequency is
fh_a.flush()
fh_d.flush()
start_index = end_index
# we're going to keep duplicates of this record -- i.e. writing
# it to both files
# completed chunks are not checkpointed -- only completed trajectories
# this means that if the process dies after completing 10/20 of the
# chunks in trajectory i -- those chunks are going to have to be recomputed
# (put trajectory i-1 is saved)
# this could be changed, but the implementation is a little tricky -- you
# have to watch out for the fact that the person might call this function
# with chunk_size=N, let it run for a while, kill it, and then call it
# again with chunk_size != N. Dealing with that appropriately is tricky
# since the chunks wont line up in the two cases
fh_a.root.completed_trajs[i] = True
fh_d.root.completed_trajs[i] = True
fh_a.close()
fh_d.close()
def streaming_assign_with_checkpoint(metric, project, generators, assignments_path,
distances_path, checkpoint=1, chunk_size=10000, atom_indices_to_load=None):
warnings.warn(("assign_with_checkpoint now uses the steaming engine "
"-- this function is deprecated"), DeprecationWarning)
assign_with_checkpoint(metric, project, generators, assignments_path,
distances_path, chunk_size, atom_indices_to_load)
| gpl-2.0 |
nigelb/gRefer | gRefer/utils.py | 1 | 2615 | # gRefer is a Bibliographic Management System that uses Google Docs
# as shared storage.
#
# Copyright (C) 2011 NigelB
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import codecs
from collections import OrderedDict
import datetime
import os
import platform
import re
import shutil
class Model: pass
def fix_filename_for_system(fname):
if platform.system() == "Windows":
return re.sub("[?\[\]/\\=+<>:;\"\*]", "_", fname)
if platform.system() == "Linux":
return re.sub("/", "_", fname)
return fname
def backup_if_exists(title, target, backup_dir, ext):
ts = datetime.datetime.now()
bak_path = os.path.join(backup_dir, "%s-%s.%s" % (title, ts.strftime("%Y-%m-%d_%H-%M-%S"), ext))
if os.path.exists(target):
shutil.move(target, bak_path)
def read_utf8_data(to_read):
f = codecs.open(to_read, "r", "utf-8")
d = f.read()
f.close()
#UTF8 decoder does not remove the BOM wtf?
if d[0] == unicode(codecs.BOM_UTF8, "utf8"):
d = d.lstrip(unicode(codecs.BOM_UTF8, "utf8"))
return d
#Grabbed from:
#http://stackoverflow.com/questions/4126348/how-do-i-rewrite-this-function-to-implement-ordereddict/4127426#4127426
class OrderedDefaultDict(OrderedDict):
def __init__(self, *args, **kwargs):
if not args:
self.default_factory = None
else:
if not (args[0] is None or callable(args[0])):
raise TypeError('first argument must be callable or None')
self.default_factory = args[0]
args = args[1:]
super(self.__class__, self).__init__(*args, **kwargs)
def __missing__ (self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = default = self.default_factory()
return default
def __reduce__(self): # optional, for pickle support
args = self.default_factory if self.default_factory else tuple()
return type(self), args, None, None, self.items()
| gpl-3.0 |
Frank-W-B/kaggle-carvana | architecture_flexible.py | 1 | 4546 |
from keras.models import Model, Sequential
from keras.layers import Input
from keras.layers.convolutional import Conv2D, MaxPooling2D, ZeroPadding2D, UpSampling2D
from keras.layers.normalization import BatchNormalization
from keras.layers.core import Layer, Activation, Reshape, Permute
def set_architecture(n_classes, img_shape, conv_layers_in_block=1):
model = Sequential()
conv_kernel = (3, 3) # changing will affect padding and stride
init = 'he_normal'
# Encoding
# Block 1
model.add(Conv2D(64, conv_kernel, padding='same', input_shape=img_shape, kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu'))
for l in range(conv_layers_in_block-1):
model.add(Conv2D(64, conv_kernel, padding='same', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2), data_format='channels_first'))
# Block 2
for l in range(conv_layers_in_block):
model.add(Conv2D(128, conv_kernel, padding='same', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2), data_format='channels_first'))
# Block 3
for l in range(conv_layers_in_block):
model.add(Conv2D(256, conv_kernel, padding='same', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2), data_format='channels_first'))
# Block 4
for l in range(conv_layers_in_block):
model.add(Conv2D(512, conv_kernel, padding='same', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
model.add(Activation('relu'))
# Decoding
# Block 4
model.add(ZeroPadding2D((1,1), data_format='channels_first' ))
model.add(Conv2D(512, conv_kernel, padding='valid', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
for l in range(conv_layers_in_block-1):
model.add(Conv2D(512, conv_kernel, padding='same', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
# Block 3
model.add(UpSampling2D((2,2), data_format='channels_first'))
model.add(ZeroPadding2D((1,1), data_format='channels_first'))
model.add(Conv2D(256, conv_kernel, padding='valid', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
for l in range(conv_layers_in_block-1):
model.add(Conv2D(256, conv_kernel, padding='same', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
# Block 2
model.add(UpSampling2D((2,2), data_format='channels_first'))
model.add(ZeroPadding2D((1,1), data_format='channels_first'))
model.add(Conv2D(128, conv_kernel, padding='valid', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
for l in range(conv_layers_in_block-1):
model.add(Conv2D(128, conv_kernel, padding='same', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
# Block 1
model.add(UpSampling2D((2,2), data_format='channels_first'))
model.add(ZeroPadding2D((1,1), data_format='channels_first'))
model.add(Conv2D(64, conv_kernel, padding='valid', data_format='channels_first'))
model.add(BatchNormalization(axis=1))
for l in range(conv_layers_in_block-1):
model.add(Conv2D(64, conv_kernel, padding='same', kernel_initializer=init, data_format='channels_first'))
model.add(BatchNormalization(axis=1))
model.add(Conv2D(n_classes, conv_kernel, padding='same', data_format='channels_first' ))
output_shape = model.output_shape
outputHeight = output_shape[2]
outputWidth = output_shape[3]
model.add(Reshape((-1, outputHeight*outputWidth)))
model.add(Permute((2, 1)))
model.add(Activation('softmax'))
return model
if __name__ == '__main__':
n_classes = 2
img_channels = 3
img_h = 256
img_w = 256
conv_layers_in_block = 1
input_shape = (img_channels, img_h, img_w)
model = set_architecture(n_classes, input_shape, conv_layers_in_block)
| mit |
Godiyos/python-for-android | python3-alpha/python3-src/Lib/lib2to3/fixes/fix_intern.py | 69 | 1402 | # Copyright 2006 Georg Brandl.
# Licensed to PSF under a Contributor Agreement.
"""Fixer for intern().
intern(s) -> sys.intern(s)"""
# Local imports
from .. import pytree
from .. import fixer_base
from ..fixer_util import Name, Attr, touch_import
class FixIntern(fixer_base.BaseFix):
BM_compatible = True
order = "pre"
PATTERN = """
power< 'intern'
trailer< lpar='('
( not(arglist | argument<any '=' any>) obj=any
| obj=arglist<(not argument<any '=' any>) any ','> )
rpar=')' >
after=any*
>
"""
def transform(self, node, results):
syms = self.syms
obj = results["obj"].clone()
if obj.type == syms.arglist:
newarglist = obj.clone()
else:
newarglist = pytree.Node(syms.arglist, [obj.clone()])
after = results["after"]
if after:
after = [n.clone() for n in after]
new = pytree.Node(syms.power,
Attr(Name("sys"), Name("intern")) +
[pytree.Node(syms.trailer,
[results["lpar"].clone(),
newarglist,
results["rpar"].clone()])] + after)
new.prefix = node.prefix
touch_import(None, 'sys', node)
return new
| apache-2.0 |
lgarren/spack | var/spack/repos/builtin/packages/py-cython/package.py | 3 | 1843 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# 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 terms and
# conditions of 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 program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class PyCython(PythonPackage):
"""The Cython compiler for writing C extensions for the Python language."""
homepage = "https://pypi.python.org/pypi/cython"
url = "https://pypi.io/packages/source/c/cython/Cython-0.25.2.tar.gz"
version('0.25.2', '642c81285e1bb833b14ab3f439964086')
version('0.23.5', '66b62989a67c55af016c916da36e7514')
version('0.23.4', '157df1f69bcec6b56fd97e0f2e057f6e')
# These versions contain illegal Python3 code...
version('0.22', '1ae25add4ef7b63ee9b4af697300d6b6')
version('0.21.2', 'd21adb870c75680dc857cd05d41046a4')
| lgpl-2.1 |
sivaprakashniet/push_pull | p2p/lib/python2.7/site-packages/django/contrib/auth/backends.py | 468 | 6114 | from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
class ModelBackend(object):
"""
Authenticates against settings.AUTH_USER_MODEL.
"""
def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
if user.check_password(password):
return user
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
def _get_user_permissions(self, user_obj):
return user_obj.user_permissions.all()
def _get_group_permissions(self, user_obj):
user_groups_field = get_user_model()._meta.get_field('groups')
user_groups_query = 'group__%s' % user_groups_field.related_query_name()
return Permission.objects.filter(**{user_groups_query: user_obj})
def _get_permissions(self, user_obj, obj, from_name):
"""
Returns the permissions of `user_obj` from `from_name`. `from_name` can
be either "group" or "user" to return permissions from
`_get_group_permissions` or `_get_user_permissions` respectively.
"""
if not user_obj.is_active or user_obj.is_anonymous() or obj is not None:
return set()
perm_cache_name = '_%s_perm_cache' % from_name
if not hasattr(user_obj, perm_cache_name):
if user_obj.is_superuser:
perms = Permission.objects.all()
else:
perms = getattr(self, '_get_%s_permissions' % from_name)(user_obj)
perms = perms.values_list('content_type__app_label', 'codename').order_by()
setattr(user_obj, perm_cache_name, set("%s.%s" % (ct, name) for ct, name in perms))
return getattr(user_obj, perm_cache_name)
def get_user_permissions(self, user_obj, obj=None):
"""
Returns a set of permission strings the user `user_obj` has from their
`user_permissions`.
"""
return self._get_permissions(user_obj, obj, 'user')
def get_group_permissions(self, user_obj, obj=None):
"""
Returns a set of permission strings the user `user_obj` has from the
groups they belong.
"""
return self._get_permissions(user_obj, obj, 'group')
def get_all_permissions(self, user_obj, obj=None):
if not user_obj.is_active or user_obj.is_anonymous() or obj is not None:
return set()
if not hasattr(user_obj, '_perm_cache'):
user_obj._perm_cache = self.get_user_permissions(user_obj)
user_obj._perm_cache.update(self.get_group_permissions(user_obj))
return user_obj._perm_cache
def has_perm(self, user_obj, perm, obj=None):
if not user_obj.is_active:
return False
return perm in self.get_all_permissions(user_obj, obj)
def has_module_perms(self, user_obj, app_label):
"""
Returns True if user_obj has any permissions in the given app_label.
"""
if not user_obj.is_active:
return False
for perm in self.get_all_permissions(user_obj):
if perm[:perm.index('.')] == app_label:
return True
return False
def get_user(self, user_id):
UserModel = get_user_model()
try:
return UserModel._default_manager.get(pk=user_id)
except UserModel.DoesNotExist:
return None
class RemoteUserBackend(ModelBackend):
"""
This backend is to be used in conjunction with the ``RemoteUserMiddleware``
found in the middleware module of this package, and is used when the server
is handling authentication outside of Django.
By default, the ``authenticate`` method creates ``User`` objects for
usernames that don't already exist in the database. Subclasses can disable
this behavior by setting the ``create_unknown_user`` attribute to
``False``.
"""
# Create a User object if not already in the database?
create_unknown_user = True
def authenticate(self, remote_user):
"""
The username passed as ``remote_user`` is considered trusted. This
method simply returns the ``User`` object with the given username,
creating a new ``User`` object if ``create_unknown_user`` is ``True``.
Returns None if ``create_unknown_user`` is ``False`` and a ``User``
object with the given username is not found in the database.
"""
if not remote_user:
return
user = None
username = self.clean_username(remote_user)
UserModel = get_user_model()
# Note that this could be accomplished in one try-except clause, but
# instead we use get_or_create when creating unknown users since it has
# built-in safeguards for multiple threads.
if self.create_unknown_user:
user, created = UserModel._default_manager.get_or_create(**{
UserModel.USERNAME_FIELD: username
})
if created:
user = self.configure_user(user)
else:
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
pass
return user
def clean_username(self, username):
"""
Performs any cleaning on the "username" prior to using it to get or
create the user object. Returns the cleaned username.
By default, returns the username unchanged.
"""
return username
def configure_user(self, user):
"""
Configures a user after creation and returns the updated user.
By default, returns the user unmodified.
"""
return user
| bsd-3-clause |
paboldin/rally | tests/unit/verification/fakes.py | 15 | 1605 | # Copyright 2014: Mirantis 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.
def get_fake_test_case():
return {
"total": {
"failures": 1,
"tests": 2,
"errors": 0,
"time": 1.412},
"test_cases": {
"fake.failed.TestCase.with_StringException[gate,negative]": {
"name":
"fake.failed.TestCase.with_StringException[gate,negative]",
"failure": {
"type": "testtools.testresult.real._StringException",
"log":
("_StringException: Empty attachments:\nOops...There "
"was supposed to be fake traceback, but it is not.\n")
},
"time": 0.706,
"status": "FAIL"},
"fake.successful.TestCase.fake_test[gate,negative]": {
"name": "fake.successful.TestCase.fake_test[gate,negative]",
"time": 0.706,
"status": "OK"
}
}
}
| apache-2.0 |
laurence6/Telegram-bot | telegram/core/main.py | 2 | 5586 | import importlib
import logging
import threading
from telegram.conf.settings import SETTINGS
from telegram.core.bot import BOT
from telegram.core.message import RequestMessage, ResponseMessage
class RequestQueue(object):
def __init__(self):
self.requests_list = []
self.requests_list_condition = threading.Condition(threading.Lock())
self.processing = []
self.processing_lock = threading.Lock()
def get(self):
while 1:
if self.requests_list == []:
with self.requests_list_condition:
self.requests_list_condition.wait()
with self.requests_list_condition:
for n, i in enumerate(self.requests_list):
message_id = '%s%s' % (i['chat']['id'], i['from']['id'])
with self.processing_lock:
if not message_id in self.processing:
self.processing.append(message_id)
ret = self.requests_list.pop(n)
return ret
self.requests_list_condition.wait()
def done(self, message_id):
with self.processing_lock:
self.processing.remove(message_id)
with self.requests_list_condition:
self.requests_list_condition.notify_all()
def put(self, request):
self.requests_list.append(request)
with self.requests_list_condition:
self.requests_list_condition.notify_all()
def load_resolver():
resolver_mod = importlib.import_module(SETTINGS.RESOLVER)
global resolver
resolver = getattr(resolver_mod, 'resolve')
def load_middleware():
global request_middleware
global handler_middleware
global response_middleware
request_middleware = []
handler_middleware = []
response_middleware = []
for middleware in SETTINGS.MIDDLEWARES:
mw_mod, mw_class = middleware.rsplit('.', 1)
mw_mod = importlib.import_module(mw_mod)
mw_class = getattr(mw_mod, mw_class)
mw = mw_class()
if hasattr(mw, 'process_request'):
request_middleware.append(mw.process_request)
if hasattr(mw, 'process_handler'):
handler_middleware.append(mw.process_handler)
if hasattr(mw, 'process_response'):
response_middleware.insert(0, mw.process_response)
class HandleMessage(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
load_resolver()
self.resolver = globals()['resolver']
load_middleware()
self.request_middleware = globals()['request_middleware']
self.handler_middleware = globals()['handler_middleware']
self.response_middleware = globals()['response_middleware']
def run(self):
logger = logging.getLogger('handle_message')
while 1:
try:
request = self.queue.get()
chat_and_from_id = '%s%s' % (request['chat']['id'], request['from']['id'])
response = None
for middleware in self.request_middleware:
response = middleware(request)
if not response is None:
break
if response is None:
handler, handler_args = self.resolver(request)
for middleware in self.handler_middleware:
response = middleware(request, handler, handler_args)
if not response is None:
break
if response is None:
response = handler(request, **handler_args)
for middleware in self.response_middleware:
response = middleware(request, response)
if isinstance(response, ResponseMessage):
getattr(BOT, response.method)(**response)
self.queue.done(chat_and_from_id)
except KeyboardInterrupt:
return
except Exception as e:
logger.error(e)
class GetUpdates(threading.Thread):
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
logger = logging.getLogger('get_updates')
offset = 0
limit = 100
timeout = 60
while 1:
try:
response = BOT.getUpdates(offset, limit, timeout)
if not response['ok']:
logger.warning('getUpdates: %s', response['description'])
continue
result = response['result']
if result:
for r in result:
self.queue.put(RequestMessage(r['message']))
offset = result[-1]['update_id']+1
else:
logger.info('No new updates')
except KeyboardInterrupt:
return
except Exception as e:
logger.error(e)
def execute():
logger = logging.getLogger('execute')
try:
request_queue = RequestQueue()
processed = [GetUpdates(request_queue)]
for i in range(SETTINGS.WORKER_PROCESSES):
processed.append(HandleMessage(request_queue))
for i in processed:
i.start()
for i in processed:
i.join()
except KeyboardInterrupt:
logger.info('Keyboard interrupt received')
exit()
except Exception as e:
logger.error(e)
| gpl-3.0 |
mancoast/CPythonPyc_test | fail/340_test_gdb.py | 12 | 35639 | # Verify that gdb can pretty-print the various PyObject* types
#
# The code for testing gdb was adapted from similar work in Unladen Swallow's
# Lib/test/test_jit_gdb.py
import os
import re
import pprint
import subprocess
import sys
import sysconfig
import unittest
import locale
# Is this Python configured to support threads?
try:
import _thread
except ImportError:
_thread = None
from test import support
from test.support import run_unittest, findfile, python_is_optimized
try:
gdb_version, _ = subprocess.Popen(["gdb", "--version"],
stdout=subprocess.PIPE).communicate()
except OSError:
# This is what "no gdb" looks like. There may, however, be other
# errors that manifest this way too.
raise unittest.SkipTest("Couldn't find gdb on the path")
gdb_version_number = re.search(b"^GNU gdb [^\d]*(\d+)\.(\d)", gdb_version)
gdb_major_version = int(gdb_version_number.group(1))
gdb_minor_version = int(gdb_version_number.group(2))
if gdb_major_version < 7:
raise unittest.SkipTest("gdb versions before 7.0 didn't support python embedding"
" Saw:\n" + gdb_version.decode('ascii', 'replace'))
if not sysconfig.is_python_build():
raise unittest.SkipTest("test_gdb only works on source builds at the moment.")
# Location of custom hooks file in a repository checkout.
checkout_hook_path = os.path.join(os.path.dirname(sys.executable),
'python-gdb.py')
PYTHONHASHSEED = '123'
def run_gdb(*args, **env_vars):
"""Runs gdb in --batch mode with the additional arguments given by *args.
Returns its (stdout, stderr) decoded from utf-8 using the replace handler.
"""
if env_vars:
env = os.environ.copy()
env.update(env_vars)
else:
env = None
base_cmd = ('gdb', '--batch')
if (gdb_major_version, gdb_minor_version) >= (7, 4):
base_cmd += ('-iex', 'add-auto-load-safe-path ' + checkout_hook_path)
out, err = subprocess.Popen(base_cmd + args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
).communicate()
return out.decode('utf-8', 'replace'), err.decode('utf-8', 'replace')
# Verify that "gdb" was built with the embedded python support enabled:
gdbpy_version, _ = run_gdb("--eval-command=python import sys; print(sys.version_info)")
if not gdbpy_version:
raise unittest.SkipTest("gdb not built with embedded python support")
# Verify that "gdb" can load our custom hooks, as OS security settings may
# disallow this without a customised .gdbinit.
cmd = ['--args', sys.executable]
_, gdbpy_errors = run_gdb('--args', sys.executable)
if "auto-loading has been declined" in gdbpy_errors:
msg = "gdb security settings prevent use of custom hooks: "
raise unittest.SkipTest(msg + gdbpy_errors.rstrip())
def gdb_has_frame_select():
# Does this build of gdb have gdb.Frame.select ?
stdout, _ = run_gdb("--eval-command=python print(dir(gdb.Frame))")
m = re.match(r'.*\[(.*)\].*', stdout)
if not m:
raise unittest.SkipTest("Unable to parse output from gdb.Frame.select test")
gdb_frame_dir = m.group(1).split(', ')
return "'select'" in gdb_frame_dir
HAS_PYUP_PYDOWN = gdb_has_frame_select()
BREAKPOINT_FN='builtin_id'
class DebuggerTests(unittest.TestCase):
"""Test that the debugger can debug Python."""
def get_stack_trace(self, source=None, script=None,
breakpoint=BREAKPOINT_FN,
cmds_after_breakpoint=None,
import_site=False):
'''
Run 'python -c SOURCE' under gdb with a breakpoint.
Support injecting commands after the breakpoint is reached
Returns the stdout from gdb
cmds_after_breakpoint: if provided, a list of strings: gdb commands
'''
# We use "set breakpoint pending yes" to avoid blocking with a:
# Function "foo" not defined.
# Make breakpoint pending on future shared library load? (y or [n])
# error, which typically happens python is dynamically linked (the
# breakpoints of interest are to be found in the shared library)
# When this happens, we still get:
# Function "textiowrapper_write" not defined.
# emitted to stderr each time, alas.
# Initially I had "--eval-command=continue" here, but removed it to
# avoid repeated print breakpoints when traversing hierarchical data
# structures
# Generate a list of commands in gdb's language:
commands = ['set breakpoint pending yes',
'break %s' % breakpoint,
'run']
if cmds_after_breakpoint:
commands += cmds_after_breakpoint
else:
commands += ['backtrace']
# print commands
# Use "commands" to generate the arguments with which to invoke "gdb":
args = ["gdb", "--batch"]
args += ['--eval-command=%s' % cmd for cmd in commands]
args += ["--args",
sys.executable]
if not import_site:
# -S suppresses the default 'import site'
args += ["-S"]
if source:
args += ["-c", source]
elif script:
args += [script]
# print args
# print (' '.join(args))
# Use "args" to invoke gdb, capturing stdout, stderr:
out, err = run_gdb(*args, PYTHONHASHSEED=PYTHONHASHSEED)
errlines = err.splitlines()
unexpected_errlines = []
# Ignore some benign messages on stderr.
ignore_patterns = (
'Function "%s" not defined.' % breakpoint,
"warning: no loadable sections found in added symbol-file"
" system-supplied DSO",
"warning: Unable to find libthread_db matching"
" inferior's thread library, thread debugging will"
" not be available.",
"warning: Cannot initialize thread debugging"
" library: Debugger service failed",
'warning: Could not load shared library symbols for '
'linux-vdso.so',
'warning: Could not load shared library symbols for '
'linux-gate.so',
'Do you need "set solib-search-path" or '
'"set sysroot"?',
'warning: Source file is more recent than executable.',
# Issue #19753: missing symbols on System Z
'Missing separate debuginfo for ',
'Try: zypper install -C ',
)
for line in errlines:
if not line.startswith(ignore_patterns):
unexpected_errlines.append(line)
# Ensure no unexpected error messages:
self.assertEqual(unexpected_errlines, [])
return out
def get_gdb_repr(self, source,
cmds_after_breakpoint=None,
import_site=False):
# Given an input python source representation of data,
# run "python -c'id(DATA)'" under gdb with a breakpoint on
# builtin_id and scrape out gdb's representation of the "op"
# parameter, and verify that the gdb displays the same string
#
# Verify that the gdb displays the expected string
#
# For a nested structure, the first time we hit the breakpoint will
# give us the top-level structure
# NOTE: avoid decoding too much of the traceback as some
# undecodable characters may lurk there in optimized mode
# (issue #19743).
cmds_after_breakpoint = cmds_after_breakpoint or ["backtrace 1"]
gdb_output = self.get_stack_trace(source, breakpoint=BREAKPOINT_FN,
cmds_after_breakpoint=cmds_after_breakpoint,
import_site=import_site)
# gdb can insert additional '\n' and space characters in various places
# in its output, depending on the width of the terminal it's connected
# to (using its "wrap_here" function)
m = re.match('.*#0\s+builtin_id\s+\(self\=.*,\s+v=\s*(.*?)\)\s+at\s+\S*Python/bltinmodule.c.*',
gdb_output, re.DOTALL)
if not m:
self.fail('Unexpected gdb output: %r\n%s' % (gdb_output, gdb_output))
return m.group(1), gdb_output
def assertEndsWith(self, actual, exp_end):
'''Ensure that the given "actual" string ends with "exp_end"'''
self.assertTrue(actual.endswith(exp_end),
msg='%r did not end with %r' % (actual, exp_end))
def assertMultilineMatches(self, actual, pattern):
m = re.match(pattern, actual, re.DOTALL)
if not m:
self.fail(msg='%r did not match %r' % (actual, pattern))
def get_sample_script(self):
return findfile('gdb_sample.py')
class PrettyPrintTests(DebuggerTests):
def test_getting_backtrace(self):
gdb_output = self.get_stack_trace('id(42)')
self.assertTrue(BREAKPOINT_FN in gdb_output)
def assertGdbRepr(self, val, exp_repr=None):
# Ensure that gdb's rendering of the value in a debugged process
# matches repr(value) in this process:
gdb_repr, gdb_output = self.get_gdb_repr('id(' + ascii(val) + ')')
if not exp_repr:
exp_repr = repr(val)
self.assertEqual(gdb_repr, exp_repr,
('%r did not equal expected %r; full output was:\n%s'
% (gdb_repr, exp_repr, gdb_output)))
def test_int(self):
'Verify the pretty-printing of various int values'
self.assertGdbRepr(42)
self.assertGdbRepr(0)
self.assertGdbRepr(-7)
self.assertGdbRepr(1000000000000)
self.assertGdbRepr(-1000000000000000)
def test_singletons(self):
'Verify the pretty-printing of True, False and None'
self.assertGdbRepr(True)
self.assertGdbRepr(False)
self.assertGdbRepr(None)
def test_dicts(self):
'Verify the pretty-printing of dictionaries'
self.assertGdbRepr({})
self.assertGdbRepr({'foo': 'bar'}, "{'foo': 'bar'}")
self.assertGdbRepr({'foo': 'bar', 'douglas': 42}, "{'douglas': 42, 'foo': 'bar'}")
def test_lists(self):
'Verify the pretty-printing of lists'
self.assertGdbRepr([])
self.assertGdbRepr(list(range(5)))
def test_bytes(self):
'Verify the pretty-printing of bytes'
self.assertGdbRepr(b'')
self.assertGdbRepr(b'And now for something hopefully the same')
self.assertGdbRepr(b'string with embedded NUL here \0 and then some more text')
self.assertGdbRepr(b'this is a tab:\t'
b' this is a slash-N:\n'
b' this is a slash-R:\r'
)
self.assertGdbRepr(b'this is byte 255:\xff and byte 128:\x80')
self.assertGdbRepr(bytes([b for b in range(255)]))
def test_strings(self):
'Verify the pretty-printing of unicode strings'
encoding = locale.getpreferredencoding()
def check_repr(text):
try:
text.encode(encoding)
printable = True
except UnicodeEncodeError:
self.assertGdbRepr(text, ascii(text))
else:
self.assertGdbRepr(text)
self.assertGdbRepr('')
self.assertGdbRepr('And now for something hopefully the same')
self.assertGdbRepr('string with embedded NUL here \0 and then some more text')
# Test printing a single character:
# U+2620 SKULL AND CROSSBONES
check_repr('\u2620')
# Test printing a Japanese unicode string
# (I believe this reads "mojibake", using 3 characters from the CJK
# Unified Ideographs area, followed by U+3051 HIRAGANA LETTER KE)
check_repr('\u6587\u5b57\u5316\u3051')
# Test a character outside the BMP:
# U+1D121 MUSICAL SYMBOL C CLEF
# This is:
# UTF-8: 0xF0 0x9D 0x84 0xA1
# UTF-16: 0xD834 0xDD21
check_repr(chr(0x1D121))
def test_tuples(self):
'Verify the pretty-printing of tuples'
self.assertGdbRepr(tuple(), '()')
self.assertGdbRepr((1,), '(1,)')
self.assertGdbRepr(('foo', 'bar', 'baz'))
def test_sets(self):
'Verify the pretty-printing of sets'
if (gdb_major_version, gdb_minor_version) < (7, 3):
self.skipTest("pretty-printing of sets needs gdb 7.3 or later")
self.assertGdbRepr(set(), 'set()')
self.assertGdbRepr(set(['a', 'b']), "{'a', 'b'}")
self.assertGdbRepr(set([4, 5, 6]), "{4, 5, 6}")
# Ensure that we handle sets containing the "dummy" key value,
# which happens on deletion:
gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
s.remove('a')
id(s)''')
self.assertEqual(gdb_repr, "{'b'}")
def test_frozensets(self):
'Verify the pretty-printing of frozensets'
if (gdb_major_version, gdb_minor_version) < (7, 3):
self.skipTest("pretty-printing of frozensets needs gdb 7.3 or later")
self.assertGdbRepr(frozenset(), 'frozenset()')
self.assertGdbRepr(frozenset(['a', 'b']), "frozenset({'a', 'b'})")
self.assertGdbRepr(frozenset([4, 5, 6]), "frozenset({4, 5, 6})")
def test_exceptions(self):
# Test a RuntimeError
gdb_repr, gdb_output = self.get_gdb_repr('''
try:
raise RuntimeError("I am an error")
except RuntimeError as e:
id(e)
''')
self.assertEqual(gdb_repr,
"RuntimeError('I am an error',)")
# Test division by zero:
gdb_repr, gdb_output = self.get_gdb_repr('''
try:
a = 1 / 0
except ZeroDivisionError as e:
id(e)
''')
self.assertEqual(gdb_repr,
"ZeroDivisionError('division by zero',)")
def test_modern_class(self):
'Verify the pretty-printing of new-style class instances'
gdb_repr, gdb_output = self.get_gdb_repr('''
class Foo:
pass
foo = Foo()
foo.an_int = 42
id(foo)''')
m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
self.assertTrue(m,
msg='Unexpected new-style class rendering %r' % gdb_repr)
def test_subclassing_list(self):
'Verify the pretty-printing of an instance of a list subclass'
gdb_repr, gdb_output = self.get_gdb_repr('''
class Foo(list):
pass
foo = Foo()
foo += [1, 2, 3]
foo.an_int = 42
id(foo)''')
m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
self.assertTrue(m,
msg='Unexpected new-style class rendering %r' % gdb_repr)
def test_subclassing_tuple(self):
'Verify the pretty-printing of an instance of a tuple subclass'
# This should exercise the negative tp_dictoffset code in the
# new-style class support
gdb_repr, gdb_output = self.get_gdb_repr('''
class Foo(tuple):
pass
foo = Foo((1, 2, 3))
foo.an_int = 42
id(foo)''')
m = re.match(r'<Foo\(an_int=42\) at remote 0x-?[0-9a-f]+>', gdb_repr)
self.assertTrue(m,
msg='Unexpected new-style class rendering %r' % gdb_repr)
def assertSane(self, source, corruption, exprepr=None):
'''Run Python under gdb, corrupting variables in the inferior process
immediately before taking a backtrace.
Verify that the variable's representation is the expected failsafe
representation'''
if corruption:
cmds_after_breakpoint=[corruption, 'backtrace']
else:
cmds_after_breakpoint=['backtrace']
gdb_repr, gdb_output = \
self.get_gdb_repr(source,
cmds_after_breakpoint=cmds_after_breakpoint)
if exprepr:
if gdb_repr == exprepr:
# gdb managed to print the value in spite of the corruption;
# this is good (see http://bugs.python.org/issue8330)
return
# Match anything for the type name; 0xDEADBEEF could point to
# something arbitrary (see http://bugs.python.org/issue8330)
pattern = '<.* at remote 0x-?[0-9a-f]+>'
m = re.match(pattern, gdb_repr)
if not m:
self.fail('Unexpected gdb representation: %r\n%s' % \
(gdb_repr, gdb_output))
def test_NULL_ptr(self):
'Ensure that a NULL PyObject* is handled gracefully'
gdb_repr, gdb_output = (
self.get_gdb_repr('id(42)',
cmds_after_breakpoint=['set variable v=0',
'backtrace'])
)
self.assertEqual(gdb_repr, '0x0')
def test_NULL_ob_type(self):
'Ensure that a PyObject* with NULL ob_type is handled gracefully'
self.assertSane('id(42)',
'set v->ob_type=0')
def test_corrupt_ob_type(self):
'Ensure that a PyObject* with a corrupt ob_type is handled gracefully'
self.assertSane('id(42)',
'set v->ob_type=0xDEADBEEF',
exprepr='42')
def test_corrupt_tp_flags(self):
'Ensure that a PyObject* with a type with corrupt tp_flags is handled'
self.assertSane('id(42)',
'set v->ob_type->tp_flags=0x0',
exprepr='42')
def test_corrupt_tp_name(self):
'Ensure that a PyObject* with a type with corrupt tp_name is handled'
self.assertSane('id(42)',
'set v->ob_type->tp_name=0xDEADBEEF',
exprepr='42')
def test_builtins_help(self):
'Ensure that the new-style class _Helper in site.py can be handled'
# (this was the issue causing tracebacks in
# http://bugs.python.org/issue8032#msg100537 )
gdb_repr, gdb_output = self.get_gdb_repr('id(__builtins__.help)', import_site=True)
m = re.match(r'<_Helper at remote 0x-?[0-9a-f]+>', gdb_repr)
self.assertTrue(m,
msg='Unexpected rendering %r' % gdb_repr)
def test_selfreferential_list(self):
'''Ensure that a reference loop involving a list doesn't lead proxyval
into an infinite loop:'''
gdb_repr, gdb_output = \
self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
gdb_repr, gdb_output = \
self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
def test_selfreferential_dict(self):
'''Ensure that a reference loop involving a dict doesn't lead proxyval
into an infinite loop:'''
gdb_repr, gdb_output = \
self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
def test_selfreferential_old_style_instance(self):
gdb_repr, gdb_output = \
self.get_gdb_repr('''
class Foo:
pass
foo = Foo()
foo.an_attr = foo
id(foo)''')
self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
gdb_repr),
'Unexpected gdb representation: %r\n%s' % \
(gdb_repr, gdb_output))
def test_selfreferential_new_style_instance(self):
gdb_repr, gdb_output = \
self.get_gdb_repr('''
class Foo(object):
pass
foo = Foo()
foo.an_attr = foo
id(foo)''')
self.assertTrue(re.match('<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>',
gdb_repr),
'Unexpected gdb representation: %r\n%s' % \
(gdb_repr, gdb_output))
gdb_repr, gdb_output = \
self.get_gdb_repr('''
class Foo(object):
pass
a = Foo()
b = Foo()
a.an_attr = b
b.an_attr = a
id(a)''')
self.assertTrue(re.match('<Foo\(an_attr=<Foo\(an_attr=<\.\.\.>\) at remote 0x-?[0-9a-f]+>\) at remote 0x-?[0-9a-f]+>',
gdb_repr),
'Unexpected gdb representation: %r\n%s' % \
(gdb_repr, gdb_output))
def test_truncation(self):
'Verify that very long output is truncated'
gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
self.assertEqual(gdb_repr,
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
"14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
"27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
"40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
"53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
"66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
"79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
"92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
"104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
"114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
"124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
"134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
"144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
"154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
"164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
"174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
"184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
"194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
"204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
"214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
"224, 225, 226...(truncated)")
self.assertEqual(len(gdb_repr),
1024 + len('...(truncated)'))
def test_builtin_method(self):
gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')
self.assertTrue(re.match('<built-in method readlines of _io.TextIOWrapper object at remote 0x-?[0-9a-f]+>',
gdb_repr),
'Unexpected gdb representation: %r\n%s' % \
(gdb_repr, gdb_output))
def test_frames(self):
gdb_output = self.get_stack_trace('''
def foo(a, b, c):
pass
foo(3, 4, 5)
id(foo.__code__)''',
breakpoint='builtin_id',
cmds_after_breakpoint=['print (PyFrameObject*)(((PyCodeObject*)v)->co_zombieframe)']
)
self.assertTrue(re.match('.*\s+\$1 =\s+Frame 0x-?[0-9a-f]+, for file <string>, line 3, in foo \(\)\s+.*',
gdb_output,
re.DOTALL),
'Unexpected gdb representation: %r\n%s' % (gdb_output, gdb_output))
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
class PyListTests(DebuggerTests):
def assertListing(self, expected, actual):
self.assertEndsWith(actual, expected)
def test_basic_command(self):
'Verify that the "py-list" command works'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-list'])
self.assertListing(' 5 \n'
' 6 def bar(a, b, c):\n'
' 7 baz(a, b, c)\n'
' 8 \n'
' 9 def baz(*args):\n'
' >10 id(42)\n'
' 11 \n'
' 12 foo(1, 2, 3)\n',
bt)
def test_one_abs_arg(self):
'Verify the "py-list" command with one absolute argument'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-list 9'])
self.assertListing(' 9 def baz(*args):\n'
' >10 id(42)\n'
' 11 \n'
' 12 foo(1, 2, 3)\n',
bt)
def test_two_abs_args(self):
'Verify the "py-list" command with two absolute arguments'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-list 1,3'])
self.assertListing(' 1 # Sample script for use by test_gdb.py\n'
' 2 \n'
' 3 def foo(a, b, c):\n',
bt)
class StackNavigationTests(DebuggerTests):
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
def test_pyup_command(self):
'Verify that the "py-up" command works'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-up'])
self.assertMultilineMatches(bt,
r'''^.*
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
baz\(a, b, c\)
$''')
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
def test_down_at_bottom(self):
'Verify handling of "py-down" at the bottom of the stack'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-down'])
self.assertEndsWith(bt,
'Unable to find a newer python frame\n')
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
def test_up_at_top(self):
'Verify handling of "py-up" at the top of the stack'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-up'] * 4)
self.assertEndsWith(bt,
'Unable to find an older python frame\n')
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
def test_up_then_down(self):
'Verify "py-up" followed by "py-down"'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-up', 'py-down'])
self.assertMultilineMatches(bt,
r'''^.*
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
baz\(a, b, c\)
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 10, in baz \(args=\(1, 2, 3\)\)
id\(42\)
$''')
class PyBtTests(DebuggerTests):
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
def test_bt(self):
'Verify that the "py-bt" command works'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-bt'])
self.assertMultilineMatches(bt,
r'''^.*
Traceback \(most recent call first\):
File ".*gdb_sample.py", line 10, in baz
id\(42\)
File ".*gdb_sample.py", line 7, in bar
baz\(a, b, c\)
File ".*gdb_sample.py", line 4, in foo
bar\(a, b, c\)
File ".*gdb_sample.py", line 12, in <module>
foo\(1, 2, 3\)
''')
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
def test_bt_full(self):
'Verify that the "py-bt-full" command works'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-bt-full'])
self.assertMultilineMatches(bt,
r'''^.*
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 7, in bar \(a=1, b=2, c=3\)
baz\(a, b, c\)
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 4, in foo \(a=1, b=2, c=3\)
bar\(a, b, c\)
#[0-9]+ Frame 0x-?[0-9a-f]+, for file .*gdb_sample.py, line 12, in <module> \(\)
foo\(1, 2, 3\)
''')
@unittest.skipUnless(_thread,
"Python was compiled without thread support")
def test_threads(self):
'Verify that "py-bt" indicates threads that are waiting for the GIL'
cmd = '''
from threading import Thread
class TestThread(Thread):
# These threads would run forever, but we'll interrupt things with the
# debugger
def run(self):
i = 0
while 1:
i += 1
t = {}
for i in range(4):
t[i] = TestThread()
t[i].start()
# Trigger a breakpoint on the main thread
id(42)
'''
# Verify with "py-bt":
gdb_output = self.get_stack_trace(cmd,
cmds_after_breakpoint=['thread apply all py-bt'])
self.assertIn('Waiting for the GIL', gdb_output)
# Verify with "py-bt-full":
gdb_output = self.get_stack_trace(cmd,
cmds_after_breakpoint=['thread apply all py-bt-full'])
self.assertIn('Waiting for the GIL', gdb_output)
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
# Some older versions of gdb will fail with
# "Cannot find new threads: generic error"
# unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
@unittest.skipUnless(_thread,
"Python was compiled without thread support")
def test_gc(self):
'Verify that "py-bt" indicates if a thread is garbage-collecting'
cmd = ('from gc import collect\n'
'id(42)\n'
'def foo():\n'
' collect()\n'
'def bar():\n'
' foo()\n'
'bar()\n')
# Verify with "py-bt":
gdb_output = self.get_stack_trace(cmd,
cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt'],
)
self.assertIn('Garbage-collecting', gdb_output)
# Verify with "py-bt-full":
gdb_output = self.get_stack_trace(cmd,
cmds_after_breakpoint=['break update_refs', 'continue', 'py-bt-full'],
)
self.assertIn('Garbage-collecting', gdb_output)
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
# Some older versions of gdb will fail with
# "Cannot find new threads: generic error"
# unless we add LD_PRELOAD=PATH-TO-libpthread.so.1 as a workaround
@unittest.skipUnless(_thread,
"Python was compiled without thread support")
def test_pycfunction(self):
'Verify that "py-bt" displays invocations of PyCFunction instances'
cmd = ('from time import sleep\n'
'def foo():\n'
' sleep(1)\n'
'def bar():\n'
' foo()\n'
'bar()\n')
# Verify with "py-bt":
gdb_output = self.get_stack_trace(cmd,
breakpoint='time_sleep',
cmds_after_breakpoint=['bt', 'py-bt'],
)
self.assertIn('<built-in method sleep', gdb_output)
# Verify with "py-bt-full":
gdb_output = self.get_stack_trace(cmd,
breakpoint='time_sleep',
cmds_after_breakpoint=['py-bt-full'],
)
self.assertIn('#0 <built-in method sleep', gdb_output)
class PyPrintTests(DebuggerTests):
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
def test_basic_command(self):
'Verify that the "py-print" command works'
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-print args'])
self.assertMultilineMatches(bt,
r".*\nlocal 'args' = \(1, 2, 3\)\n.*")
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
def test_print_after_up(self):
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-up', 'py-print c', 'py-print b', 'py-print a'])
self.assertMultilineMatches(bt,
r".*\nlocal 'c' = 3\nlocal 'b' = 2\nlocal 'a' = 1\n.*")
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
def test_printing_global(self):
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-print __name__'])
self.assertMultilineMatches(bt,
r".*\nglobal '__name__' = '__main__'\n.*")
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
def test_printing_builtin(self):
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-print len'])
self.assertMultilineMatches(bt,
r".*\nbuiltin 'len' = <built-in method len of module object at remote 0x-?[0-9a-f]+>\n.*")
class PyLocalsTests(DebuggerTests):
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
def test_basic_command(self):
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-locals'])
self.assertMultilineMatches(bt,
r".*\nargs = \(1, 2, 3\)\n.*")
@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
@unittest.skipIf(python_is_optimized(),
"Python was compiled with optimizations")
def test_locals_after_up(self):
bt = self.get_stack_trace(script=self.get_sample_script(),
cmds_after_breakpoint=['py-up', 'py-locals'])
self.assertMultilineMatches(bt,
r".*\na = 1\nb = 2\nc = 3\n.*")
def test_main():
if support.verbose:
print("GDB version:")
for line in os.fsdecode(gdb_version).splitlines():
print(" " * 4 + line)
run_unittest(PrettyPrintTests,
PyListTests,
StackNavigationTests,
PyBtTests,
PyPrintTests,
PyLocalsTests
)
if __name__ == "__main__":
test_main()
| gpl-3.0 |
risicle/django | tests/model_validation/tests.py | 292 | 2117 | from django.core import management
from django.core.checks import Error, run_checks
from django.db.models.signals import post_init
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils import six
class OnPostInit(object):
def __call__(self, **kwargs):
pass
def on_post_init(**kwargs):
pass
@override_settings(
INSTALLED_APPS=['django.contrib.auth', 'django.contrib.contenttypes'],
SILENCED_SYSTEM_CHECKS=['fields.W342'], # ForeignKey(unique=True)
)
class ModelValidationTest(SimpleTestCase):
def test_models_validate(self):
# All our models should validate properly
# Validation Tests:
# * choices= Iterable of Iterables
# See: https://code.djangoproject.com/ticket/20430
# * related_name='+' doesn't clash with another '+'
# See: https://code.djangoproject.com/ticket/21375
management.call_command("check", stdout=six.StringIO())
def test_model_signal(self):
unresolved_references = post_init.unresolved_references.copy()
post_init.connect(on_post_init, sender='missing-app.Model')
post_init.connect(OnPostInit(), sender='missing-app.Model')
errors = run_checks()
expected = [
Error(
"The 'on_post_init' function was connected to the 'post_init' "
"signal with a lazy reference to the 'missing-app.Model' "
"sender, which has not been installed.",
hint=None,
obj='model_validation.tests',
id='signals.E001',
),
Error(
"An instance of the 'OnPostInit' class was connected to "
"the 'post_init' signal with a lazy reference to the "
"'missing-app.Model' sender, which has not been installed.",
hint=None,
obj='model_validation.tests',
id='signals.E001',
)
]
self.assertEqual(errors, expected)
post_init.unresolved_references = unresolved_references
| bsd-3-clause |
dennybaa/st2 | st2common/tests/unit/test_persistence.py | 4 | 8300 | # Licensed to the StackStorm, Inc ('StackStorm') 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.
import uuid
import datetime
import bson
from st2tests import DbTestCase
from st2common.util import date as date_utils
from tests.unit.base import FakeModel, FakeModelDB
class TestPersistence(DbTestCase):
@classmethod
def setUpClass(cls):
super(TestPersistence, cls).setUpClass()
cls.access = FakeModel()
def tearDown(self):
FakeModelDB.drop_collection()
super(TestPersistence, self).tearDown()
def test_crud(self):
obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'a': 1})
obj1 = self.access.add_or_update(obj1)
obj2 = self.access.get(name=obj1.name)
self.assertIsNotNone(obj2)
self.assertEqual(obj1.id, obj2.id)
self.assertEqual(obj1.name, obj2.name)
self.assertDictEqual(obj1.context, obj2.context)
obj1.name = uuid.uuid4().hex
obj1 = self.access.add_or_update(obj1)
obj2 = self.access.get(name=obj1.name)
self.assertIsNotNone(obj2)
self.assertEqual(obj1.id, obj2.id)
self.assertEqual(obj1.name, obj2.name)
self.assertDictEqual(obj1.context, obj2.context)
self.access.delete(obj1)
obj2 = self.access.get(name=obj1.name)
self.assertIsNone(obj2)
def test_count(self):
obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
obj1 = self.access.add_or_update(obj1)
obj2 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'stanley'})
obj2 = self.access.add_or_update(obj2)
self.assertEqual(self.access.count(), 2)
def test_get_all(self):
obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
obj1 = self.access.add_or_update(obj1)
obj2 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'stanley'})
obj2 = self.access.add_or_update(obj2)
objs = self.access.get_all()
self.assertIsNotNone(objs)
self.assertEqual(len(objs), 2)
self.assertListEqual(list(objs), [obj1, obj2])
def test_query_by_id(self):
obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
obj1 = self.access.add_or_update(obj1)
obj2 = self.access.get_by_id(str(obj1.id))
self.assertIsNotNone(obj2)
self.assertEqual(obj1.id, obj2.id)
self.assertEqual(obj1.name, obj2.name)
self.assertDictEqual(obj1.context, obj2.context)
self.assertRaises(ValueError, self.access.get_by_id, str(bson.ObjectId()))
def test_query_by_name(self):
obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
obj1 = self.access.add_or_update(obj1)
obj2 = self.access.get_by_name(obj1.name)
self.assertIsNotNone(obj2)
self.assertEqual(obj1.id, obj2.id)
self.assertEqual(obj1.name, obj2.name)
self.assertDictEqual(obj1.context, obj2.context)
self.assertRaises(ValueError, self.access.get_by_name, uuid.uuid4().hex)
def test_query_filter(self):
obj1 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'system'})
obj1 = self.access.add_or_update(obj1)
obj2 = FakeModelDB(name=uuid.uuid4().hex, context={'user': 'stanley'})
obj2 = self.access.add_or_update(obj2)
objs = self.access.query(context__user='system')
self.assertIsNotNone(objs)
self.assertGreater(len(objs), 0)
self.assertEqual(obj1.id, objs[0].id)
self.assertEqual(obj1.name, objs[0].name)
self.assertDictEqual(obj1.context, objs[0].context)
def test_null_filter(self):
obj1 = FakeModelDB(name=uuid.uuid4().hex)
obj1 = self.access.add_or_update(obj1)
objs = self.access.query(index='null')
self.assertEqual(len(objs), 1)
self.assertEqual(obj1.id, objs[0].id)
self.assertEqual(obj1.name, objs[0].name)
self.assertIsNone(getattr(obj1, 'index', None))
objs = self.access.query(index=None)
self.assertEqual(len(objs), 1)
self.assertEqual(obj1.id, objs[0].id)
self.assertEqual(obj1.name, objs[0].name)
self.assertIsNone(getattr(obj1, 'index', None))
def test_datetime_range(self):
base = date_utils.add_utc_tz(datetime.datetime(2014, 12, 25, 0, 0, 0))
for i in range(60):
timestamp = base + datetime.timedelta(seconds=i)
obj = FakeModelDB(name=uuid.uuid4().hex, timestamp=timestamp)
self.access.add_or_update(obj)
dt_range = '2014-12-25T00:00:10Z..2014-12-25T00:00:19Z'
objs = self.access.query(timestamp=dt_range)
self.assertEqual(len(objs), 10)
self.assertLess(objs[0].timestamp, objs[9].timestamp)
dt_range = '2014-12-25T00:00:19Z..2014-12-25T00:00:10Z'
objs = self.access.query(timestamp=dt_range)
self.assertEqual(len(objs), 10)
self.assertLess(objs[9].timestamp, objs[0].timestamp)
def test_pagination(self):
count = 100
page_size = 25
pages = count / page_size
users = ['Peter', 'Susan', 'Edmund', 'Lucy']
for user in users:
context = {'user': user}
for i in range(count):
self.access.add_or_update(FakeModelDB(name=uuid.uuid4().hex,
context=context, index=i))
self.assertEqual(self.access.count(), len(users) * count)
for user in users:
for i in range(pages):
offset = i * page_size
objs = self.access.query(context__user=user, order_by=['index'],
offset=offset, limit=page_size)
self.assertEqual(len(objs), page_size)
for j in range(page_size):
self.assertEqual(objs[j].context['user'], user)
self.assertEqual(objs[j].index, (i * page_size) + j)
def test_sort_multiple(self):
count = 60
base = date_utils.add_utc_tz(datetime.datetime(2014, 12, 25, 0, 0, 0))
for i in range(count):
category = 'type1' if i % 2 else 'type2'
timestamp = base + datetime.timedelta(seconds=i)
obj = FakeModelDB(name=uuid.uuid4().hex, timestamp=timestamp, category=category)
self.access.add_or_update(obj)
objs = self.access.query(order_by=['category', 'timestamp'])
self.assertEqual(len(objs), count)
for i in range(count):
category = 'type1' if i < count / 2 else 'type2'
self.assertEqual(objs[i].category, category)
self.assertLess(objs[0].timestamp, objs[(count / 2) - 1].timestamp)
self.assertLess(objs[count / 2].timestamp, objs[(count / 2) - 1].timestamp)
self.assertLess(objs[count / 2].timestamp, objs[count - 1].timestamp)
def test_escaped_field(self):
context = {'a.b.c': 'abc'}
obj1 = FakeModelDB(name=uuid.uuid4().hex, context=context)
obj2 = self.access.add_or_update(obj1)
# Check that the original dict has not been altered.
self.assertIn('a.b.c', context.keys())
self.assertNotIn('a\uff0eb\uff0ec', context.keys())
# Check to_python has run and context is not left escaped.
self.assertDictEqual(obj2.context, context)
# Check field is not escaped when retrieving from persistence.
obj3 = self.access.get(name=obj2.name)
self.assertIsNotNone(obj3)
self.assertEqual(obj3.id, obj2.id)
self.assertDictEqual(obj3.context, context)
| apache-2.0 |
averagehat/GuerillaDNS | src/makedomains.py | 1 | 2493 | from mymongo import MyMongo
from dnsclient import DNSClient
import random, time
import os, sys
import datetime
import re
dns_username = os.environ['FDNS_UN']
dns_password = os.environ['FDNS_PW']
print dns_username
print dns_password
mandrill_1 = os.environ['MANDRILL_1']
mandrill_2 = os.environ['MANDRILL_2']
dns = DNSClient(dns_username, dns_password)
connection = MyMongo()
dc= connection.domains
wordsfile = open('../data/words.txt')
random.seed(time.time())
chars = ['-','.']
def get_recent_domains():
reg = re.compile(r'[0-9]') # they tend to have too many numbers and look weird
start = datetime.datetime(2014, 8, 1, 1, 1, 1, 1)
return dc.find({'createTime' : {'$gte' : start}, 'domainName': {'$not' : reg}})
def getword():
line = words[random.randint(0, len(words) - 1)]
return line
def randomchar(): return chars[random.randint(0, len(chars) -1)]
def getwords(lines):
words = []
for line in lines:
char = randomchar()
line = line.replace(' ', char)
line = line.replace('/', '')
line = line.replace('"', '')
line = line.replace("'", '')
line = line.strip()
words.append(line)
return words
# if len(line) > 7: l.append(line)
def getdomain(): return cursor.next()
def coinflip(): return random.randint(1,2) %2
def getsubstring():
word1, word2 = getword(), getword()
if coinflip(): result = randomchar().join([word1, word2])
else: result = word1
if len(result) > 14: result = result[:15]
return result
def adddomains(total):
count = 0
while count < total:
record_type = 'MX'
d = getdomain()
domain_id, domain_str = d['webid'], d['domainName']
substring = getsubstring()
subdomain = '.'.join([substring, domain_str])
success = True
print 'attempting ', subdomain, ' . . . . '
for dest_str in [mandrill_1, mandrill_2]:
response, error = dns.addsubdomain(domain_id, substring, 'MX', dest_str)
if error:
success = False
break
if success: print subdomain, ' added'
count += 1
dc.update({'webid' : domain_id} , {'$set' : {'using' : success, 'subdomain' : subdomain}} )
if __name__ == '__main__':
r, error = dns.login()
if error: sys.exit(1)
cursor = get_recent_domains()
words = getwords(wordsfile.readlines())
adddomains(20)
| gpl-2.0 |
jinie/sublime-wakatime | packages/wakatime/packages/pygments_py2/pygments/formatters/other.py | 73 | 5162 | # -*- coding: utf-8 -*-
"""
pygments.formatters.other
~~~~~~~~~~~~~~~~~~~~~~~~~
Other formatters: NullFormatter, RawTokenFormatter.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.formatter import Formatter
from pygments.util import OptionError, get_choice_opt
from pygments.token import Token
from pygments.console import colorize
__all__ = ['NullFormatter', 'RawTokenFormatter', 'TestcaseFormatter']
class NullFormatter(Formatter):
"""
Output the text unchanged without any formatting.
"""
name = 'Text only'
aliases = ['text', 'null']
filenames = ['*.txt']
def format(self, tokensource, outfile):
enc = self.encoding
for ttype, value in tokensource:
if enc:
outfile.write(value.encode(enc))
else:
outfile.write(value)
class RawTokenFormatter(Formatter):
r"""
Format tokens as a raw representation for storing token streams.
The format is ``tokentype<TAB>repr(tokenstring)\n``. The output can later
be converted to a token stream with the `RawTokenLexer`, described in the
:doc:`lexer list <lexers>`.
Only two options are accepted:
`compress`
If set to ``'gz'`` or ``'bz2'``, compress the output with the given
compression algorithm after encoding (default: ``''``).
`error_color`
If set to a color name, highlight error tokens using that color. If
set but with no value, defaults to ``'red'``.
.. versionadded:: 0.11
"""
name = 'Raw tokens'
aliases = ['raw', 'tokens']
filenames = ['*.raw']
unicodeoutput = False
def __init__(self, **options):
Formatter.__init__(self, **options)
# We ignore self.encoding if it is set, since it gets set for lexer
# and formatter if given with -Oencoding on the command line.
# The RawTokenFormatter outputs only ASCII. Override here.
self.encoding = 'ascii' # let pygments.format() do the right thing
self.compress = get_choice_opt(options, 'compress',
['', 'none', 'gz', 'bz2'], '')
self.error_color = options.get('error_color', None)
if self.error_color is True:
self.error_color = 'red'
if self.error_color is not None:
try:
colorize(self.error_color, '')
except KeyError:
raise ValueError("Invalid color %r specified" %
self.error_color)
def format(self, tokensource, outfile):
try:
outfile.write(b'')
except TypeError:
raise TypeError('The raw tokens formatter needs a binary '
'output file')
if self.compress == 'gz':
import gzip
outfile = gzip.GzipFile('', 'wb', 9, outfile)
def write(text):
outfile.write(text.encode())
flush = outfile.flush
elif self.compress == 'bz2':
import bz2
compressor = bz2.BZ2Compressor(9)
def write(text):
outfile.write(compressor.compress(text.encode()))
def flush():
outfile.write(compressor.flush())
outfile.flush()
else:
def write(text):
outfile.write(text.encode())
flush = outfile.flush
if self.error_color:
for ttype, value in tokensource:
line = "%s\t%r\n" % (ttype, value)
if ttype is Token.Error:
write(colorize(self.error_color, line))
else:
write(line)
else:
for ttype, value in tokensource:
write("%s\t%r\n" % (ttype, value))
flush()
TESTCASE_BEFORE = u'''\
def testNeedsName(self):
fragment = %r
tokens = [
'''
TESTCASE_AFTER = u'''\
]
self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
'''
class TestcaseFormatter(Formatter):
"""
Format tokens as appropriate for a new testcase.
.. versionadded:: 2.0
"""
name = 'Testcase'
aliases = ['testcase']
def __init__(self, **options):
Formatter.__init__(self, **options)
if self.encoding is not None and self.encoding != 'utf-8':
raise ValueError("Only None and utf-8 are allowed encodings.")
def format(self, tokensource, outfile):
indentation = ' ' * 12
rawbuf = []
outbuf = []
for ttype, value in tokensource:
rawbuf.append(value)
outbuf.append('%s(%s, %r),\n' % (indentation, ttype, value))
before = TESTCASE_BEFORE % (u''.join(rawbuf),)
during = u''.join(outbuf)
after = TESTCASE_AFTER
if self.encoding is None:
outfile.write(before + during + after)
else:
outfile.write(before.encode('utf-8'))
outfile.write(during.encode('utf-8'))
outfile.write(after.encode('utf-8'))
outfile.flush()
| bsd-3-clause |
gcallah/Indra | models/segregation.py | 1 | 4209 | """
Schelling's segregation model.
"""
import random
from indra.agent import Agent
from indra.composite import Composite
from indra.display_methods import RED, BLUE
from indra.env import Env
from registry.registry import get_env, get_prop
from registry.registry import run_notice
from indra.utils import init_props
MODEL_NAME = "segregation"
DEBUG = True # Turns debugging code on or off
DEBUG2 = False # Turns deeper debugging code on or off
NUM_RED = 250
NUM_BLUE = 250
DEF_CITY_DIM = 40
TOLERANCE = "tolerance"
DEVIATION = "deviation"
COLOR = "color"
DEF_HOOD_SIZE = 1
DEF_TOLERANCE = .5
DEF_SIGMA = .2
MAX_TOL = 0.1
MIN_TOL = 0.9
BLUE_TEAM = 0
RED_TEAM = 1
HOOD_SIZE = 4
NOT_ZERO = .001
BLUE_AGENTS = "Blue agents"
RED_AGENTS = "Red agents"
group_names = [BLUE_AGENTS, RED_AGENTS]
hood_size = None
opp_group = None
def get_tolerance(default_tolerance, sigma):
tol = random.gauss(default_tolerance, sigma)
# a low tolerance number here means high tolerance!
tol = max(tol, MAX_TOL)
tol = min(tol, MIN_TOL)
return tol
def my_group_index(agent):
return int(agent[COLOR])
def other_group_index(agent):
return not my_group_index(agent)
def env_favorable(hood_ratio, my_tolerance):
"""
Is the environment to our agent's liking or not??
"""
return hood_ratio >= my_tolerance
def seg_agent_action(agent):
"""
If the agent is surrounded by more "others" than it
is comfortable with, the agent will move.
"""
stay_put = True
if agent["hood_changed"]:
agent_group = agent.primary_group()
ratio_same = 0
neighbors = get_env().get_moore_hood(agent,
hood_size=agent['hood_size'])
num_same = 0
for neighbor in neighbors:
if neighbors[neighbor].primary_group() == agent_group:
num_same += 1
if agent["just_moved"] is True:
neighbors[neighbor]["hood_changed"] = True
agent["just_moved"] = False
if len(neighbors) != 0:
ratio_same = num_same / len(neighbors)
stay_put = env_favorable(ratio_same, agent[TOLERANCE])
if stay_put:
agent["hood_changed"] = False
else:
agent["just_moved"] = True
for neighbor in neighbors:
neighbors[neighbor]["hood_changed"] = True
return stay_put
def create_resident(name, i):
"""
Creates agent of specified color type
"""
if "Blue" in name:
color = 0
mean_tol = get_prop('mean_tol', DEF_TOLERANCE)
else:
color = 1
mean_tol = -get_prop('mean_tol', DEF_TOLERANCE)
dev = get_prop('deviation', DEF_SIGMA)
this_tolerance = get_tolerance(mean_tol,
dev)
return Agent(name + str(i),
action=seg_agent_action,
attrs={TOLERANCE: this_tolerance,
COLOR: color, "hood_changed": True,
"just_moved": False,
"hood_size": get_prop('hood_size',
DEF_HOOD_SIZE)
}, )
def set_up(props=None):
"""
A func to set up run that can also be used by test code.
"""
init_props(MODEL_NAME, props)
blue_agents = Composite(group_names[BLUE_TEAM],
{"color": BLUE},
member_creator=create_resident,
num_members=get_prop('num_blue',
NUM_BLUE))
red_agents = Composite(group_names[RED_TEAM],
{"color": RED},
member_creator=create_resident,
num_members=get_prop('num_red', NUM_RED))
city = Env(MODEL_NAME, members=[blue_agents, red_agents],
height=get_prop('grid_height', DEF_CITY_DIM),
width=get_prop('grid_width', DEF_CITY_DIM))
city.exclude_menu_item("line_graph")
def main():
set_up()
run_notice(MODEL_NAME)
# get_env() returns a callable object:
get_env()()
return 0
if __name__ == "__main__":
main()
| gpl-3.0 |
mastizada/kuma | vendor/packages/ipython/IPython/Extensions/ipipe.py | 7 | 71681 | # -*- coding: iso-8859-1 -*-
"""
``ipipe`` provides classes to be used in an interactive Python session. Doing a
``from ipipe import *`` is the preferred way to do this. The name of all
objects imported this way starts with ``i`` to minimize collisions.
``ipipe`` supports "pipeline expressions", which is something resembling Unix
pipes. An example is::
>>> ienv | isort("key.lower()")
This gives a listing of all environment variables sorted by name.
There are three types of objects in a pipeline expression:
* ``Table``s: These objects produce items. Examples are ``ils`` (listing the
current directory, ``ienv`` (listing environment variables), ``ipwd`` (listing
user accounts) and ``igrp`` (listing user groups). A ``Table`` must be the
first object in a pipe expression.
* ``Pipe``s: These objects sit in the middle of a pipe expression. They
transform the input in some way (e.g. filtering or sorting it). Examples are:
``ifilter`` (which filters the input pipe), ``isort`` (which sorts the input
pipe) and ``ieval`` (which evaluates a function or expression for each object
in the input pipe).
* ``Display``s: These objects can be put as the last object in a pipeline
expression. There are responsible for displaying the result of the pipeline
expression. If a pipeline expression doesn't end in a display object a default
display objects will be used. One example is ``ibrowse`` which is a ``curses``
based browser.
Adding support for pipeline expressions to your own objects can be done through
three extensions points (all of them optional):
* An object that will be displayed as a row by a ``Display`` object should
implement the method ``__xattrs__(self, mode)`` method or register an
implementation of the generic function ``xattrs``. For more info see ``xattrs``.
* When an object ``foo`` is displayed by a ``Display`` object, the generic
function ``xrepr`` is used.
* Objects that can be iterated by ``Pipe``s must iterable. For special cases,
where iteration for display is different than the normal iteration a special
implementation can be registered with the generic function ``xiter``. This
makes it possible to use dictionaries and modules in pipeline expressions,
for example::
>>> import sys
>>> sys | ifilter("isinstance(value, int)") | idump
key |value
api_version| 1012
dllhandle | 503316480
hexversion | 33817328
maxint |2147483647
maxunicode | 65535
>>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
...
Note: The expression strings passed to ``ifilter()`` and ``isort()`` can
refer to the object to be filtered or sorted via the variable ``_`` and to any
of the attributes of the object, i.e.::
>>> sys.modules | ifilter("_.value is not None") | isort("_.key.lower()")
does the same as::
>>> sys.modules | ifilter("value is not None") | isort("key.lower()")
In addition to expression strings, it's possible to pass callables (taking
the object as an argument) to ``ifilter()``, ``isort()`` and ``ieval()``::
>>> sys | ifilter(lambda _:isinstance(_.value, int)) \
... | ieval(lambda _: (_.key, hex(_.value))) | idump
0 |1
api_version|0x3f4
dllhandle |0x1e000000
hexversion |0x20402f0
maxint |0x7fffffff
maxunicode |0xffff
"""
skip_doctest = True # ignore top-level docstring as a doctest.
import sys, os, os.path, stat, glob, new, csv, datetime, types
import itertools, mimetypes, StringIO
try: # Python 2.3 compatibility
import collections
except ImportError:
deque = list
else:
deque = collections.deque
try: # Python 2.3 compatibility
set
except NameError:
import sets
set = sets.Set
try: # Python 2.3 compatibility
sorted
except NameError:
def sorted(iterator, key=None, reverse=False):
items = list(iterator)
if key is not None:
items.sort(lambda i1, i2: cmp(key(i1), key(i2)))
else:
items.sort()
if reverse:
items.reverse()
return items
try: # Python 2.4 compatibility
GeneratorExit
except NameError:
GeneratorExit = SystemExit
try:
import pwd
except ImportError:
pwd = None
try:
import grp
except ImportError:
grp = None
from IPython.external import simplegeneric
from IPython.external import path
try:
from IPython import genutils, generics
except ImportError:
genutils = None
generics = None
from IPython import ipapi
__all__ = [
"ifile", "ils", "iglob", "iwalk", "ipwdentry", "ipwd", "igrpentry", "igrp",
"icsv", "ix", "ichain", "isort", "ifilter", "ieval", "ienum",
"ienv", "ihist", "ialias", "icap", "idump", "iless"
]
os.stat_float_times(True) # enable microseconds
class AttrNamespace(object):
"""
Helper class that is used for providing a namespace for evaluating
expressions containing attribute names of an object.
"""
def __init__(self, wrapped):
self.wrapped = wrapped
def __getitem__(self, name):
if name == "_":
return self.wrapped
try:
return getattr(self.wrapped, name)
except AttributeError:
raise KeyError(name)
# Python 2.3 compatibility
# use eval workaround to find out which names are used in the
# eval string and put them into the locals. This works for most
# normal uses case, bizarre ones like accessing the locals()
# will fail
try:
eval("_", None, AttrNamespace(None))
except TypeError:
real_eval = eval
def eval(codestring, _globals, _locals):
"""
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mappping.
This function is a workaround for the shortcomings of
Python 2.3's eval.
"""
if isinstance(codestring, basestring):
code = compile(codestring, "_eval", "eval")
else:
code = codestring
newlocals = {}
for name in code.co_names:
try:
newlocals[name] = _locals[name]
except KeyError:
pass
return real_eval(code, _globals, newlocals)
noitem = object()
def item(iterator, index, default=noitem):
"""
Return the ``index``th item from the iterator ``iterator``.
``index`` must be an integer (negative integers are relative to the
end (i.e. the last items produced by the iterator)).
If ``default`` is given, this will be the default value when
the iterator doesn't contain an item at this position. Otherwise an
``IndexError`` will be raised.
Note that using this function will partially or totally exhaust the
iterator.
"""
i = index
if i>=0:
for item in iterator:
if not i:
return item
i -= 1
else:
i = -index
cache = deque()
for item in iterator:
cache.append(item)
if len(cache)>i:
cache.popleft()
if len(cache)==i:
return cache.popleft()
if default is noitem:
raise IndexError(index)
else:
return default
def getglobals(g):
"""
Return the global namespace that is used for expression strings in
``ifilter`` and others. This is ``g`` or (if ``g`` is ``None``) IPython's
user namespace.
"""
if g is None:
if ipapi is not None:
api = ipapi.get()
if api is not None:
return api.user_ns
return globals()
return g
class Descriptor(object):
"""
A ``Descriptor`` object is used for describing the attributes of objects.
"""
def __hash__(self):
return hash(self.__class__) ^ hash(self.key())
def __eq__(self, other):
return self.__class__ is other.__class__ and self.key() == other.key()
def __ne__(self, other):
return self.__class__ is not other.__class__ or self.key() != other.key()
def key(self):
pass
def name(self):
"""
Return the name of this attribute for display by a ``Display`` object
(e.g. as a column title).
"""
key = self.key()
if key is None:
return "_"
return str(key)
def attrtype(self, obj):
"""
Return the type of this attribute (i.e. something like "attribute" or
"method").
"""
def valuetype(self, obj):
"""
Return the type of this attribute value of the object ``obj``.
"""
def value(self, obj):
"""
Return the value of this attribute of the object ``obj``.
"""
def doc(self, obj):
"""
Return the documentation for this attribute.
"""
def shortdoc(self, obj):
"""
Return a short documentation for this attribute (defaulting to the
first line).
"""
doc = self.doc(obj)
if doc is not None:
doc = doc.strip().splitlines()[0].strip()
return doc
def iter(self, obj):
"""
Return an iterator for this attribute of the object ``obj``.
"""
return xiter(self.value(obj))
class SelfDescriptor(Descriptor):
"""
A ``SelfDescriptor`` describes the object itself.
"""
def key(self):
return None
def attrtype(self, obj):
return "self"
def valuetype(self, obj):
return type(obj)
def value(self, obj):
return obj
def __repr__(self):
return "Self"
selfdescriptor = SelfDescriptor() # there's no need for more than one
class AttributeDescriptor(Descriptor):
"""
An ``AttributeDescriptor`` describes a simple attribute of an object.
"""
__slots__ = ("_name", "_doc")
def __init__(self, name, doc=None):
self._name = name
self._doc = doc
def key(self):
return self._name
def doc(self, obj):
return self._doc
def attrtype(self, obj):
return "attr"
def valuetype(self, obj):
return type(getattr(obj, self._name))
def value(self, obj):
return getattr(obj, self._name)
def __repr__(self):
if self._doc is None:
return "Attribute(%r)" % self._name
else:
return "Attribute(%r, %r)" % (self._name, self._doc)
class IndexDescriptor(Descriptor):
"""
An ``IndexDescriptor`` describes an "attribute" of an object that is fetched
via ``__getitem__``.
"""
__slots__ = ("_index",)
def __init__(self, index):
self._index = index
def key(self):
return self._index
def attrtype(self, obj):
return "item"
def valuetype(self, obj):
return type(obj[self._index])
def value(self, obj):
return obj[self._index]
def __repr__(self):
return "Index(%r)" % self._index
class MethodDescriptor(Descriptor):
"""
A ``MethodDescriptor`` describes a method of an object that can be called
without argument. Note that this method shouldn't change the object.
"""
__slots__ = ("_name", "_doc")
def __init__(self, name, doc=None):
self._name = name
self._doc = doc
def key(self):
return self._name
def doc(self, obj):
if self._doc is None:
return getattr(obj, self._name).__doc__
return self._doc
def attrtype(self, obj):
return "method"
def valuetype(self, obj):
return type(self.value(obj))
def value(self, obj):
return getattr(obj, self._name)()
def __repr__(self):
if self._doc is None:
return "Method(%r)" % self._name
else:
return "Method(%r, %r)" % (self._name, self._doc)
class IterAttributeDescriptor(Descriptor):
"""
An ``IterAttributeDescriptor`` works like an ``AttributeDescriptor`` but
doesn't return an attribute values (because this value might be e.g. a large
list).
"""
__slots__ = ("_name", "_doc")
def __init__(self, name, doc=None):
self._name = name
self._doc = doc
def key(self):
return self._name
def doc(self, obj):
return self._doc
def attrtype(self, obj):
return "iter"
def valuetype(self, obj):
return noitem
def value(self, obj):
return noitem
def iter(self, obj):
return xiter(getattr(obj, self._name))
def __repr__(self):
if self._doc is None:
return "IterAttribute(%r)" % self._name
else:
return "IterAttribute(%r, %r)" % (self._name, self._doc)
class IterMethodDescriptor(Descriptor):
"""
An ``IterMethodDescriptor`` works like an ``MethodDescriptor`` but doesn't
return an attribute values (because this value might be e.g. a large list).
"""
__slots__ = ("_name", "_doc")
def __init__(self, name, doc=None):
self._name = name
self._doc = doc
def key(self):
return self._name
def doc(self, obj):
if self._doc is None:
return getattr(obj, self._name).__doc__
return self._doc
def attrtype(self, obj):
return "itermethod"
def valuetype(self, obj):
return noitem
def value(self, obj):
return noitem
def iter(self, obj):
return xiter(getattr(obj, self._name)())
def __repr__(self):
if self._doc is None:
return "IterMethod(%r)" % self._name
else:
return "IterMethod(%r, %r)" % (self._name, self._doc)
class FunctionDescriptor(Descriptor):
"""
A ``FunctionDescriptor`` turns a function into a descriptor. The function
will be called with the object to get the type and value of the attribute.
"""
__slots__ = ("_function", "_name", "_doc")
def __init__(self, function, name=None, doc=None):
self._function = function
self._name = name
self._doc = doc
def key(self):
return self._function
def name(self):
if self._name is not None:
return self._name
return getattr(self._function, "__xname__", self._function.__name__)
def doc(self, obj):
if self._doc is None:
return self._function.__doc__
return self._doc
def attrtype(self, obj):
return "function"
def valuetype(self, obj):
return type(self._function(obj))
def value(self, obj):
return self._function(obj)
def __repr__(self):
if self._doc is None:
return "Function(%r)" % self._name
else:
return "Function(%r, %r)" % (self._name, self._doc)
class Table(object):
"""
A ``Table`` is an object that produces items (just like a normal Python
iterator/generator does) and can be used as the first object in a pipeline
expression. The displayhook will open the default browser for such an object
(instead of simply printing the ``repr()`` result).
"""
# We want to support ``foo`` and ``foo()`` in pipeline expression:
# So we implement the required operators (``|`` and ``+``) in the metaclass,
# instantiate the class and forward the operator to the instance
class __metaclass__(type):
def __iter__(self):
return iter(self())
def __or__(self, other):
return self() | other
def __add__(self, other):
return self() + other
def __radd__(self, other):
return other + self()
def __getitem__(self, index):
return self()[index]
def __getitem__(self, index):
return item(self, index)
def __contains__(self, item):
for haveitem in self:
if item == haveitem:
return True
return False
def __or__(self, other):
# autoinstantiate right hand side
if isinstance(other, type) and issubclass(other, (Table, Display)):
other = other()
# treat simple strings and functions as ``ieval`` instances
elif not isinstance(other, Display) and not isinstance(other, Table):
other = ieval(other)
# forward operations to the right hand side
return other.__ror__(self)
def __add__(self, other):
# autoinstantiate right hand side
if isinstance(other, type) and issubclass(other, Table):
other = other()
return ichain(self, other)
def __radd__(self, other):
# autoinstantiate left hand side
if isinstance(other, type) and issubclass(other, Table):
other = other()
return ichain(other, self)
class Pipe(Table):
"""
A ``Pipe`` is an object that can be used in a pipeline expression. It
processes the objects it gets from its input ``Table``/``Pipe``. Note that
a ``Pipe`` object can't be used as the first object in a pipeline
expression, as it doesn't produces items itself.
"""
class __metaclass__(Table.__metaclass__):
def __ror__(self, input):
return input | self()
def __ror__(self, input):
# autoinstantiate left hand side
if isinstance(input, type) and issubclass(input, Table):
input = input()
self.input = input
return self
def xrepr(item, mode="default"):
"""
Generic function that adds color output and different display modes to ``repr``.
The result of an ``xrepr`` call is iterable and consists of ``(style, string)``
tuples. The ``style`` in this tuple must be a ``Style`` object from the
``astring`` module. To reconfigure the output the first yielded tuple can be
a ``(aligment, full)`` tuple instead of a ``(style, string)`` tuple.
``alignment`` can be -1 for left aligned, 0 for centered and 1 for right
aligned (the default is left alignment). ``full`` is a boolean that specifies
whether the complete output must be displayed or the ``Display`` object is
allowed to stop output after enough text has been produced (e.g. a syntax
highlighted text line would use ``True``, but for a large data structure
(i.e. a nested list, tuple or dictionary) ``False`` would be used).
The default is full output.
There are four different possible values for ``mode`` depending on where
the ``Display`` object will display ``item``:
``"header"``
``item`` will be displayed in a header line (this is used by ``ibrowse``).
``"footer"``
``item`` will be displayed in a footer line (this is used by ``ibrowse``).
``"cell"``
``item`` will be displayed in a table cell/list.
``"default"``
default mode. If an ``xrepr`` implementation recursively outputs objects,
``"default"`` must be passed in the recursive calls to ``xrepr``.
If no implementation is registered for ``item``, ``xrepr`` will try the
``__xrepr__`` method on ``item``. If ``item`` doesn't have an ``__xrepr__``
method it falls back to ``repr``/``__repr__`` for all modes.
"""
try:
func = item.__xrepr__
except AttributeError:
yield (astyle.style_default, repr(item))
else:
try:
for x in func(mode):
yield x
except (KeyboardInterrupt, SystemExit, GeneratorExit):
raise
except Exception:
yield (astyle.style_default, repr(item))
xrepr = simplegeneric.generic(xrepr)
def xrepr_none(self, mode="default"):
yield (astyle.style_type_none, repr(self))
xrepr.when_object(None)(xrepr_none)
def xrepr_noitem(self, mode="default"):
yield (2, True)
yield (astyle.style_nodata, "<?>")
xrepr.when_object(noitem)(xrepr_noitem)
def xrepr_bool(self, mode="default"):
yield (astyle.style_type_bool, repr(self))
xrepr.when_type(bool)(xrepr_bool)
def xrepr_str(self, mode="default"):
if mode == "cell":
yield (astyle.style_default, repr(self.expandtabs(tab))[1:-1])
else:
yield (astyle.style_default, repr(self))
xrepr.when_type(str)(xrepr_str)
def xrepr_unicode(self, mode="default"):
if mode == "cell":
yield (astyle.style_default, repr(self.expandtabs(tab))[2:-1])
else:
yield (astyle.style_default, repr(self))
xrepr.when_type(unicode)(xrepr_unicode)
def xrepr_number(self, mode="default"):
yield (1, True)
yield (astyle.style_type_number, repr(self))
xrepr.when_type(int)(xrepr_number)
xrepr.when_type(long)(xrepr_number)
xrepr.when_type(float)(xrepr_number)
def xrepr_complex(self, mode="default"):
yield (astyle.style_type_number, repr(self))
xrepr.when_type(complex)(xrepr_number)
def xrepr_datetime(self, mode="default"):
if mode == "cell":
# Don't use strftime() here, as this requires year >= 1900
yield (astyle.style_type_datetime,
"%04d-%02d-%02d %02d:%02d:%02d.%06d" % \
(self.year, self.month, self.day,
self.hour, self.minute, self.second,
self.microsecond),
)
else:
yield (astyle.style_type_datetime, repr(self))
xrepr.when_type(datetime.datetime)(xrepr_datetime)
def xrepr_date(self, mode="default"):
if mode == "cell":
yield (astyle.style_type_datetime,
"%04d-%02d-%02d" % (self.year, self.month, self.day))
else:
yield (astyle.style_type_datetime, repr(self))
xrepr.when_type(datetime.date)(xrepr_date)
def xrepr_time(self, mode="default"):
if mode == "cell":
yield (astyle.style_type_datetime,
"%02d:%02d:%02d.%06d" % \
(self.hour, self.minute, self.second, self.microsecond))
else:
yield (astyle.style_type_datetime, repr(self))
xrepr.when_type(datetime.time)(xrepr_time)
def xrepr_timedelta(self, mode="default"):
yield (astyle.style_type_datetime, repr(self))
xrepr.when_type(datetime.timedelta)(xrepr_timedelta)
def xrepr_type(self, mode="default"):
if self.__module__ == "__builtin__":
yield (astyle.style_type_type, self.__name__)
else:
yield (astyle.style_type_type, "%s.%s" % (self.__module__, self.__name__))
xrepr.when_type(type)(xrepr_type)
def xrepr_exception(self, mode="default"):
if self.__class__.__module__ == "exceptions":
classname = self.__class__.__name__
else:
classname = "%s.%s" % \
(self.__class__.__module__, self.__class__.__name__)
if mode == "header" or mode == "footer":
yield (astyle.style_error, "%s: %s" % (classname, self))
else:
yield (astyle.style_error, classname)
xrepr.when_type(Exception)(xrepr_exception)
def xrepr_listtuple(self, mode="default"):
if mode == "header" or mode == "footer":
if self.__class__.__module__ == "__builtin__":
classname = self.__class__.__name__
else:
classname = "%s.%s" % \
(self.__class__.__module__,self.__class__.__name__)
yield (astyle.style_default,
"<%s object with %d items at 0x%x>" % \
(classname, len(self), id(self)))
else:
yield (-1, False)
if isinstance(self, list):
yield (astyle.style_default, "[")
end = "]"
else:
yield (astyle.style_default, "(")
end = ")"
for (i, subself) in enumerate(self):
if i:
yield (astyle.style_default, ", ")
for part in xrepr(subself, "default"):
yield part
yield (astyle.style_default, end)
xrepr.when_type(list)(xrepr_listtuple)
xrepr.when_type(tuple)(xrepr_listtuple)
def xrepr_dict(self, mode="default"):
if mode == "header" or mode == "footer":
if self.__class__.__module__ == "__builtin__":
classname = self.__class__.__name__
else:
classname = "%s.%s" % \
(self.__class__.__module__,self.__class__.__name__)
yield (astyle.style_default,
"<%s object with %d items at 0x%x>" % \
(classname, len(self), id(self)))
else:
yield (-1, False)
if isinstance(self, dict):
yield (astyle.style_default, "{")
end = "}"
else:
yield (astyle.style_default, "dictproxy((")
end = "})"
for (i, (key, value)) in enumerate(self.iteritems()):
if i:
yield (astyle.style_default, ", ")
for part in xrepr(key, "default"):
yield part
yield (astyle.style_default, ": ")
for part in xrepr(value, "default"):
yield part
yield (astyle.style_default, end)
xrepr.when_type(dict)(xrepr_dict)
xrepr.when_type(types.DictProxyType)(xrepr_dict)
def upgradexattr(attr):
"""
Convert an attribute descriptor string to a real descriptor object.
If attr already is a descriptor object return it unmodified. A
``SelfDescriptor`` will be returned if ``attr`` is ``None``. ``"foo"``
returns an ``AttributeDescriptor`` for the attribute named ``"foo"``.
``"foo()"`` returns a ``MethodDescriptor`` for the method named ``"foo"``.
``"-foo"`` will return an ``IterAttributeDescriptor`` for the attribute
named ``"foo"`` and ``"-foo()"`` will return an ``IterMethodDescriptor``
for the method named ``"foo"``. Furthermore integers will return the appropriate
``IndexDescriptor`` and callables will return a ``FunctionDescriptor``.
"""
if attr is None:
return selfdescriptor
elif isinstance(attr, Descriptor):
return attr
elif isinstance(attr, basestring):
if attr.endswith("()"):
if attr.startswith("-"):
return IterMethodDescriptor(attr[1:-2])
else:
return MethodDescriptor(attr[:-2])
else:
if attr.startswith("-"):
return IterAttributeDescriptor(attr[1:])
else:
return AttributeDescriptor(attr)
elif isinstance(attr, (int, long)):
return IndexDescriptor(attr)
elif callable(attr):
return FunctionDescriptor(attr)
else:
raise TypeError("can't handle descriptor %r" % attr)
def xattrs(item, mode="default"):
"""
Generic function that returns an iterable of attribute descriptors
to be used for displaying the attributes ob the object ``item`` in display
mode ``mode``.
There are two possible modes:
``"detail"``
The ``Display`` object wants to display a detailed list of the object
attributes.
``"default"``
The ``Display`` object wants to display the object in a list view.
If no implementation is registered for the object ``item`` ``xattrs`` falls
back to trying the ``__xattrs__`` method of the object. If this doesn't
exist either, ``dir(item)`` is used for ``"detail"`` mode and ``(None,)``
for ``"default"`` mode.
The implementation must yield attribute descriptors (see the class
``Descriptor`` for more info). The ``__xattrs__`` method may also return
attribute descriptor strings (and ``None``) which will be converted to real
descriptors by ``upgradexattr()``.
"""
try:
func = item.__xattrs__
except AttributeError:
if mode == "detail":
for attrname in dir(item):
yield AttributeDescriptor(attrname)
else:
yield selfdescriptor
else:
for attr in func(mode):
yield upgradexattr(attr)
xattrs = simplegeneric.generic(xattrs)
def xattrs_complex(self, mode="default"):
if mode == "detail":
return (AttributeDescriptor("real"), AttributeDescriptor("imag"))
return (selfdescriptor,)
xattrs.when_type(complex)(xattrs_complex)
def _isdict(item):
try:
itermeth = item.__class__.__iter__
except (AttributeError, TypeError):
return False
return itermeth is dict.__iter__ or itermeth is types.DictProxyType.__iter__
def _isstr(item):
if not isinstance(item, basestring):
return False
try:
itermeth = item.__class__.__iter__
except AttributeError:
return True
return False # ``__iter__`` has been redefined
def xiter(item):
"""
Generic function that implements iteration for pipeline expression. If no
implementation is registered for ``item`` ``xiter`` falls back to ``iter``.
"""
try:
func = item.__xiter__
except AttributeError:
if _isdict(item):
def items(item):
fields = ("key", "value")
for (key, value) in item.iteritems():
yield Fields(fields, key=key, value=value)
return items(item)
elif isinstance(item, new.module):
def items(item):
fields = ("key", "value")
for key in sorted(item.__dict__):
yield Fields(fields, key=key, value=getattr(item, key))
return items(item)
elif _isstr(item):
if not item:
raise ValueError("can't enter empty string")
lines = item.splitlines()
if len(lines) == 1:
def iterone(item):
yield item
return iterone(item)
else:
return iter(lines)
return iter(item)
else:
return iter(func()) # iter() just to be safe
xiter = simplegeneric.generic(xiter)
class ichain(Pipe):
"""
Chains multiple ``Table``s into one.
"""
def __init__(self, *iters):
self.iters = iters
def __iter__(self):
return itertools.chain(*self.iters)
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer":
for (i, item) in enumerate(self.iters):
if i:
yield (astyle.style_default, "+")
if isinstance(item, Pipe):
yield (astyle.style_default, "(")
for part in xrepr(item, mode):
yield part
if isinstance(item, Pipe):
yield (astyle.style_default, ")")
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
args = ", ".join([repr(it) for it in self.iters])
return "%s.%s(%s)" % \
(self.__class__.__module__, self.__class__.__name__, args)
class ifile(path.path):
"""
file (or directory) object.
"""
def getmode(self):
return self.stat().st_mode
mode = property(getmode, None, None, "Access mode")
def gettype(self):
data = [
(stat.S_ISREG, "file"),
(stat.S_ISDIR, "dir"),
(stat.S_ISCHR, "chardev"),
(stat.S_ISBLK, "blockdev"),
(stat.S_ISFIFO, "fifo"),
(stat.S_ISLNK, "symlink"),
(stat.S_ISSOCK,"socket"),
]
lstat = self.lstat()
if lstat is not None:
types = set([text for (func, text) in data if func(lstat.st_mode)])
else:
types = set()
m = self.mode
types.update([text for (func, text) in data if func(m)])
return ", ".join(types)
type = property(gettype, None, None, "file type (file, directory, link, etc.)")
def getmodestr(self):
m = self.mode
data = [
(stat.S_IRUSR, "-r"),
(stat.S_IWUSR, "-w"),
(stat.S_IXUSR, "-x"),
(stat.S_IRGRP, "-r"),
(stat.S_IWGRP, "-w"),
(stat.S_IXGRP, "-x"),
(stat.S_IROTH, "-r"),
(stat.S_IWOTH, "-w"),
(stat.S_IXOTH, "-x"),
]
return "".join([text[bool(m&bit)] for (bit, text) in data])
modestr = property(getmodestr, None, None, "Access mode as string")
def getblocks(self):
return self.stat().st_blocks
blocks = property(getblocks, None, None, "File size in blocks")
def getblksize(self):
return self.stat().st_blksize
blksize = property(getblksize, None, None, "Filesystem block size")
def getdev(self):
return self.stat().st_dev
dev = property(getdev)
def getnlink(self):
return self.stat().st_nlink
nlink = property(getnlink, None, None, "Number of links")
def getuid(self):
return self.stat().st_uid
uid = property(getuid, None, None, "User id of file owner")
def getgid(self):
return self.stat().st_gid
gid = property(getgid, None, None, "Group id of file owner")
def getowner(self):
stat = self.stat()
try:
return pwd.getpwuid(stat.st_uid).pw_name
except KeyError:
return stat.st_uid
owner = property(getowner, None, None, "Owner name (or id)")
def getgroup(self):
stat = self.stat()
try:
return grp.getgrgid(stat.st_gid).gr_name
except KeyError:
return stat.st_gid
group = property(getgroup, None, None, "Group name (or id)")
def getadate(self):
return datetime.datetime.utcfromtimestamp(self.atime)
adate = property(getadate, None, None, "Access date")
def getcdate(self):
return datetime.datetime.utcfromtimestamp(self.ctime)
cdate = property(getcdate, None, None, "Creation date")
def getmdate(self):
return datetime.datetime.utcfromtimestamp(self.mtime)
mdate = property(getmdate, None, None, "Modification date")
def mimetype(self):
"""
Return MIME type guessed from the extension.
"""
return mimetypes.guess_type(self.basename())[0]
def encoding(self):
"""
Return guessed compression (like "compress" or "gzip").
"""
return mimetypes.guess_type(self.basename())[1]
def __repr__(self):
return "ifile(%s)" % path._base.__repr__(self)
if sys.platform == "win32":
defaultattrs = (None, "type", "size", "modestr", "mdate")
else:
defaultattrs = (None, "type", "size", "modestr", "owner", "group", "mdate")
def __xattrs__(self, mode="default"):
if mode == "detail":
return (
"name",
"basename()",
"abspath()",
"realpath()",
"type",
"mode",
"modestr",
"stat()",
"lstat()",
"uid",
"gid",
"owner",
"group",
"dev",
"nlink",
"ctime",
"mtime",
"atime",
"cdate",
"mdate",
"adate",
"size",
"blocks",
"blksize",
"isdir()",
"islink()",
"mimetype()",
"encoding()",
"-listdir()",
"-dirs()",
"-files()",
"-walk()",
"-walkdirs()",
"-walkfiles()",
)
else:
return self.defaultattrs
def xiter_ifile(self):
if self.isdir():
yield (self / os.pardir).abspath()
for child in sorted(self.listdir()):
yield child
else:
f = self.open("rb")
for line in f:
yield line
f.close()
xiter.when_type(ifile)(xiter_ifile)
# We need to implement ``xrepr`` for ``ifile`` as a generic function, because
# otherwise ``xrepr_str`` would kick in.
def xrepr_ifile(self, mode="default"):
try:
if self.isdir():
name = "idir"
style = astyle.style_dir
else:
name = "ifile"
style = astyle.style_file
except IOError:
name = "ifile"
style = astyle.style_default
if mode in ("cell", "header", "footer"):
abspath = repr(path._base(self.normpath()))
if abspath.startswith("u"):
abspath = abspath[2:-1]
else:
abspath = abspath[1:-1]
if mode == "cell":
yield (style, abspath)
else:
yield (style, "%s(%s)" % (name, abspath))
else:
yield (style, repr(self))
xrepr.when_type(ifile)(xrepr_ifile)
class ils(Table):
"""
List the current (or a specified) directory.
Examples::
>>> ils
<class 'IPython.Extensions.ipipe.ils'>
>>> ils("/usr/local/lib/python2.4")
IPython.Extensions.ipipe.ils('/usr/local/lib/python2.4')
>>> ils("~")
IPython.Extensions.ipipe.ils('/home/fperez')
# all-random
"""
def __init__(self, base=os.curdir, dirs=True, files=True):
self.base = os.path.expanduser(base)
self.dirs = dirs
self.files = files
def __iter__(self):
base = ifile(self.base)
yield (base / os.pardir).abspath()
for child in sorted(base.listdir()):
if self.dirs:
if self.files:
yield child
else:
if child.isdir():
yield child
elif self.files:
if not child.isdir():
yield child
def __xrepr__(self, mode="default"):
return xrepr(ifile(self.base), mode)
def __repr__(self):
return "%s.%s(%r)" % \
(self.__class__.__module__, self.__class__.__name__, self.base)
class iglob(Table):
"""
List all files and directories matching a specified pattern.
(See ``glob.glob()`` for more info.).
Examples::
>>> iglob("*.py")
IPython.Extensions.ipipe.iglob('*.py')
"""
def __init__(self, glob):
self.glob = glob
def __iter__(self):
for name in glob.glob(self.glob):
yield ifile(name)
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer" or mode == "cell":
yield (astyle.style_default,
"%s(%r)" % (self.__class__.__name__, self.glob))
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
return "%s.%s(%r)" % \
(self.__class__.__module__, self.__class__.__name__, self.glob)
class iwalk(Table):
"""
List all files and directories in a directory and it's subdirectory::
>>> iwalk
<class 'IPython.Extensions.ipipe.iwalk'>
>>> iwalk("/usr/lib")
IPython.Extensions.ipipe.iwalk('/usr/lib')
>>> iwalk("~")
IPython.Extensions.ipipe.iwalk('/home/fperez') # random
"""
def __init__(self, base=os.curdir, dirs=True, files=True):
self.base = os.path.expanduser(base)
self.dirs = dirs
self.files = files
def __iter__(self):
for (dirpath, dirnames, filenames) in os.walk(self.base):
if self.dirs:
for name in sorted(dirnames):
yield ifile(os.path.join(dirpath, name))
if self.files:
for name in sorted(filenames):
yield ifile(os.path.join(dirpath, name))
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer" or mode == "cell":
yield (astyle.style_default,
"%s(%r)" % (self.__class__.__name__, self.base))
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
return "%s.%s(%r)" % \
(self.__class__.__module__, self.__class__.__name__, self.base)
class ipwdentry(object):
"""
``ipwdentry`` objects encapsulate entries in the Unix user account and
password database.
"""
def __init__(self, id):
self._id = id
self._entry = None
def __eq__(self, other):
return self.__class__ is other.__class__ and self._id == other._id
def __ne__(self, other):
return self.__class__ is not other.__class__ or self._id != other._id
def _getentry(self):
if self._entry is None:
if isinstance(self._id, basestring):
self._entry = pwd.getpwnam(self._id)
else:
self._entry = pwd.getpwuid(self._id)
return self._entry
def getname(self):
if isinstance(self._id, basestring):
return self._id
else:
return self._getentry().pw_name
name = property(getname, None, None, "User name")
def getpasswd(self):
return self._getentry().pw_passwd
passwd = property(getpasswd, None, None, "Password")
def getuid(self):
if isinstance(self._id, basestring):
return self._getentry().pw_uid
else:
return self._id
uid = property(getuid, None, None, "User id")
def getgid(self):
return self._getentry().pw_gid
gid = property(getgid, None, None, "Primary group id")
def getgroup(self):
return igrpentry(self.gid)
group = property(getgroup, None, None, "Group")
def getgecos(self):
return self._getentry().pw_gecos
gecos = property(getgecos, None, None, "Information (e.g. full user name)")
def getdir(self):
return self._getentry().pw_dir
dir = property(getdir, None, None, "$HOME directory")
def getshell(self):
return self._getentry().pw_shell
shell = property(getshell, None, None, "Login shell")
def __xattrs__(self, mode="default"):
return ("name", "passwd", "uid", "gid", "gecos", "dir", "shell")
def __repr__(self):
return "%s.%s(%r)" % \
(self.__class__.__module__, self.__class__.__name__, self._id)
class ipwd(Table):
"""
List all entries in the Unix user account and password database.
Example::
>>> ipwd | isort("uid")
<IPython.Extensions.ipipe.isort key='uid' reverse=False at 0x849efec>
# random
"""
def __iter__(self):
for entry in pwd.getpwall():
yield ipwdentry(entry.pw_name)
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer" or mode == "cell":
yield (astyle.style_default, "%s()" % self.__class__.__name__)
else:
yield (astyle.style_default, repr(self))
class igrpentry(object):
"""
``igrpentry`` objects encapsulate entries in the Unix group database.
"""
def __init__(self, id):
self._id = id
self._entry = None
def __eq__(self, other):
return self.__class__ is other.__class__ and self._id == other._id
def __ne__(self, other):
return self.__class__ is not other.__class__ or self._id != other._id
def _getentry(self):
if self._entry is None:
if isinstance(self._id, basestring):
self._entry = grp.getgrnam(self._id)
else:
self._entry = grp.getgrgid(self._id)
return self._entry
def getname(self):
if isinstance(self._id, basestring):
return self._id
else:
return self._getentry().gr_name
name = property(getname, None, None, "Group name")
def getpasswd(self):
return self._getentry().gr_passwd
passwd = property(getpasswd, None, None, "Password")
def getgid(self):
if isinstance(self._id, basestring):
return self._getentry().gr_gid
else:
return self._id
gid = property(getgid, None, None, "Group id")
def getmem(self):
return self._getentry().gr_mem
mem = property(getmem, None, None, "Members")
def __xattrs__(self, mode="default"):
return ("name", "passwd", "gid", "mem")
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer" or mode == "cell":
yield (astyle.style_default, "group ")
try:
yield (astyle.style_default, self.name)
except KeyError:
if isinstance(self._id, basestring):
yield (astyle.style_default, self.name_id)
else:
yield (astyle.style_type_number, str(self._id))
else:
yield (astyle.style_default, repr(self))
def __iter__(self):
for member in self.mem:
yield ipwdentry(member)
def __repr__(self):
return "%s.%s(%r)" % \
(self.__class__.__module__, self.__class__.__name__, self._id)
class igrp(Table):
"""
This ``Table`` lists all entries in the Unix group database.
"""
def __iter__(self):
for entry in grp.getgrall():
yield igrpentry(entry.gr_name)
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer":
yield (astyle.style_default, "%s()" % self.__class__.__name__)
else:
yield (astyle.style_default, repr(self))
class Fields(object):
def __init__(self, fieldnames, **fields):
self.__fieldnames = [upgradexattr(fieldname) for fieldname in fieldnames]
for (key, value) in fields.iteritems():
setattr(self, key, value)
def __xattrs__(self, mode="default"):
return self.__fieldnames
def __xrepr__(self, mode="default"):
yield (-1, False)
if mode == "header" or mode == "cell":
yield (astyle.style_default, self.__class__.__name__)
yield (astyle.style_default, "(")
for (i, f) in enumerate(self.__fieldnames):
if i:
yield (astyle.style_default, ", ")
yield (astyle.style_default, f.name())
yield (astyle.style_default, "=")
for part in xrepr(getattr(self, f), "default"):
yield part
yield (astyle.style_default, ")")
elif mode == "footer":
yield (astyle.style_default, self.__class__.__name__)
yield (astyle.style_default, "(")
for (i, f) in enumerate(self.__fieldnames):
if i:
yield (astyle.style_default, ", ")
yield (astyle.style_default, f.name())
yield (astyle.style_default, ")")
else:
yield (astyle.style_default, repr(self))
class FieldTable(Table, list):
def __init__(self, *fields):
Table.__init__(self)
list.__init__(self)
self.fields = fields
def add(self, **fields):
self.append(Fields(self.fields, **fields))
def __xrepr__(self, mode="default"):
yield (-1, False)
if mode == "header" or mode == "footer":
yield (astyle.style_default, self.__class__.__name__)
yield (astyle.style_default, "(")
for (i, f) in enumerate(self.__fieldnames):
if i:
yield (astyle.style_default, ", ")
yield (astyle.style_default, f)
yield (astyle.style_default, ")")
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
return "<%s.%s object with fields=%r at 0x%x>" % \
(self.__class__.__module__, self.__class__.__name__,
", ".join(map(repr, self.fields)), id(self))
class List(list):
def __xattrs__(self, mode="default"):
return xrange(len(self))
def __xrepr__(self, mode="default"):
yield (-1, False)
if mode == "header" or mode == "cell" or mode == "footer" or mode == "default":
yield (astyle.style_default, self.__class__.__name__)
yield (astyle.style_default, "(")
for (i, item) in enumerate(self):
if i:
yield (astyle.style_default, ", ")
for part in xrepr(item, "default"):
yield part
yield (astyle.style_default, ")")
else:
yield (astyle.style_default, repr(self))
class ienv(Table):
"""
List environment variables.
Example::
>>> ienv
<class 'IPython.Extensions.ipipe.ienv'>
"""
def __iter__(self):
fields = ("key", "value")
for (key, value) in os.environ.iteritems():
yield Fields(fields, key=key, value=value)
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "cell":
yield (astyle.style_default, "%s()" % self.__class__.__name__)
else:
yield (astyle.style_default, repr(self))
class ihist(Table):
"""
IPython input history
Example::
>>> ihist
<class 'IPython.Extensions.ipipe.ihist'>
>>> ihist(True) # raw mode
<IPython.Extensions.ipipe.ihist object at 0x849602c> # random
"""
def __init__(self, raw=True):
self.raw = raw
def __iter__(self):
api = ipapi.get()
if self.raw:
for line in api.IP.input_hist_raw:
yield line.rstrip("\n")
else:
for line in api.IP.input_hist:
yield line.rstrip("\n")
class Alias(object):
"""
Entry in the alias table
"""
def __init__(self, name, args, command):
self.name = name
self.args = args
self.command = command
def __xattrs__(self, mode="default"):
return ("name", "args", "command")
class ialias(Table):
"""
IPython alias list
Example::
>>> ialias
<class 'IPython.Extensions.ipipe.ialias'>
"""
def __iter__(self):
api = ipapi.get()
for (name, (args, command)) in api.IP.alias_table.iteritems():
yield Alias(name, args, command)
class icsv(Pipe):
"""
This ``Pipe`` turns the input (with must be a pipe outputting lines
or an ``ifile``) into lines of CVS columns.
"""
def __init__(self, **csvargs):
"""
Create an ``icsv`` object. ``cvsargs`` will be passed through as
keyword arguments to ``cvs.reader()``.
"""
self.csvargs = csvargs
def __iter__(self):
input = self.input
if isinstance(input, ifile):
input = input.open("rb")
reader = csv.reader(input, **self.csvargs)
for line in reader:
yield List(line)
def __xrepr__(self, mode="default"):
yield (-1, False)
if mode == "header" or mode == "footer":
input = getattr(self, "input", None)
if input is not None:
for part in xrepr(input, mode):
yield part
yield (astyle.style_default, " | ")
yield (astyle.style_default, "%s(" % self.__class__.__name__)
for (i, (name, value)) in enumerate(self.csvargs.iteritems()):
if i:
yield (astyle.style_default, ", ")
yield (astyle.style_default, name)
yield (astyle.style_default, "=")
for part in xrepr(value, "default"):
yield part
yield (astyle.style_default, ")")
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
args = ", ".join(["%s=%r" % item for item in self.csvargs.iteritems()])
return "<%s.%s %s at 0x%x>" % \
(self.__class__.__module__, self.__class__.__name__, args, id(self))
class ix(Table):
"""
Execute a system command and list its output as lines
(similar to ``os.popen()``).
Examples::
>>> ix("ps x")
IPython.Extensions.ipipe.ix('ps x')
>>> ix("find .") | ifile
<IPython.Extensions.ipipe.ieval expr=<class 'IPython.Extensions.ipipe.ifile'> at 0x8509d2c>
# random
"""
def __init__(self, cmd):
self.cmd = cmd
self._pipeout = None
def __iter__(self):
(_pipein, self._pipeout) = os.popen4(self.cmd)
_pipein.close()
for l in self._pipeout:
yield l.rstrip("\r\n")
self._pipeout.close()
self._pipeout = None
def __del__(self):
if self._pipeout is not None and not self._pipeout.closed:
self._pipeout.close()
self._pipeout = None
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer":
yield (astyle.style_default,
"%s(%r)" % (self.__class__.__name__, self.cmd))
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
return "%s.%s(%r)" % \
(self.__class__.__module__, self.__class__.__name__, self.cmd)
class ifilter(Pipe):
"""
Filter an input pipe. Only objects where an expression evaluates to true
(and doesn't raise an exception) are listed.
Examples::
>>> ils | ifilter("_.isfile() and size>1000")
>>> igrp | ifilter("len(mem)")
>>> sys.modules | ifilter(lambda _:_.value is not None)
# all-random
"""
def __init__(self, expr, globals=None, errors="raiseifallfail"):
"""
Create an ``ifilter`` object. ``expr`` can be a callable or a string
containing an expression. ``globals`` will be used as the global
namespace for calling string expressions (defaulting to IPython's
user namespace). ``errors`` specifies how exception during evaluation
of ``expr`` are handled:
``"drop"``
drop all items that have errors;
``"keep"``
keep all items that have errors;
``"keeperror"``
keep the exception of all items that have errors;
``"raise"``
raise the exception;
``"raiseifallfail"``
raise the first exception if all items have errors; otherwise drop
those with errors (this is the default).
"""
self.expr = expr
self.globals = globals
self.errors = errors
def __iter__(self):
if callable(self.expr):
test = self.expr
else:
g = getglobals(self.globals)
expr = compile(self.expr, "ipipe-expression", "eval")
def test(item):
return eval(expr, g, AttrNamespace(item))
ok = 0
exc_info = None
for item in xiter(self.input):
try:
if test(item):
yield item
ok += 1
except (KeyboardInterrupt, SystemExit):
raise
except Exception, exc:
if self.errors == "drop":
pass # Ignore errors
elif self.errors == "keep":
yield item
elif self.errors == "keeperror":
yield exc
elif self.errors == "raise":
raise
elif self.errors == "raiseifallfail":
if exc_info is None:
exc_info = sys.exc_info()
if not ok and exc_info is not None:
raise exc_info[0], exc_info[1], exc_info[2]
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer":
input = getattr(self, "input", None)
if input is not None:
for part in xrepr(input, mode):
yield part
yield (astyle.style_default, " | ")
yield (astyle.style_default, "%s(" % self.__class__.__name__)
for part in xrepr(self.expr, "default"):
yield part
yield (astyle.style_default, ")")
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
return "<%s.%s expr=%r at 0x%x>" % \
(self.__class__.__module__, self.__class__.__name__,
self.expr, id(self))
class ieval(Pipe):
"""
Evaluate an expression for each object in the input pipe.
Examples::
>>> ils | ieval("_.abspath()")
# random
>>> sys.path | ieval(ifile)
# random
"""
def __init__(self, expr, globals=None, errors="raiseifallfail"):
"""
Create an ``ieval`` object. ``expr`` can be a callable or a string
containing an expression. For the meaning of ``globals`` and
``errors`` see ``ifilter``.
"""
self.expr = expr
self.globals = globals
self.errors = errors
def __iter__(self):
if callable(self.expr):
do = self.expr
else:
g = getglobals(self.globals)
expr = compile(self.expr, "ipipe-expression", "eval")
def do(item):
return eval(expr, g, AttrNamespace(item))
ok = 0
exc_info = None
for item in xiter(self.input):
try:
yield do(item)
except (KeyboardInterrupt, SystemExit):
raise
except Exception, exc:
if self.errors == "drop":
pass # Ignore errors
elif self.errors == "keep":
yield item
elif self.errors == "keeperror":
yield exc
elif self.errors == "raise":
raise
elif self.errors == "raiseifallfail":
if exc_info is None:
exc_info = sys.exc_info()
if not ok and exc_info is not None:
raise exc_info[0], exc_info[1], exc_info[2]
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer":
input = getattr(self, "input", None)
if input is not None:
for part in xrepr(input, mode):
yield part
yield (astyle.style_default, " | ")
yield (astyle.style_default, "%s(" % self.__class__.__name__)
for part in xrepr(self.expr, "default"):
yield part
yield (astyle.style_default, ")")
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
return "<%s.%s expr=%r at 0x%x>" % \
(self.__class__.__module__, self.__class__.__name__,
self.expr, id(self))
class ienum(Pipe):
"""
Enumerate the input pipe (i.e. wrap each input object in an object
with ``index`` and ``object`` attributes).
Examples::
>>> xrange(20) | ieval("_,_*_") | ienum | ifilter("index % 2 == 0") | ieval("object")
"""
skip_doctest = True
def __iter__(self):
fields = ("index", "object")
for (index, object) in enumerate(xiter(self.input)):
yield Fields(fields, index=index, object=object)
class isort(Pipe):
"""
Sorts the input pipe.
Examples::
>>> ils | isort("size")
<IPython.Extensions.ipipe.isort key='size' reverse=False at 0x849ec2c>
>>> ils | isort("_.isdir(), _.lower()", reverse=True)
<IPython.Extensions.ipipe.isort key='_.isdir(), _.lower()' reverse=True at 0x849eacc>
# all-random
"""
def __init__(self, key=None, globals=None, reverse=False):
"""
Create an ``isort`` object. ``key`` can be a callable or a string
containing an expression (or ``None`` in which case the items
themselves will be sorted). If ``reverse`` is true the sort order
will be reversed. For the meaning of ``globals`` see ``ifilter``.
"""
self.key = key
self.globals = globals
self.reverse = reverse
def __iter__(self):
if self.key is None:
items = sorted(xiter(self.input), reverse=self.reverse)
elif callable(self.key):
items = sorted(xiter(self.input), key=self.key, reverse=self.reverse)
else:
g = getglobals(self.globals)
key = compile(self.key, "ipipe-expression", "eval")
def realkey(item):
return eval(key, g, AttrNamespace(item))
items = sorted(xiter(self.input), key=realkey, reverse=self.reverse)
for item in items:
yield item
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer":
input = getattr(self, "input", None)
if input is not None:
for part in xrepr(input, mode):
yield part
yield (astyle.style_default, " | ")
yield (astyle.style_default, "%s(" % self.__class__.__name__)
for part in xrepr(self.key, "default"):
yield part
if self.reverse:
yield (astyle.style_default, ", ")
for part in xrepr(True, "default"):
yield part
yield (astyle.style_default, ")")
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
return "<%s.%s key=%r reverse=%r at 0x%x>" % \
(self.__class__.__module__, self.__class__.__name__,
self.key, self.reverse, id(self))
tab = 3 # for expandtabs()
def _format(field):
if isinstance(field, str):
text = repr(field.expandtabs(tab))[1:-1]
elif isinstance(field, unicode):
text = repr(field.expandtabs(tab))[2:-1]
elif isinstance(field, datetime.datetime):
# Don't use strftime() here, as this requires year >= 1900
text = "%04d-%02d-%02d %02d:%02d:%02d.%06d" % \
(field.year, field.month, field.day,
field.hour, field.minute, field.second, field.microsecond)
elif isinstance(field, datetime.date):
text = "%04d-%02d-%02d" % (field.year, field.month, field.day)
else:
text = repr(field)
return text
class Display(object):
class __metaclass__(type):
def __ror__(self, input):
return input | self()
def __init__(self, input=None):
self.input = input
def __ror__(self, input):
self.input = input
return self
def display(self):
pass
class iless(Display):
cmd = "less --quit-if-one-screen --LONG-PROMPT --LINE-NUMBERS --chop-long-lines --shift=8 --RAW-CONTROL-CHARS"
def display(self):
try:
pager = os.popen(self.cmd, "w")
try:
for item in xiter(self.input):
first = False
for attr in xattrs(item, "default"):
if first:
first = False
else:
pager.write(" ")
attr = upgradexattr(attr)
if not isinstance(attr, SelfDescriptor):
pager.write(attr.name())
pager.write("=")
pager.write(str(attr.value(item)))
pager.write("\n")
finally:
pager.close()
except Exception, exc:
print "%s: %s" % (exc.__class__.__name__, str(exc))
class _RedirectIO(object):
def __init__(self,*args,**kwargs):
"""
Map the system output streams to self.
"""
self.stream = StringIO.StringIO()
self.stdout = sys.stdout
sys.stdout = self
self.stderr = sys.stderr
sys.stderr = self
def write(self, text):
"""
Write both to screen and to self.
"""
self.stream.write(text)
self.stdout.write(text)
if "\n" in text:
self.stdout.flush()
def writelines(self, lines):
"""
Write lines both to screen and to self.
"""
self.stream.writelines(lines)
self.stdout.writelines(lines)
self.stdout.flush()
def restore(self):
"""
Restore the default system streams.
"""
self.stdout.flush()
self.stderr.flush()
sys.stdout = self.stdout
sys.stderr = self.stderr
class icap(Table):
"""
Execute a python string and capture any output to stderr/stdout.
Examples::
>>> import time
>>> icap("for i in range(10): print i, time.sleep(0.1)")
"""
skip_doctest = True
def __init__(self, expr, globals=None):
self.expr = expr
self.globals = globals
log = _RedirectIO()
try:
exec(expr, getglobals(globals))
finally:
log.restore()
self.stream = log.stream
def __iter__(self):
self.stream.seek(0)
for line in self.stream:
yield line.rstrip("\r\n")
def __xrepr__(self, mode="default"):
if mode == "header" or mode == "footer":
yield (astyle.style_default,
"%s(%r)" % (self.__class__.__name__, self.expr))
else:
yield (astyle.style_default, repr(self))
def __repr__(self):
return "%s.%s(%r)" % \
(self.__class__.__module__, self.__class__.__name__, self.expr)
def xformat(value, mode, maxlength):
align = None
full = True
width = 0
text = astyle.Text()
for (style, part) in xrepr(value, mode):
# only consider the first result
if align is None:
if isinstance(style, int):
# (style, text) really is (alignment, stop)
align = style
full = part
continue
else:
align = -1
full = True
if not isinstance(style, int):
text.append((style, part))
width += len(part)
if width >= maxlength and not full:
text.append((astyle.style_ellisis, "..."))
width += 3
break
if align is None: # default to left alignment
align = -1
return (align, width, text)
import astyle
class idump(Display):
# The approximate maximum length of a column entry
maxattrlength = 200
# Style for column names
style_header = astyle.Style.fromstr("white:black:bold")
def __init__(self, input=None, *attrs):
Display.__init__(self, input)
self.attrs = [upgradexattr(attr) for attr in attrs]
self.headerpadchar = " "
self.headersepchar = "|"
self.datapadchar = " "
self.datasepchar = "|"
def display(self):
stream = genutils.Term.cout
allattrs = []
attrset = set()
colwidths = {}
rows = []
for item in xiter(self.input):
row = {}
attrs = self.attrs
if not attrs:
attrs = xattrs(item, "default")
for attr in attrs:
if attr not in attrset:
allattrs.append(attr)
attrset.add(attr)
colwidths[attr] = len(attr.name())
try:
value = attr.value(item)
except (KeyboardInterrupt, SystemExit):
raise
except Exception, exc:
value = exc
(align, width, text) = xformat(value, "cell", self.maxattrlength)
colwidths[attr] = max(colwidths[attr], width)
# remember alignment, length and colored parts
row[attr] = (align, width, text)
rows.append(row)
stream.write("\n")
for (i, attr) in enumerate(allattrs):
attrname = attr.name()
self.style_header(attrname).write(stream)
spc = colwidths[attr] - len(attrname)
if i < len(colwidths)-1:
stream.write(self.headerpadchar*spc)
stream.write(self.headersepchar)
stream.write("\n")
for row in rows:
for (i, attr) in enumerate(allattrs):
(align, width, text) = row[attr]
spc = colwidths[attr] - width
if align == -1:
text.write(stream)
if i < len(colwidths)-1:
stream.write(self.datapadchar*spc)
elif align == 0:
spc = colwidths[attr] - width
spc1 = spc//2
spc2 = spc-spc1
stream.write(self.datapadchar*spc1)
text.write(stream)
if i < len(colwidths)-1:
stream.write(self.datapadchar*spc2)
else:
stream.write(self.datapadchar*spc)
text.write(stream)
if i < len(colwidths)-1:
stream.write(self.datasepchar)
stream.write("\n")
class AttributeDetail(Table):
"""
``AttributeDetail`` objects are use for displaying a detailed list of object
attributes.
"""
def __init__(self, object, descriptor):
self.object = object
self.descriptor = descriptor
def __iter__(self):
return self.descriptor.iter(self.object)
def name(self):
return self.descriptor.name()
def attrtype(self):
return self.descriptor.attrtype(self.object)
def valuetype(self):
return self.descriptor.valuetype(self.object)
def doc(self):
return self.descriptor.doc(self.object)
def shortdoc(self):
return self.descriptor.shortdoc(self.object)
def value(self):
return self.descriptor.value(self.object)
def __xattrs__(self, mode="default"):
attrs = ("name()", "attrtype()", "valuetype()", "value()", "shortdoc()")
if mode == "detail":
attrs += ("doc()",)
return attrs
def __xrepr__(self, mode="default"):
yield (-1, True)
valuetype = self.valuetype()
if valuetype is not noitem:
for part in xrepr(valuetype):
yield part
yield (astyle.style_default, " ")
yield (astyle.style_default, self.attrtype())
yield (astyle.style_default, " ")
yield (astyle.style_default, self.name())
yield (astyle.style_default, " of ")
for part in xrepr(self.object):
yield part
try:
from ibrowse import ibrowse
except ImportError:
# No curses (probably Windows) => try igrid
try:
from igrid import igrid
except ImportError:
# no wx either => use ``idump`` as the default display.
defaultdisplay = idump
else:
defaultdisplay = igrid
__all__.append("igrid")
else:
defaultdisplay = ibrowse
__all__.append("ibrowse")
# If we're running under IPython, register our objects with IPython's
# generic function ``result_display``, else install a displayhook
# directly as sys.displayhook
if generics is not None:
def display_display(obj):
return obj.display()
generics.result_display.when_type(Display)(display_display)
def display_tableobject(obj):
return display_display(defaultdisplay(obj))
generics.result_display.when_type(Table)(display_tableobject)
def display_tableclass(obj):
return display_tableobject(obj())
generics.result_display.when_type(Table.__metaclass__)(display_tableclass)
else:
def installdisplayhook():
_originalhook = sys.displayhook
def displayhook(obj):
if isinstance(obj, type) and issubclass(obj, Table):
obj = obj()
if isinstance(obj, Table):
obj = defaultdisplay(obj)
if isinstance(obj, Display):
return obj.display()
else:
_originalhook(obj)
sys.displayhook = displayhook
installdisplayhook()
| mpl-2.0 |
ioannistsanaktsidis/invenio | modules/websearch/lib/websearch_webcoll.py | 5 | 56561 | ## This file is part of Invenio.
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 CERN.
##
## Invenio 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.
##
## Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Create Invenio collection cache."""
__revision__ = "$Id$"
import calendar
import copy
import sys
import cgi
import re
import os
import string
import time
import cPickle
from invenio.config import \
CFG_CERN_SITE, \
CFG_WEBSEARCH_INSTANT_BROWSE, \
CFG_WEBSEARCH_NARROW_SEARCH_SHOW_GRANDSONS, \
CFG_WEBSEARCH_I18N_LATEST_ADDITIONS, \
CFG_CACHEDIR, \
CFG_SITE_LANG, \
CFG_SITE_NAME, \
CFG_SITE_LANGS, \
CFG_WEBSEARCH_ENABLED_SEARCH_INTERFACES, \
CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE, \
CFG_WEBSEARCH_DEF_RECORDS_IN_GROUPS, \
CFG_SCOAP3_SITE
from invenio.messages import gettext_set_language, language_list_long
from invenio.search_engine import search_pattern_parenthesised, get_creation_date, get_field_i18nname, collection_restricted_p, sort_records, EM_REPOSITORY
from invenio.dbquery import run_sql, Error, get_table_update_time
from invenio.bibrank_record_sorter import get_bibrank_methods
from invenio.dateutils import convert_datestruct_to_dategui, strftime
from invenio.bibformat import format_record
from invenio.shellutils import mymkdir
from invenio.intbitset import intbitset
from invenio.websearch_external_collections import \
external_collection_load_states, \
dico_collection_external_searches, \
external_collection_sort_engine_by_name
from invenio.bibtask import task_init, task_get_option, task_set_option, \
write_message, task_has_option, task_update_progress, \
task_sleep_now_if_required, task_set_task_param
import invenio.template
websearch_templates = invenio.template.load('websearch')
from invenio.websearch_external_collections_searcher import external_collections_dictionary
from invenio.websearch_external_collections_config import CFG_EXTERNAL_COLLECTION_TIMEOUT
from invenio.websearch_external_collections_config import CFG_HOSTED_COLLECTION_TIMEOUT_NBRECS
## global vars
COLLECTION_HOUSE = {} # will hold collections we treat in this run of the program; a dict of {collname2, collobject1}, ...
# CFG_CACHE_LAST_UPDATED_TIMESTAMP_TOLERANCE -- cache timestamp
# tolerance (in seconds), to account for the fact that an admin might
# accidentally happen to edit the collection definitions at exactly
# the same second when some webcoll process was about to be started.
# In order to be safe, let's put an exaggerated timestamp tolerance
# value such as 20 seconds:
CFG_CACHE_LAST_UPDATED_TIMESTAMP_TOLERANCE = 20
# CFG_CACHE_LAST_UPDATED_TIMESTAMP_FILE -- location of the cache
# timestamp file:
CFG_CACHE_LAST_UPDATED_TIMESTAMP_FILE = "%s/collections/last_updated" % CFG_CACHEDIR
# CFG_CACHE_LAST_FAST_UPDATED_TIMESTAMP_FILE -- location of the cache
# timestamp file usef when running webcoll in the fast-mode.
CFG_CACHE_LAST_FAST_UPDATED_TIMESTAMP_FILE = "%s/collections/last_fast_updated" % CFG_CACHEDIR
def get_collection(colname):
"""Return collection object from the collection house for given colname.
If does not exist, then create it."""
if not COLLECTION_HOUSE.has_key(colname):
colobject = Collection(colname)
COLLECTION_HOUSE[colname] = colobject
return COLLECTION_HOUSE[colname]
## auxiliary functions:
def is_selected(var, fld):
"Checks if the two are equal, and if yes, returns ' selected'. Useful for select boxes."
if var == fld:
return ' selected="selected"'
else:
return ""
def get_field(recID, tag):
"Gets list of field 'tag' for the record with 'recID' system number."
out = []
digit = tag[0:2]
bx = "bib%sx" % digit
bibx = "bibrec_bib%sx" % digit
query = "SELECT bx.value FROM %s AS bx, %s AS bibx WHERE bibx.id_bibrec='%s' AND bx.id=bibx.id_bibxxx AND bx.tag='%s'" \
% (bx, bibx, recID, tag)
res = run_sql(query)
for row in res:
out.append(row[0])
return out
def check_nbrecs_for_all_external_collections():
"""Check if any of the external collections have changed their total number of records, aka nbrecs.
Return True if any of the total numbers of records have changed and False if they're all the same."""
res = run_sql("SELECT name FROM collection WHERE dbquery LIKE 'hostedcollection:%';")
for row in res:
coll_name = row[0]
if (get_collection(coll_name)).check_nbrecs_for_external_collection():
return True
return False
class Collection:
"Holds the information on collections (id,name,dbquery)."
def __init__(self, name=""):
"Creates collection instance by querying the DB configuration database about 'name'."
self.calculate_reclist_run_already = 0 # to speed things up without much refactoring
self.update_reclist_run_already = 0 # to speed things up without much refactoring
self.reclist_updated_since_start = 0 # to check if webpage cache need rebuilding
self.reclist_with_nonpublic_subcolls = intbitset()
# temporary counters for the number of records in hosted collections
self.nbrecs_tmp = None # number of records in a hosted collection
self.nbrecs_from_hosted_collections = 0 # total number of records from
# descendant hosted collections
if not name:
self.name = CFG_SITE_NAME # by default we are working on the home page
self.id = 1
self.dbquery = None
self.nbrecs = None
self.reclist = intbitset()
self.old_reclist = intbitset()
self.reclist_updated_since_start = 1
else:
self.name = name
try:
res = run_sql("""SELECT id,name,dbquery,nbrecs,reclist FROM collection
WHERE name=%s""", (name,))
if res:
self.id = res[0][0]
self.name = res[0][1]
self.dbquery = res[0][2]
self.nbrecs = res[0][3]
try:
self.reclist = intbitset(res[0][4])
except:
self.reclist = intbitset()
self.reclist_updated_since_start = 1
else: # collection does not exist!
self.id = None
self.dbquery = None
self.nbrecs = None
self.reclist = intbitset()
self.reclist_updated_since_start = 1
self.old_reclist = intbitset(self.reclist)
except Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit(1)
def get_example_search_queries(self):
"""Returns list of sample search queries for this collection.
"""
res = run_sql("""SELECT example.body FROM example
LEFT JOIN collection_example on example.id=collection_example.id_example
WHERE collection_example.id_collection=%s ORDER BY collection_example.score""", (self.id,))
return [query[0] for query in res]
def get_name(self, ln=CFG_SITE_LANG, name_type="ln", prolog="", epilog="", prolog_suffix=" ", epilog_suffix=""):
"""Return nicely formatted collection name for language LN.
The NAME_TYPE may be 'ln' (=long name), 'sn' (=short name), etc."""
out = prolog
i18name = ""
res = run_sql("SELECT value FROM collectionname WHERE id_collection=%s AND ln=%s AND type=%s", (self.id, ln, name_type))
try:
i18name += res[0][0]
except IndexError:
pass
if i18name:
out += i18name
else:
out += self.name
out += epilog
return out
def get_collectionbox_name(self, ln=CFG_SITE_LANG, box_type="r"):
"""
Return collection-specific labelling of 'Focus on' (regular
collection), 'Narrow by' (virtual collection) and 'Latest
addition' boxes.
If translation for given language does not exist, use label
for CFG_SITE_LANG. If no custom label is defined for
CFG_SITE_LANG, return default label for the box.
@param ln: the language of the label
@param box_type: can be 'r' (=Narrow by), 'v' (=Focus on), 'l' (=Latest additions)
"""
i18name = ""
res = run_sql("SELECT value FROM collectionboxname WHERE id_collection=%s AND ln=%s AND type=%s", (self.id, ln, box_type))
try:
i18name = res[0][0]
except IndexError:
res = run_sql("SELECT value FROM collectionboxname WHERE id_collection=%s AND ln=%s AND type=%s", (self.id, CFG_SITE_LANG, box_type))
try:
i18name = res[0][0]
except IndexError:
pass
if not i18name:
# load the right message language
_ = gettext_set_language(ln)
if box_type == "v":
i18name = _('Focus on:')
elif box_type == "r":
if CFG_SCOAP3_SITE:
i18name = _('Narrow by publisher/journal:')
else:
i18name = _('Narrow by collection:')
elif box_type == "l":
i18name = _('Latest additions:')
return i18name
def get_ancestors(self):
"Returns list of ancestors of the current collection."
ancestors = []
ancestors_ids = intbitset()
id_son = self.id
while 1:
query = "SELECT cc.id_dad,c.name FROM collection_collection AS cc, collection AS c "\
"WHERE cc.id_son=%d AND c.id=cc.id_dad" % int(id_son)
res = run_sql(query, None, 1)
if res:
col_ancestor = get_collection(res[0][1])
# looking for loops
if self.id in ancestors_ids:
write_message("Loop found in collection %s" % self.name, stream=sys.stderr)
raise OverflowError("Loop found in collection %s" % self.name)
else:
ancestors.append(col_ancestor)
ancestors_ids.add(col_ancestor.id)
id_son = res[0][0]
else:
break
ancestors.reverse()
return ancestors
def restricted_p(self):
"""Predicate to test if the collection is restricted or not. Return the contect of the
`restrited' column of the collection table (typically Apache group). Otherwise return
None if the collection is public."""
if collection_restricted_p(self.name):
return 1
return None
def get_sons(self, type='r'):
"Returns list of direct sons of type 'type' for the current collection."
sons = []
id_dad = self.id
query = "SELECT cc.id_son,c.name FROM collection_collection AS cc, collection AS c "\
"WHERE cc.id_dad=%d AND cc.type='%s' AND c.id=cc.id_son ORDER BY score DESC, c.name ASC" % (int(id_dad), type)
res = run_sql(query)
for row in res:
sons.append(get_collection(row[1]))
return sons
def get_descendants(self, type='r'):
"Returns list of all descendants of type 'type' for the current collection."
descendants = []
descendant_ids = intbitset()
id_dad = self.id
query = "SELECT cc.id_son,c.name FROM collection_collection AS cc, collection AS c "\
"WHERE cc.id_dad=%d AND cc.type='%s' AND c.id=cc.id_son ORDER BY score DESC" % (int(id_dad), type)
res = run_sql(query)
for row in res:
col_desc = get_collection(row[1])
# looking for loops
if self.id in descendant_ids:
write_message("Loop found in collection %s" % self.name, stream=sys.stderr)
raise OverflowError("Loop found in collection %s" % self.name)
else:
descendants.append(col_desc)
descendant_ids.add(col_desc.id)
tmp_descendants = col_desc.get_descendants()
for descendant in tmp_descendants:
descendant_ids.add(descendant.id)
descendants += tmp_descendants
return descendants
def write_cache_file(self, filename='', filebody={}):
"Write a file inside collection cache."
# open file:
dirname = "%s/collections" % (CFG_CACHEDIR)
mymkdir(dirname)
fullfilename = dirname + "/%s.html" % filename
try:
os.umask(022)
f = open(fullfilename, "wb")
except IOError, v:
try:
(code, message) = v
except:
code = 0
message = v
print "I/O Error: " + str(message) + " (" + str(code) + ")"
sys.exit(1)
# print user info:
write_message("... creating %s" % fullfilename, verbose=6)
# print page body:
cPickle.dump(filebody, f, cPickle.HIGHEST_PROTOCOL)
# close file:
f.close()
def update_webpage_cache(self, lang):
"""Create collection page header, navtrail, body (including left and right stripes) and footer, and
call write_cache_file() afterwards to update the collection webpage cache."""
## precalculate latest additions for non-aggregate
## collections (the info is ln and as independent)
if self.dbquery:
if CFG_WEBSEARCH_I18N_LATEST_ADDITIONS:
self.create_latest_additions_info(ln=lang)
else:
self.create_latest_additions_info()
# load the right message language
_ = gettext_set_language(lang)
# create dictionary with data
cache = {"te_portalbox" : self.create_portalbox(lang, 'te'),
"np_portalbox" : self.create_portalbox(lang, 'np'),
"ne_portalbox" : self.create_portalbox(lang, 'ne'),
"tp_portalbox" : self.create_portalbox(lang, "tp"),
"lt_portalbox" : self.create_portalbox(lang, "lt"),
"rt_portalbox" : self.create_portalbox(lang, "rt"),
"last_updated" : convert_datestruct_to_dategui(time.localtime(),
ln=lang)}
for aas in CFG_WEBSEARCH_ENABLED_SEARCH_INTERFACES: # do light, simple and advanced search pages:
cache["navtrail_%s" % aas] = self.create_navtrail_links(aas, lang)
cache["searchfor_%s" % aas] = self.create_searchfor(aas, lang)
cache["narrowsearch_%s" % aas] = self.create_narrowsearch(aas, lang, 'r')
cache["focuson_%s" % aas] = self.create_narrowsearch(aas, lang, "v")+ \
self.create_external_collections_box(lang)
cache["instantbrowse_%s" % aas] = self.create_instant_browse(aas=aas, ln=lang)
# write cache file
self.write_cache_file("%s-ln=%s"%(self.name, lang), cache)
return cache
def create_navtrail_links(self, aas=CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE, ln=CFG_SITE_LANG):
"""Creates navigation trail links, i.e. links to collection
ancestors (except Home collection). If aas==1, then links to
Advanced Search interfaces; otherwise Simple Search.
"""
dads = []
for dad in self.get_ancestors():
if dad.name != CFG_SITE_NAME: # exclude Home collection
dads.append((dad.name, dad.get_name(ln)))
return websearch_templates.tmpl_navtrail_links(
aas=aas, ln=ln, dads=dads)
def create_portalbox(self, lang=CFG_SITE_LANG, position="rt"):
"""Creates portalboxes of language CFG_SITE_LANG of the position POSITION by consulting DB configuration database.
The position may be: 'lt'='left top', 'rt'='right top', etc."""
out = ""
query = "SELECT p.title,p.body FROM portalbox AS p, collection_portalbox AS cp "\
" WHERE cp.id_collection=%d AND p.id=cp.id_portalbox AND cp.ln='%s' AND cp.position='%s' "\
" ORDER BY cp.score DESC" % (self.id, lang, position)
res = run_sql(query)
for row in res:
title, body = row[0], row[1]
if title:
out += websearch_templates.tmpl_portalbox(title = title,
body = body)
else:
# no title specified, so print body ``as is'' only:
out += body
return out
def create_narrowsearch(self, aas=CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE, ln=CFG_SITE_LANG, type="r"):
"""Creates list of collection descendants of type 'type' under title 'title'.
If aas==1, then links to Advanced Search interfaces; otherwise Simple Search.
Suitable for 'Narrow search' and 'Focus on' boxes."""
# get list of sons and analyse it
sons = self.get_sons(type)
if not sons:
return ''
# get descendents
descendants = self.get_descendants(type)
grandsons = []
if CFG_WEBSEARCH_NARROW_SEARCH_SHOW_GRANDSONS:
# load grandsons for each son
for son in sons:
grandsons.append(son.get_sons())
# return ""
return websearch_templates.tmpl_narrowsearch(
aas = aas,
ln = ln,
type = type,
father = self,
has_grandchildren = len(descendants)>len(sons),
sons = sons,
display_grandsons = CFG_WEBSEARCH_NARROW_SEARCH_SHOW_GRANDSONS,
grandsons = grandsons
)
def create_external_collections_box(self, ln=CFG_SITE_LANG):
external_collection_load_states()
if not dico_collection_external_searches.has_key(self.id):
return ""
engines_list = external_collection_sort_engine_by_name(dico_collection_external_searches[self.id])
return websearch_templates.tmpl_searchalso(ln, engines_list, self.id)
def create_latest_additions_info(self, rg=CFG_WEBSEARCH_INSTANT_BROWSE, ln=CFG_SITE_LANG):
"""
Create info about latest additions that will be used for
create_instant_browse() later.
"""
self.latest_additions_info = []
if self.nbrecs and self.reclist:
# firstly, get last 'rg' records:
recIDs = list(self.reclist)
of = 'hb'
# CERN hack begins: tweak latest additions for selected collections:
if CFG_CERN_SITE:
# alter recIDs list for some CERN collections:
this_year = time.strftime("%Y", time.localtime())
if self.name in ['CERN Yellow Reports','Videos']:
last_year = str(int(this_year) - 1)
# detect recIDs only from this and past year:
recIDs = list(self.reclist & \
search_pattern_parenthesised(p='year:%s or year:%s' % \
(this_year, last_year)))
elif self.name in ['VideosXXX']:
# detect recIDs only from this year:
recIDs = list(self.reclist & \
search_pattern_parenthesised(p='year:%s' % this_year))
elif self.name == 'CMS Physics Analysis Summaries' and \
1281585 in self.reclist:
# REALLY, REALLY temporary hack
recIDs = list(self.reclist)
recIDs.remove(1281585)
# apply special filters:
if self.name in ['Videos']:
# select only videos with movies:
recIDs = list(intbitset(recIDs) & \
search_pattern_parenthesised(p='collection:"PUBLVIDEOMOVIE"'))
of = 'hvp'
# sort some CERN collections specially:
if self.name in ['Videos',
'Video Clips',
'Video Movies',
'Video News',
'Video Rushes',
'Webcast',
'ATLAS Videos',
'Restricted Video Movies',
'Restricted Video Rushes',
'LHC First Beam Videos',
'CERN openlab Videos']:
recIDs = sort_records(None, recIDs, '269__c')
elif self.name in ['LHCb Talks']:
recIDs = sort_records(None, recIDs, 'reportnumber')
elif self.name in ['CERN Yellow Reports']:
recIDs = sort_records(None, recIDs, '084__a')
# CERN hack ends.
total = len(recIDs)
to_display = min(rg, total)
for idx in range(total-1, total-to_display-1, -1):
recid = recIDs[idx]
self.latest_additions_info.append({'id': recid,
'format': format_record(recid, of, ln=ln),
'date': get_creation_date(recid, fmt="%Y-%m-%d<br />%H:%i")})
return
def create_instant_browse(self, rg=CFG_WEBSEARCH_INSTANT_BROWSE, aas=CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE, ln=CFG_SITE_LANG):
"Searches database and produces list of last 'rg' records."
if self.restricted_p():
return websearch_templates.tmpl_box_restricted_content(ln = ln)
if str(self.dbquery).startswith("hostedcollection:"):
return websearch_templates.tmpl_box_hosted_collection(ln = ln)
if rg == 0:
# do not show latest additions box
return ""
# CERN hack: do not display latest additions for some CERN collections:
if CFG_CERN_SITE and self.name in ['Periodicals', 'Electronic Journals',
'Press Office Photo Selection',
'Press Office Video Selection']:
return ""
try:
self.latest_additions_info
latest_additions_info_p = True
except:
latest_additions_info_p = False
if latest_additions_info_p:
passIDs = []
for idx in range(0, min(len(self.latest_additions_info), rg)):
# CERN hack: display the records in a grid layout, so do not show the related links
if CFG_CERN_SITE and self.name in ['Videos']:
passIDs.append({'id': self.latest_additions_info[idx]['id'],
'body': self.latest_additions_info[idx]['format'],
'date': self.latest_additions_info[idx]['date']})
else:
passIDs.append({'id': self.latest_additions_info[idx]['id'],
'body': self.latest_additions_info[idx]['format'] + \
websearch_templates.tmpl_record_links(recid=self.latest_additions_info[idx]['id'],
rm='citation',
ln=ln),
'date': self.latest_additions_info[idx]['date']})
if self.nbrecs > rg:
url = websearch_templates.build_search_url(
cc=self.name, jrec=rg+1, ln=ln, aas=aas)
else:
url = ""
# CERN hack: display the records in a grid layout
if CFG_CERN_SITE and self.name in ['Videos']:
return websearch_templates.tmpl_instant_browse(
aas=aas, ln=ln, recids=passIDs, more_link=url, grid_layout=True, father=self)
return websearch_templates.tmpl_instant_browse(
aas=aas, ln=ln, recids=passIDs, more_link=url, father=self)
return websearch_templates.tmpl_box_no_records(ln=ln)
def create_searchoptions(self):
"Produces 'Search options' portal box."
box = ""
query = """SELECT DISTINCT(cff.id_field),f.code,f.name FROM collection_field_fieldvalue AS cff, field AS f
WHERE cff.id_collection=%d AND cff.id_fieldvalue IS NOT NULL AND cff.id_field=f.id
ORDER BY cff.score DESC""" % self.id
res = run_sql(query)
if res:
for row in res:
field_id = row[0]
field_code = row[1]
field_name = row[2]
query_bis = """SELECT fv.value,fv.name FROM fieldvalue AS fv, collection_field_fieldvalue AS cff
WHERE cff.id_collection=%d AND cff.type='seo' AND cff.id_field=%d AND fv.id=cff.id_fieldvalue
ORDER BY cff.score_fieldvalue DESC, cff.score DESC, fv.name ASC""" % (self.id, field_id)
res_bis = run_sql(query_bis)
if res_bis:
values = [{'value' : '', 'text' : 'any' + ' ' + field_name}] # FIXME: internationalisation of "any"
for row_bis in res_bis:
values.append({'value' : cgi.escape(row_bis[0], 1), 'text' : row_bis[1]})
box += websearch_templates.tmpl_select(
fieldname = field_code,
values = values
)
return box
def create_sortoptions(self, ln=CFG_SITE_LANG):
"""Produces 'Sort options' portal box."""
# load the right message language
_ = gettext_set_language(ln)
box = ""
query = """SELECT f.code,f.name FROM field AS f, collection_field_fieldvalue AS cff
WHERE id_collection=%d AND cff.type='soo' AND cff.id_field=f.id
ORDER BY cff.score DESC, f.name ASC""" % self.id
values = [{'value' : '', 'text': "- %s -" % _("latest first")}]
res = run_sql(query)
if res:
for row in res:
values.append({'value' : row[0], 'text': get_field_i18nname(row[1], ln)})
else:
for tmp in ('title', 'author', 'report number', 'year'):
values.append({'value' : tmp.replace(' ', ''), 'text' : get_field_i18nname(tmp, ln)})
box = websearch_templates.tmpl_select(
fieldname = 'sf',
css_class = 'address',
values = values
)
box += websearch_templates.tmpl_select(
fieldname = 'so',
css_class = 'address',
values = [
{'value' : 'a' , 'text' : _("asc.")},
{'value' : 'd' , 'text' : _("desc.")}
]
)
return box
def create_rankoptions(self, ln=CFG_SITE_LANG):
"Produces 'Rank options' portal box."
# load the right message language
_ = gettext_set_language(ln)
values = [{'value' : '', 'text': "- %s %s -" % (string.lower(_("OR")), _("rank by"))}]
for (code, name) in get_bibrank_methods(self.id, ln):
values.append({'value' : code, 'text': name})
box = websearch_templates.tmpl_select(
fieldname = 'rm',
css_class = 'address',
values = values
)
return box
def create_displayoptions(self, ln=CFG_SITE_LANG):
"Produces 'Display options' portal box."
# load the right message language
_ = gettext_set_language(ln)
values = []
for i in ['10', '25', '50', '100', '250', '500']:
values.append({'value' : i, 'text' : i + ' ' + _("results")})
box = websearch_templates.tmpl_select(
fieldname = 'rg',
selected = str(CFG_WEBSEARCH_DEF_RECORDS_IN_GROUPS),
css_class = 'address',
values = values
)
if self.get_sons():
box += websearch_templates.tmpl_select(
fieldname = 'sc',
css_class = 'address',
values = [
{'value' : '1' , 'text' : CFG_SCOAP3_SITE and _("split by publisher/journal") or _("split by collection")},
{'value' : '0' , 'text' : _("single list")}
]
)
return box
def create_formatoptions(self, ln=CFG_SITE_LANG):
"Produces 'Output format options' portal box."
# load the right message language
_ = gettext_set_language(ln)
box = ""
values = []
query = """SELECT f.code,f.name FROM format AS f, collection_format AS cf
WHERE cf.id_collection=%d AND cf.id_format=f.id AND f.visibility='1'
ORDER BY cf.score DESC, f.name ASC""" % self.id
res = run_sql(query)
if res:
for row in res:
values.append({'value' : row[0], 'text': row[1]})
else:
values.append({'value' : 'hb', 'text' : "HTML %s" % _("brief")})
box = websearch_templates.tmpl_select(
fieldname = 'of',
css_class = 'address',
values = values
)
return box
def create_searchwithin_selection_box(self, fieldname='f', value='', ln='en'):
"""Produces 'search within' selection box for the current collection."""
# get values
query = """SELECT f.code,f.name FROM field AS f, collection_field_fieldvalue AS cff
WHERE cff.type='sew' AND cff.id_collection=%d AND cff.id_field=f.id
ORDER BY cff.score DESC, f.name ASC""" % self.id
res = run_sql(query)
values = [{'value' : '', 'text' : get_field_i18nname("any field", ln)}]
if res:
for row in res:
values.append({'value' : row[0], 'text' : get_field_i18nname(row[1], ln)})
else:
if CFG_CERN_SITE:
for tmp in ['title', 'author', 'abstract', 'report number', 'year']:
values.append({'value' : tmp.replace(' ', ''), 'text' : get_field_i18nname(tmp, ln)})
else:
for tmp in ['title', 'author', 'abstract', 'keyword', 'report number', 'journal', 'year', 'fulltext', 'reference']:
values.append({'value' : tmp.replace(' ', ''), 'text' : get_field_i18nname(tmp, ln)})
return websearch_templates.tmpl_searchwithin_select(
fieldname = fieldname,
ln = ln,
selected = value,
values = values
)
def create_searchexample(self):
"Produces search example(s) for the current collection."
out = "$collSearchExamples = getSearchExample(%d, $se);" % self.id
return out
def create_searchfor(self, aas=CFG_WEBSEARCH_DEFAULT_SEARCH_INTERFACE, ln=CFG_SITE_LANG):
"Produces either Simple or Advanced 'Search for' box for the current collection."
if aas == 1:
return self.create_searchfor_advanced(ln)
elif aas == 0:
return self.create_searchfor_simple(ln)
else:
return self.create_searchfor_light(ln)
def create_searchfor_light(self, ln=CFG_SITE_LANG):
"Produces light 'Search for' box for the current collection."
return websearch_templates.tmpl_searchfor_light(
ln=ln,
collection_id = self.name,
collection_name=self.get_name(ln=ln),
record_count=self.nbrecs,
example_search_queries=self.get_example_search_queries(),
)
def create_searchfor_simple(self, ln=CFG_SITE_LANG):
"Produces simple 'Search for' box for the current collection."
return websearch_templates.tmpl_searchfor_simple(
ln=ln,
collection_id = self.name,
collection_name=self.get_name(ln=ln),
record_count=self.nbrecs,
middle_option = self.create_searchwithin_selection_box(ln=ln),
)
def create_searchfor_advanced(self, ln=CFG_SITE_LANG):
"Produces advanced 'Search for' box for the current collection."
return websearch_templates.tmpl_searchfor_advanced(
ln = ln,
collection_id = self.name,
collection_name=self.get_name(ln=ln),
record_count=self.nbrecs,
middle_option_1 = self.create_searchwithin_selection_box('f1', ln=ln),
middle_option_2 = self.create_searchwithin_selection_box('f2', ln=ln),
middle_option_3 = self.create_searchwithin_selection_box('f3', ln=ln),
searchoptions = self.create_searchoptions(),
sortoptions = self.create_sortoptions(ln),
rankoptions = self.create_rankoptions(ln),
displayoptions = self.create_displayoptions(ln),
formatoptions = self.create_formatoptions(ln)
)
def calculate_reclist(self):
"""
Calculate, set and return the (reclist,
reclist_with_nonpublic_subcolls,
nbrecs_from_hosted_collections)
tuple for the given collection."""
if str(self.dbquery).startswith("hostedcollection:"):
# we don't normally use this function to calculate the reclist
# for hosted collections. In case we do, recursively for a regular
# ancestor collection, then quickly return the object attributes.
return (self.reclist,
self.reclist_with_nonpublic_subcolls,
self.nbrecs)
if self.calculate_reclist_run_already:
# do we really have to recalculate? If not,
# then return the object attributes
return (self.reclist,
self.reclist_with_nonpublic_subcolls,
self.nbrecs_from_hosted_collections)
write_message("... calculating reclist of %s" % self.name, verbose=6)
reclist = intbitset() # will hold results for public sons only; good for storing into DB
reclist_with_nonpublic_subcolls = intbitset() # will hold results for both public and nonpublic sons; good for deducing total
# number of documents
nbrecs_from_hosted_collections = 0 # will hold the total number of records from descendant hosted collections
if not self.dbquery:
# A - collection does not have dbquery, so query recursively all its sons
# that are either non-restricted or that have the same restriction rules
for coll in self.get_sons():
coll_reclist,\
coll_reclist_with_nonpublic_subcolls,\
coll_nbrecs_from_hosted_collection = coll.calculate_reclist()
if ((coll.restricted_p() is None) or
(coll.restricted_p() == self.restricted_p())):
# add this reclist ``for real'' only if it is public
reclist.union_update(coll_reclist)
reclist_with_nonpublic_subcolls.union_update(coll_reclist_with_nonpublic_subcolls)
# increment the total number of records from descendant hosted collections
nbrecs_from_hosted_collections += coll_nbrecs_from_hosted_collection
else:
# B - collection does have dbquery, so compute it:
# (note: explicitly remove DELETED records)
if CFG_CERN_SITE:
reclist = search_pattern_parenthesised(None, self.dbquery + \
' -980__:"DELETED" -980__:"DUMMY"', ap=-9) #ap=-9 for allow queries containing hidden tags
else:
reclist = search_pattern_parenthesised(None, self.dbquery + ' -980__:"DELETED"', ap=-9) #ap=-9 allow queries containing hidden tags
reclist_with_nonpublic_subcolls = copy.deepcopy(reclist)
# store the results:
self.nbrecs_from_hosted_collections = nbrecs_from_hosted_collections
self.nbrecs = len(reclist_with_nonpublic_subcolls) + \
nbrecs_from_hosted_collections
self.reclist = reclist
self.reclist_with_nonpublic_subcolls = reclist_with_nonpublic_subcolls
# last but not least, update the speed-up flag:
self.calculate_reclist_run_already = 1
# return the two sets, as well as
# the total number of records from descendant hosted collections:
return (self.reclist,
self.reclist_with_nonpublic_subcolls,
self.nbrecs_from_hosted_collections)
def calculate_nbrecs_for_external_collection(self, timeout=CFG_EXTERNAL_COLLECTION_TIMEOUT):
"""Calculate the total number of records, aka nbrecs, for given external collection."""
#if self.calculate_reclist_run_already:
# do we have to recalculate?
#return self.nbrecs
#write_message("... calculating nbrecs of external collection %s" % self.name, verbose=6)
if external_collections_dictionary.has_key(self.name):
engine = external_collections_dictionary[self.name]
if engine.parser:
self.nbrecs_tmp = engine.parser.parse_nbrecs(timeout)
if self.nbrecs_tmp >= 0: return self.nbrecs_tmp
# the parse_nbrecs() function returns negative values for some specific cases
# maybe we can handle these specific cases, some warnings or something
# for now the total number of records remains silently the same
else: return self.nbrecs
else: write_message("External collection %s does not have a parser!" % self.name, verbose=6)
else: write_message("External collection %s not found!" % self.name, verbose=6)
return 0
# last but not least, update the speed-up flag:
#self.calculate_reclist_run_already = 1
def check_nbrecs_for_external_collection(self):
"""Check if the external collections has changed its total number of records, aka nbrecs.
Rerurns True if the total number of records has changed and False if it's the same"""
write_message("*** self.nbrecs = %s / self.cal...ion = %s ***" % (str(self.nbrecs), str(self.calculate_nbrecs_for_external_collection())), verbose=6)
write_message("*** self.nbrecs != self.cal...ion = %s ***" % (str(self.nbrecs != self.calculate_nbrecs_for_external_collection()),), verbose=6)
return self.nbrecs != self.calculate_nbrecs_for_external_collection(CFG_HOSTED_COLLECTION_TIMEOUT_NBRECS)
def set_nbrecs_for_external_collection(self):
"""Set this external collection's total number of records, aka nbrecs"""
if self.calculate_reclist_run_already:
# do we have to recalculate?
return
write_message("... calculating nbrecs of external collection %s" % self.name, verbose=6)
if self.nbrecs_tmp:
self.nbrecs = self.nbrecs_tmp
else:
self.nbrecs = self.calculate_nbrecs_for_external_collection(CFG_HOSTED_COLLECTION_TIMEOUT_NBRECS)
# last but not least, update the speed-up flag:
self.calculate_reclist_run_already = 1
def get_added_records(self):
"""Return new records added since last run."""
return self.reclist - self.old_reclist
def update_reclist(self):
"Update the record universe for given collection; nbrecs, reclist of the collection table."
if self.update_reclist_run_already:
# do we have to reupdate?
return 0
write_message("... updating reclist of %s (%s recs)" % (self.name, self.nbrecs), verbose=6)
sys.stdout.flush()
try:
## In principle we could skip this update if old_reclist==reclist
## however we just update it here in case of race-conditions.
run_sql("UPDATE collection SET nbrecs=%s, reclist=%s WHERE id=%s",
(self.nbrecs, self.reclist.fastdump(), self.id))
if self.old_reclist != self.reclist:
self.reclist_updated_since_start = 1
else:
write_message("... no changes in reclist detected", verbose=6)
except Error, e:
print "Database Query Error %d: %s." % (e.args[0], e.args[1])
sys.exit(1)
# last but not least, update the speed-up flag:
self.update_reclist_run_already = 1
return 0
def perform_display_collection(colID, colname, aas, ln, em, show_help_boxes):
"""Returns the data needed to display a collection page
The arguments are as follows:
colID - id of the collection to display
colname - name of the collection to display
aas - 0 if simple search, 1 if advanced search
ln - language of the page
em - code to display just part of the page
show_help_boxes - whether to show the help boxes or not"""
# check and update cache if necessary
cachedfile = open("%s/collections/%s-ln=%s.html" %
(CFG_CACHEDIR, colname, ln), "rb")
try:
data = cPickle.load(cachedfile)
except ValueError:
data = get_collection(colname).update_webpage_cache(ln)
cachedfile.close()
# check em value to return just part of the page
if em != "":
if EM_REPOSITORY["search_box"] not in em:
data["searchfor_%s" % aas] = ""
if EM_REPOSITORY["see_also_box"] not in em:
data["focuson_%s" % aas] = ""
if EM_REPOSITORY["all_portalboxes"] not in em:
if EM_REPOSITORY["te_portalbox"] not in em:
data["te_portalbox"] = ""
if EM_REPOSITORY["np_portalbox"] not in em:
data["np_portalbox"] = ""
if EM_REPOSITORY["ne_portalbox"] not in em:
data["ne_portalbox"] = ""
if EM_REPOSITORY["tp_portalbox"] not in em:
data["tp_portalbox"] = ""
if EM_REPOSITORY["lt_portalbox"] not in em:
data["lt_portalbox"] = ""
if EM_REPOSITORY["rt_portalbox"] not in em:
data["rt_portalbox"] = ""
c_body = websearch_templates.tmpl_webcoll_body(ln, colID, data["te_portalbox"],
data["searchfor_%s"%aas], data["np_portalbox"], data["narrowsearch_%s"%aas],
data["focuson_%s"%aas], data["instantbrowse_%s"%aas], data["ne_portalbox"],
em=="" or EM_REPOSITORY["body"] in em)
if show_help_boxes <= 0:
data["rt_portalbox"] = ""
return (c_body, data["navtrail_%s"%aas], data["lt_portalbox"], data["rt_portalbox"],
data["tp_portalbox"], data["te_portalbox"], data["last_updated"])
def get_datetime(var, format_string="%Y-%m-%d %H:%M:%S"):
"""Returns a date string according to the format string.
It can handle normal date strings and shifts with respect
to now."""
date = time.time()
shift_re = re.compile("([-\+]{0,1})([\d]+)([dhms])")
factors = {"d":24*3600, "h":3600, "m":60, "s":1}
m = shift_re.match(var)
if m:
sign = m.groups()[0] == "-" and -1 or 1
factor = factors[m.groups()[2]]
value = float(m.groups()[1])
date = time.localtime(date + sign * factor * value)
date = strftime(format_string, date)
else:
date = time.strptime(var, format_string)
date = strftime(format_string, date)
return date
def get_current_time_timestamp():
"""Return timestamp corresponding to the current time."""
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def compare_timestamps_with_tolerance(timestamp1,
timestamp2,
tolerance=0):
"""Compare two timestamps TIMESTAMP1 and TIMESTAMP2, of the form
'2005-03-31 17:37:26'. Optionally receives a TOLERANCE argument
(in seconds). Return -1 if TIMESTAMP1 is less than TIMESTAMP2
minus TOLERANCE, 0 if they are equal within TOLERANCE limit,
and 1 if TIMESTAMP1 is greater than TIMESTAMP2 plus TOLERANCE.
"""
# remove any trailing .00 in timestamps:
timestamp1 = re.sub(r'\.[0-9]+$', '', timestamp1)
timestamp2 = re.sub(r'\.[0-9]+$', '', timestamp2)
# first convert timestamps to Unix epoch seconds:
timestamp1_seconds = calendar.timegm(time.strptime(timestamp1, "%Y-%m-%d %H:%M:%S"))
timestamp2_seconds = calendar.timegm(time.strptime(timestamp2, "%Y-%m-%d %H:%M:%S"))
# now compare them:
if timestamp1_seconds < timestamp2_seconds - tolerance:
return -1
elif timestamp1_seconds > timestamp2_seconds + tolerance:
return 1
else:
return 0
def get_database_last_updated_timestamp():
"""Return last updated timestamp for collection-related and
record-related database tables.
"""
database_tables_timestamps = []
database_tables_timestamps.append(get_table_update_time('bibrec'))
## In INSPIRE bibfmt is on innodb and there is not such configuration
bibfmt_last_update = run_sql("SELECT max(last_updated) FROM bibfmt")
if bibfmt_last_update and bibfmt_last_update[0][0] is not None:
database_tables_timestamps.append(str(bibfmt_last_update[0][0]))
try:
database_tables_timestamps.append(get_table_update_time('idxWORD%'))
except ValueError:
# There are no indexes in the database. That's OK.
pass
database_tables_timestamps.append(get_table_update_time('collection%'))
database_tables_timestamps.append(get_table_update_time('portalbox'))
database_tables_timestamps.append(get_table_update_time('field%'))
database_tables_timestamps.append(get_table_update_time('format%'))
database_tables_timestamps.append(get_table_update_time('rnkMETHODNAME'))
database_tables_timestamps.append(get_table_update_time('accROLE_accACTION_accARGUMENT', run_on_slave=True))
return max(database_tables_timestamps)
def get_cache_last_updated_timestamp():
"""Return last updated cache timestamp."""
try:
f = open(CFG_CACHE_LAST_UPDATED_TIMESTAMP_FILE, "r")
except:
return "1970-01-01 00:00:00"
timestamp = f.read()
f.close()
return timestamp
def set_cache_last_updated_timestamp(timestamp):
"""Set last updated cache timestamp to TIMESTAMP."""
try:
f = open(CFG_CACHE_LAST_UPDATED_TIMESTAMP_FILE, "w")
except:
pass
f.write(timestamp)
f.close()
return timestamp
def main():
"""Main that construct all the bibtask."""
task_init(authorization_action="runwebcoll",
authorization_msg="WebColl Task Submission",
description="""Description:
webcoll updates the collection cache (record universe for a
given collection plus web page elements) based on invenio.conf and DB
configuration parameters. If the collection name is passed as an argument,
only this collection's cache will be updated. If the recursive option is
set as well, the collection's descendants will also be updated.\n""",
help_specific_usage=" -c, --collection\t Update cache for the given "
"collection only. [all]\n"
" -r, --recursive\t Update cache for the given collection and all its\n"
"\t\t\t descendants (to be used in combination with -c). [no]\n"
" -q, --quick\t\t Skip webpage cache update for those collections whose\n"
"\t\t\t reclist was not changed. Note: if you use this option, it is advised\n"
"\t\t\t to schedule, e.g. a nightly 'webcoll --force'. [no]\n"
" -f, --force\t\t Force update even if cache is up to date. [no]\n"
" -p, --part\t\t Update only certain cache parts (1=reclist,"
" 2=webpage). [both]\n"
" -l, --language\t Update pages in only certain language"
" (e.g. fr,it,...). [all]\n",
version=__revision__,
specific_params=("c:rqfp:l:", [
"collection=",
"recursive",
"quick",
"force",
"part=",
"language="
]),
task_submit_elaborate_specific_parameter_fnc=task_submit_elaborate_specific_parameter,
task_submit_check_options_fnc=task_submit_check_options,
task_run_fnc=task_run_core)
def task_submit_elaborate_specific_parameter(key, value, opts, args):
""" Given the string key it checks it's meaning, eventually using the value.
Usually it fills some key in the options dict.
It must return True if it has elaborated the key, False, if it doesn't
know that key.
eg:
if key in ['-n', '--number']:
self.options['number'] = value
return True
return False
"""
if key in ("-c", "--collection"):
task_set_option("collection", value)
elif key in ("-r", "--recursive"):
task_set_option("recursive", 1)
elif key in ("-f", "--force"):
task_set_option("force", 1)
elif key in ("-q", "--quick"):
task_set_option("quick", 1)
elif key in ("-p", "--part"):
task_set_option("part", int(value))
elif key in ("-l", "--language"):
languages = task_get_option("language", [])
languages += value.split(',')
for ln in languages:
if ln not in CFG_SITE_LANGS:
print 'ERROR: "%s" is not a recognized language code' % ln
return False
task_set_option("language", languages)
else:
return False
return True
def task_submit_check_options():
if task_has_option('collection'):
coll = get_collection(task_get_option("collection"))
if coll.id is None:
print 'ERROR: Collection "%s" does not exist' % coll.name
return False
return True
def task_run_core():
""" Reimplement to add the body of the task."""
##
## ------->--->time--->------>
## (-1) | ( 0) | ( 1)
## | | |
## [T.db] | [T.fc] | [T.db]
## | | |
## |<-tol|tol->|
##
## the above is the compare_timestamps_with_tolerance result "diagram"
## [T.db] stands fore the database timestamp and [T.fc] for the file cache timestamp
## ( -1, 0, 1) stand for the returned value
## tol stands for the tolerance in seconds
##
## When a record has been added or deleted from one of the collections the T.db becomes greater that the T.fc
## and when webcoll runs it is fully ran. It recalculates the reclists and nbrecs, and since it updates the
## collections db table it also updates the T.db. The T.fc is set as the moment the task started running thus
## slightly before the T.db (practically the time distance between the start of the task and the last call of
## update_reclist). Therefore when webcoll runs again, and even if no database changes have taken place in the
## meanwhile, it fully runs (because compare_timestamps_with_tolerance returns 0). This time though, and if
## no databases changes have taken place, the T.db remains the same while T.fc is updated and as a result if
## webcoll runs again it will not be fully ran
##
task_run_start_timestamp = get_current_time_timestamp()
colls = []
params = {}
task_set_task_param("post_process_params", params)
# decide whether we need to run or not, by comparing last updated timestamps:
write_message("Database timestamp is %s." % get_database_last_updated_timestamp(), verbose=3)
write_message("Collection cache timestamp is %s." % get_cache_last_updated_timestamp(), verbose=3)
if task_has_option("part"):
write_message("Running cache update part %s only." % task_get_option("part"), verbose=3)
if check_nbrecs_for_all_external_collections() or task_has_option("force") or \
compare_timestamps_with_tolerance(get_database_last_updated_timestamp(),
get_cache_last_updated_timestamp(),
CFG_CACHE_LAST_UPDATED_TIMESTAMP_TOLERANCE) >= 0:
## either forced update was requested or cache is not up to date, so recreate it:
# firstly, decide which collections to do:
if task_has_option("collection"):
coll = get_collection(task_get_option("collection"))
colls.append(coll)
if task_has_option("recursive"):
r_type_descendants = coll.get_descendants(type='r')
colls += r_type_descendants
v_type_descendants = coll.get_descendants(type='v')
colls += v_type_descendants
else:
res = run_sql("SELECT name FROM collection ORDER BY id")
for row in res:
colls.append(get_collection(row[0]))
# secondly, update collection reclist cache:
if task_get_option('part', 1) == 1:
all_recids_added = intbitset()
i = 0
for coll in colls:
i += 1
write_message("%s / reclist cache update" % coll.name)
if str(coll.dbquery).startswith("hostedcollection:"):
coll.set_nbrecs_for_external_collection()
else:
coll.calculate_reclist()
coll.update_reclist()
task_update_progress("Part 1/2: done %d/%d" % (i, len(colls)))
all_recids_added.update(coll.get_added_records())
task_sleep_now_if_required(can_stop_too=True)
params.update({'recids': list(all_recids_added)})
# thirdly, update collection webpage cache:
if task_get_option("part", 2) == 2:
i = 0
for coll in colls:
i += 1
if coll.reclist_updated_since_start or task_has_option("collection") or task_get_option("force") or not task_get_option("quick"):
write_message("%s / webpage cache update" % coll.name)
for lang in CFG_SITE_LANGS:
coll.update_webpage_cache(lang)
else:
write_message("%s / webpage cache seems not to need an update and --quick was used" % coll.name, verbose=2)
task_update_progress("Part 2/2: done %d/%d" % (i, len(colls)))
task_sleep_now_if_required(can_stop_too=True)
# finally update the cache last updated timestamp:
# (but only when all collections were updated, not when only
# some of them were forced-updated as per admin's demand)
if not task_has_option("collection"):
set_cache_last_updated_timestamp(task_run_start_timestamp)
write_message("Collection cache timestamp is set to %s." % get_cache_last_updated_timestamp(), verbose=3)
task_set_task_param("post_process_params", params)
else:
## cache up to date, we don't have to run
write_message("Collection cache is up to date, no need to run.")
## we are done:
return True
### okay, here we go:
if __name__ == '__main__':
main()
| gpl-2.0 |
andrewyoung1991/supriya | supriya/tools/ugentools/Balance2.py | 1 | 5756 | # -*- encoding: utf-8 -*-
from supriya.tools.ugentools.MultiOutUGen import MultiOutUGen
class Balance2(MultiOutUGen):
r'''A stereo signal balancer.
::
>>> left = ugentools.WhiteNoise.ar()
>>> right = ugentools.SinOsc.ar()
>>> balance_2 = ugentools.Balance2.ar(
... left=left,
... level=1,
... position=0,
... right=right,
... )
>>> balance_2
UGenArray({2})
'''
### CLASS VARIABLES ###
__documentation_section__ = 'Spatialization UGens'
__slots__ = ()
_ordered_input_names = (
'left',
'right',
'position',
'level',
)
_valid_calculation_rates = None
### INITIALIZER ###
def __init__(
self,
calculation_rate=None,
left=None,
level=1,
position=0,
right=None,
):
MultiOutUGen.__init__(
self,
calculation_rate=calculation_rate,
channel_count=2,
left=left,
level=level,
position=position,
right=right,
)
### PUBLIC METHODS ###
@classmethod
def ar(
cls,
left=None,
level=1,
position=0,
right=None,
):
r'''Constructs an audio-rate Balance2.
::
>>> left = ugentools.WhiteNoise.ar()
>>> right = ugentools.SinOsc.ar()
>>> balance_2 = ugentools.Balance2.ar(
... left=left,
... level=1,
... position=0,
... right=right,
... )
>>> balance_2
UGenArray({2})
Returns ugen graph.
'''
from supriya.tools import synthdeftools
calculation_rate = synthdeftools.CalculationRate.AUDIO
ugen = cls._new_expanded(
calculation_rate=calculation_rate,
left=left,
level=level,
position=position,
right=right,
)
return ugen
@classmethod
def kr(
cls,
left=None,
level=1,
position=0,
right=None,
):
r'''Constructs a control-rate Balance2.
::
>>> left = ugentools.WhiteNoise.kr()
>>> right = ugentools.SinOsc.kr()
>>> balance_2 = ugentools.Balance2.kr(
... left=left,
... level=1,
... position=0,
... right=right,
... )
>>> balance_2
UGenArray({2})
Returns ugen graph.
'''
from supriya.tools import synthdeftools
calculation_rate = synthdeftools.CalculationRate.CONTROL
ugen = cls._new_expanded(
calculation_rate=calculation_rate,
left=left,
level=level,
position=position,
right=right,
)
return ugen
### PUBLIC PROPERTIES ###
@property
def left(self):
r'''Gets `left` input of Balance2.
::
>>> left = ugentools.WhiteNoise.ar()
>>> right = ugentools.SinOsc.ar()
>>> balance_2 = ugentools.Balance2.ar(
... left=left,
... level=1,
... position=0,
... right=right,
... )
>>> balance_2[0].source.left
OutputProxy(
source=WhiteNoise(
calculation_rate=CalculationRate.AUDIO
),
output_index=0
)
Returns ugen input.
'''
index = self._ordered_input_names.index('left')
return self._inputs[index]
@property
def level(self):
r'''Gets `level` input of Balance2.
::
>>> left = ugentools.WhiteNoise.ar()
>>> right = ugentools.SinOsc.ar()
>>> balance_2 = ugentools.Balance2.ar(
... left=left,
... level=1,
... position=0,
... right=right,
... )
>>> balance_2[0].source.level
1.0
Returns ugen input.
'''
index = self._ordered_input_names.index('level')
return self._inputs[index]
@property
def position(self):
r'''Gets `position` input of Balance2.
::
>>> left = ugentools.WhiteNoise.ar()
>>> right = ugentools.SinOsc.ar()
>>> balance_2 = ugentools.Balance2.ar(
... left=left,
... level=1,
... position=0.5,
... right=right,
... )
>>> balance_2[0].source.position
0.5
Returns ugen input.
'''
index = self._ordered_input_names.index('position')
return self._inputs[index]
@property
def right(self):
r'''Gets `right` input of Balance2.
::
>>> left = ugentools.WhiteNoise.ar()
>>> right = ugentools.SinOsc.ar()
>>> balance_2 = ugentools.Balance2.ar(
... left=left,
... level=1,
... position=0,
... right=right,
... )
>>> balance_2[0].source.right
OutputProxy(
source=SinOsc(
calculation_rate=CalculationRate.AUDIO,
frequency=440.0,
phase=0.0
),
output_index=0
)
Returns ugen input.
'''
index = self._ordered_input_names.index('right')
return self._inputs[index] | mit |
rafalo1333/kivy | kivy/modules/monitor.py | 23 | 2448 | '''
Monitor module
==============
The Monitor module is a toolbar that shows the activity of your current
application :
* FPS
* Graph of input events
Usage
-----
For normal module usage, please see the :mod:`~kivy.modules` documentation.
'''
__all__ = ('start', 'stop')
from kivy.uix.label import Label
from kivy.graphics import Rectangle, Color
from kivy.clock import Clock
from functools import partial
_statsinput = 0
_maxinput = -1
def update_fps(ctx, *largs):
ctx.label.text = 'FPS: %f' % Clock.get_fps()
ctx.rectangle.texture = ctx.label.texture
ctx.rectangle.size = ctx.label.texture_size
def update_stats(win, ctx, *largs):
global _statsinput
ctx.stats = ctx.stats[1:] + [_statsinput]
_statsinput = 0
m = max(1., _maxinput)
for i, x in enumerate(ctx.stats):
ctx.statsr[i].size = (4, ctx.stats[i] / m * 20)
ctx.statsr[i].pos = (win.width - 64 * 4 + i * 4, win.height - 25)
def _update_monitor_canvas(win, ctx, *largs):
with win.canvas.after:
ctx.overlay.pos = (0, win.height - 25)
ctx.overlay.size = (win.width, 25)
ctx.rectangle.pos = (5, win.height - 20)
class StatsInput(object):
def process(self, events):
global _statsinput, _maxinput
_statsinput += len(events)
if _statsinput > _maxinput:
_maxinput = float(_statsinput)
return events
def start(win, ctx):
# late import to avoid breaking module loading
from kivy.input.postproc import kivy_postproc_modules
kivy_postproc_modules['fps'] = StatsInput()
global _ctx
ctx.label = Label(text='FPS: 0.0')
ctx.inputstats = 0
ctx.stats = []
ctx.statsr = []
with win.canvas.after:
ctx.color = Color(1, 0, 0, .5)
ctx.overlay = Rectangle(pos=(0, win.height - 25),
size=(win.width, 25))
ctx.color = Color(1, 1, 1)
ctx.rectangle = Rectangle(pos=(5, win.height - 20))
ctx.color = Color(1, 1, 1, .5)
for i in range(64):
ctx.stats.append(0)
ctx.statsr.append(
Rectangle(pos=(win.width - 64 * 4 + i * 4, win.height - 25),
size=(4, 0)))
win.bind(size=partial(_update_monitor_canvas, win, ctx))
Clock.schedule_interval(partial(update_fps, ctx), .5)
Clock.schedule_interval(partial(update_stats, win, ctx), 1 / 60.)
def stop(win, ctx):
win.canvas.remove(ctx.label)
| mit |
jalanb/jab | src/python/update_hosts.py | 2 | 2813 | """A program to update /etc/hosts from our defintions"""
from __future__ import print_function
import os
import sys
def parse_line(line):
parts = line.split()
ip, names = parts[0], parts[1:]
return ip, names
def format_line(ip, names):
if names is None:
return str(ip)
names = sorted(list(names))
return '%-16s\t%s' % (ip, ' '.join(names))
def read_host_lines(path_to_hosts):
lines = []
for line in file(path_to_hosts, 'r'):
line = line.rstrip()
if not line or line[0] == '#':
parsed = (line, None)
else:
parts = line.split()
parsed = parts[0], set(parts[1:])
lines.append(parsed)
return lines
def path_to_etc_hosts():
return '/etc/hosts'
def path_to_jab_hosts():
jab = '~/jab'
return os.path.join(jab, 'etc/hosts')
def read_etc_hosts():
return read_host_lines(path_to_etc_hosts())
def read_my_hosts():
return read_host_lines(path_to_jab_hosts())
def _has_names(line):
_ip, names = line
return names is not None
def ip_dict(lines):
return dict([l for l in lines if _has_names(l)])
def merge_hosts(etc_hosts, my_hosts):
extras = ip_dict(my_hosts)
result = []
added_line = '# Added by %s' % os.path.basename(sys.argv[0])
has_added_line = False
for line in etc_hosts:
ip, names = line
new_line = format_line(ip, names)
if new_line == added_line:
has_added_line = True
else:
if has_added_line and not new_line:
has_added_line = False
if _has_names(line) and ip in extras:
extra_names = extras[ip]
if names.difference(extra_names):
new_line = format_line(ip, names.union(extra_names))
del extras[ip]
result.append(new_line)
extra_lines = []
for ip, names in extras.items():
extra_lines.append(format_line(ip, names))
if extra_lines and not has_added_line:
extra_lines.insert(0, '#')
extra_lines.insert(1, '# Added by %s' % sys.argv[0])
result.extend(extra_lines)
return result
def write_hosts(lines, path_to_hosts):
"""Write the given lines to the given hosts file
If that is not possible (usually permission denied for /etc/hosts)
then just write to stdout
"""
try:
output = file(path_to_hosts, 'w')
for line in lines:
print(line, file=output)
output.close()
return os.EX_OK
except IOError:
print('\n'.join(lines))
return os.EX_NOPERM
def main():
etc_hosts = read_etc_hosts()
my_hosts = read_my_hosts()
lines = merge_hosts(etc_hosts, my_hosts)
return write_hosts(lines, path_to_etc_hosts())
if __name__ == '__main__':
sys.exit(main())
| mit |
ic-labs/django-icekit | icekit/page_types/article/migrations/0001_initial.py | 1 | 2970 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('fluent_pages', '0001_initial'),
('icekit', '0006_auto_20150911_0744'),
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),
('publishing_is_draft', models.BooleanField(db_index=True, editable=False, default=True)),
('publishing_modified_at', models.DateTimeField(editable=False, default=django.utils.timezone.now)),
('publishing_published_at', models.DateTimeField(null=True, editable=False)),
('title', models.CharField(max_length=255)),
('slug', models.SlugField(max_length=255)),
('layout', models.ForeignKey(related_name='icekit_article_article_related', blank=True, null=True, to='icekit.Layout')),
],
),
migrations.CreateModel(
name='ArticleCategoryPage',
fields=[
('urlnode_ptr', models.OneToOneField(serialize=False, primary_key=True, auto_created=True, parent_link=True, to='fluent_pages.UrlNode')),
('publishing_is_draft', models.BooleanField(db_index=True, editable=False, default=True)),
('publishing_modified_at', models.DateTimeField(editable=False, default=django.utils.timezone.now)),
('publishing_published_at', models.DateTimeField(null=True, editable=False)),
('layout', models.ForeignKey(related_name='icekit_article_articlecategorypage_related', blank=True, null=True, to='icekit.Layout')),
('publishing_linked', models.OneToOneField(null=True, related_name='publishing_draft', on_delete=django.db.models.deletion.SET_NULL, editable=False, to='icekit_article.ArticleCategoryPage')),
],
options={
'db_table': 'pagetype_icekit_article_articlecategorypage',
'abstract': False,
},
bases=('fluent_pages.htmlpage', models.Model),
),
migrations.AddField(
model_name='article',
name='parent',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='icekit_article.ArticleCategoryPage'),
),
migrations.AddField(
model_name='article',
name='publishing_linked',
field=models.OneToOneField(null=True, related_name='publishing_draft', on_delete=django.db.models.deletion.SET_NULL, editable=False, to='icekit_article.Article'),
),
migrations.AlterUniqueTogether(
name='article',
unique_together=set([('slug', 'parent', 'publishing_linked')]),
),
]
| mit |
openstack-hyper-v-python/numpy | numpy/doc/ufuncs.py | 172 | 5427 | """
===================
Universal Functions
===================
Ufuncs are, generally speaking, mathematical functions or operations that are
applied element-by-element to the contents of an array. That is, the result
in each output array element only depends on the value in the corresponding
input array (or arrays) and on no other array elements. Numpy comes with a
large suite of ufuncs, and scipy extends that suite substantially. The simplest
example is the addition operator: ::
>>> np.array([0,2,3,4]) + np.array([1,1,-1,2])
array([1, 3, 2, 6])
The unfunc module lists all the available ufuncs in numpy. Documentation on
the specific ufuncs may be found in those modules. This documentation is
intended to address the more general aspects of unfuncs common to most of
them. All of the ufuncs that make use of Python operators (e.g., +, -, etc.)
have equivalent functions defined (e.g. add() for +)
Type coercion
=============
What happens when a binary operator (e.g., +,-,\\*,/, etc) deals with arrays of
two different types? What is the type of the result? Typically, the result is
the higher of the two types. For example: ::
float32 + float64 -> float64
int8 + int32 -> int32
int16 + float32 -> float32
float32 + complex64 -> complex64
There are some less obvious cases generally involving mixes of types
(e.g. uints, ints and floats) where equal bit sizes for each are not
capable of saving all the information in a different type of equivalent
bit size. Some examples are int32 vs float32 or uint32 vs int32.
Generally, the result is the higher type of larger size than both
(if available). So: ::
int32 + float32 -> float64
uint32 + int32 -> int64
Finally, the type coercion behavior when expressions involve Python
scalars is different than that seen for arrays. Since Python has a
limited number of types, combining a Python int with a dtype=np.int8
array does not coerce to the higher type but instead, the type of the
array prevails. So the rules for Python scalars combined with arrays is
that the result will be that of the array equivalent the Python scalar
if the Python scalar is of a higher 'kind' than the array (e.g., float
vs. int), otherwise the resultant type will be that of the array.
For example: ::
Python int + int8 -> int8
Python float + int8 -> float64
ufunc methods
=============
Binary ufuncs support 4 methods.
**.reduce(arr)** applies the binary operator to elements of the array in
sequence. For example: ::
>>> np.add.reduce(np.arange(10)) # adds all elements of array
45
For multidimensional arrays, the first dimension is reduced by default: ::
>>> np.add.reduce(np.arange(10).reshape(2,5))
array([ 5, 7, 9, 11, 13])
The axis keyword can be used to specify different axes to reduce: ::
>>> np.add.reduce(np.arange(10).reshape(2,5),axis=1)
array([10, 35])
**.accumulate(arr)** applies the binary operator and generates an an
equivalently shaped array that includes the accumulated amount for each
element of the array. A couple examples: ::
>>> np.add.accumulate(np.arange(10))
array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
>>> np.multiply.accumulate(np.arange(1,9))
array([ 1, 2, 6, 24, 120, 720, 5040, 40320])
The behavior for multidimensional arrays is the same as for .reduce(),
as is the use of the axis keyword).
**.reduceat(arr,indices)** allows one to apply reduce to selected parts
of an array. It is a difficult method to understand. See the documentation
at:
**.outer(arr1,arr2)** generates an outer operation on the two arrays arr1 and
arr2. It will work on multidimensional arrays (the shape of the result is
the concatenation of the two input shapes.: ::
>>> np.multiply.outer(np.arange(3),np.arange(4))
array([[0, 0, 0, 0],
[0, 1, 2, 3],
[0, 2, 4, 6]])
Output arguments
================
All ufuncs accept an optional output array. The array must be of the expected
output shape. Beware that if the type of the output array is of a different
(and lower) type than the output result, the results may be silently truncated
or otherwise corrupted in the downcast to the lower type. This usage is useful
when one wants to avoid creating large temporary arrays and instead allows one
to reuse the same array memory repeatedly (at the expense of not being able to
use more convenient operator notation in expressions). Note that when the
output argument is used, the ufunc still returns a reference to the result.
>>> x = np.arange(2)
>>> np.add(np.arange(2),np.arange(2.),x)
array([0, 2])
>>> x
array([0, 2])
and & or as ufuncs
==================
Invariably people try to use the python 'and' and 'or' as logical operators
(and quite understandably). But these operators do not behave as normal
operators since Python treats these quite differently. They cannot be
overloaded with array equivalents. Thus using 'and' or 'or' with an array
results in an error. There are two alternatives:
1) use the ufunc functions logical_and() and logical_or().
2) use the bitwise operators & and \\|. The drawback of these is that if
the arguments to these operators are not boolean arrays, the result is
likely incorrect. On the other hand, most usages of logical_and and
logical_or are with boolean arrays. As long as one is careful, this is
a convenient way to apply these operators.
"""
from __future__ import division, absolute_import, print_function
| bsd-3-clause |
lail3344/sms-tools | lectures/09-Sound-description/plots-code/hpcp.py | 25 | 1194 | import numpy as np
import matplotlib.pyplot as plt
import essentia.standard as ess
M = 1024
N = 1024
H = 512
fs = 44100
spectrum = ess.Spectrum(size=N)
window = ess.Windowing(size=M, type='hann')
spectralPeaks = ess.SpectralPeaks()
hpcp = ess.HPCP()
x = ess.MonoLoader(filename = '../../../sounds/cello-double.wav', sampleRate = fs)()
hpcps = []
for frame in ess.FrameGenerator(x, frameSize=M, hopSize=H, startFromZero=True):
mX = spectrum(window(frame))
spectralPeaks_freqs, spectralPeaks_mags = spectralPeaks(mX)
hpcp_vals = hpcp(spectralPeaks_freqs, spectralPeaks_mags)
hpcps.append(hpcp_vals)
hpcps = np.array(hpcps)
plt.figure(1, figsize=(9.5, 7))
plt.subplot(2,1,1)
plt.plot(np.arange(x.size)/float(fs), x, 'b')
plt.axis([0, x.size/float(fs), min(x), max(x)])
plt.ylabel('amplitude')
plt.title('x (cello-double.wav)')
plt.subplot(2,1,2)
numFrames = int(hpcps[:,0].size)
frmTime = H*np.arange(numFrames)/float(fs)
plt.pcolormesh(frmTime, np.arange(12), np.transpose(hpcps))
plt.ylabel('spectral bins')
plt.title('HPCP')
plt.autoscale(tight=True)
plt.tight_layout()
plt.savefig('hpcp.png')
plt.show()
| agpl-3.0 |
ksophocleous/grpc | src/python/grpcio_test/grpc_test/_adapter/_event_invocation_synchronous_event_service_test.py | 14 | 2001 | # Copyright 2015, 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.
"""One of the tests of the Face layer of RPC Framework."""
import unittest
from grpc_test._adapter import _face_test_case
from grpc_test.framework.face.testing import event_invocation_synchronous_event_service_test_case as test_case
class EventInvocationSynchronousEventServiceTest(
_face_test_case.FaceTestCase,
test_case.EventInvocationSynchronousEventServiceTestCase,
unittest.TestCase):
pass
if __name__ == '__main__':
unittest.main(verbosity=2)
| bsd-3-clause |
BT-fgarbely/odoo | addons/base_vat/base_vat.py | 238 | 14207 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2012 OpenERP SA (<http://openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
import string
import datetime
import re
_logger = logging.getLogger(__name__)
try:
import vatnumber
except ImportError:
_logger.warning("VAT validation partially unavailable because the `vatnumber` Python library cannot be found. "
"Install it to support more countries, for example with `easy_install vatnumber`.")
vatnumber = None
from openerp.osv import fields, osv
from openerp.tools.misc import ustr
from openerp.tools.translate import _
_ref_vat = {
'at': 'ATU12345675',
'be': 'BE0477472701',
'bg': 'BG1234567892',
'ch': 'CHE-123.456.788 TVA or CH TVA 123456', #Swiss by Yannick Vaucher @ Camptocamp
'cy': 'CY12345678F',
'cz': 'CZ12345679',
'de': 'DE123456788',
'dk': 'DK12345674',
'ee': 'EE123456780',
'el': 'EL12345670',
'es': 'ESA12345674',
'fi': 'FI12345671',
'fr': 'FR32123456789',
'gb': 'GB123456782',
'gr': 'GR12345670',
'hu': 'HU12345676',
'hr': 'HR01234567896', # Croatia, contributed by Milan Tribuson
'ie': 'IE1234567FA',
'it': 'IT12345670017',
'lt': 'LT123456715',
'lu': 'LU12345613',
'lv': 'LV41234567891',
'mt': 'MT12345634',
'mx': 'MXABC123456T1B',
'nl': 'NL123456782B90',
'no': 'NO123456785',
'pe': 'PER10254824220 or PED10254824220',
'pl': 'PL1234567883',
'pt': 'PT123456789',
'ro': 'RO1234567897',
'se': 'SE123456789701',
'si': 'SI12345679',
'sk': 'SK0012345675',
'tr': 'TR1234567890 (VERGINO) veya TR12345678901 (TCKIMLIKNO)' # Levent Karakas @ Eska Yazilim A.S.
}
class res_partner(osv.osv):
_inherit = 'res.partner'
def _split_vat(self, vat):
vat_country, vat_number = vat[:2].lower(), vat[2:].replace(' ', '')
return vat_country, vat_number
def simple_vat_check(self, cr, uid, country_code, vat_number, context=None):
'''
Check the VAT number depending of the country.
http://sima-pc.com/nif.php
'''
if not ustr(country_code).encode('utf-8').isalpha():
return False
check_func_name = 'check_vat_' + country_code
check_func = getattr(self, check_func_name, None) or \
getattr(vatnumber, check_func_name, None)
if not check_func:
# No VAT validation available, default to check that the country code exists
if country_code.upper() == 'EU':
# Foreign companies that trade with non-enterprises in the EU
# may have a VATIN starting with "EU" instead of a country code.
return True
res_country = self.pool.get('res.country')
return bool(res_country.search(cr, uid, [('code', '=ilike', country_code)], context=context))
return check_func(vat_number)
def vies_vat_check(self, cr, uid, country_code, vat_number, context=None):
try:
# Validate against VAT Information Exchange System (VIES)
# see also http://ec.europa.eu/taxation_customs/vies/
return vatnumber.check_vies(country_code.upper()+vat_number)
except Exception:
# see http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl
# Fault code may contain INVALID_INPUT, SERVICE_UNAVAILABLE, MS_UNAVAILABLE,
# TIMEOUT or SERVER_BUSY. There is no way we can validate the input
# with VIES if any of these arise, including the first one (it means invalid
# country code or empty VAT number), so we fall back to the simple check.
return self.simple_vat_check(cr, uid, country_code, vat_number, context=context)
def button_check_vat(self, cr, uid, ids, context=None):
if not self.check_vat(cr, uid, ids, context=context):
msg = self._construct_constraint_msg(cr, uid, ids, context=context)
raise osv.except_osv(_('Error!'), msg)
return True
def check_vat(self, cr, uid, ids, context=None):
user_company = self.pool.get('res.users').browse(cr, uid, uid).company_id
if user_company.vat_check_vies:
# force full VIES online check
check_func = self.vies_vat_check
else:
# quick and partial off-line checksum validation
check_func = self.simple_vat_check
for partner in self.browse(cr, uid, ids, context=context):
if not partner.vat:
continue
vat_country, vat_number = self._split_vat(partner.vat)
if not check_func(cr, uid, vat_country, vat_number, context=context):
_logger.info(_("Importing VAT Number [%s] is not valid !" % vat_number))
return False
return True
def vat_change(self, cr, uid, ids, value, context=None):
return {'value': {'vat_subjected': bool(value)}}
def _commercial_fields(self, cr, uid, context=None):
return super(res_partner, self)._commercial_fields(cr, uid, context=context) + ['vat_subjected']
def _construct_constraint_msg(self, cr, uid, ids, context=None):
def default_vat_check(cn, vn):
# by default, a VAT number is valid if:
# it starts with 2 letters
# has more than 3 characters
return cn[0] in string.ascii_lowercase and cn[1] in string.ascii_lowercase
vat_country, vat_number = self._split_vat(self.browse(cr, uid, ids)[0].vat)
vat_no = "'CC##' (CC=Country Code, ##=VAT Number)"
error_partner = self.browse(cr, uid, ids, context=context)
if default_vat_check(vat_country, vat_number):
vat_no = _ref_vat[vat_country] if vat_country in _ref_vat else vat_no
if self.pool['res.users'].browse(cr, uid, uid).company_id.vat_check_vies:
return '\n' + _('The VAT number [%s] for partner [%s] either failed the VIES VAT validation check or did not respect the expected format %s.') % (error_partner[0].vat, error_partner[0].name, vat_no)
return '\n' + _('The VAT number [%s] for partner [%s] does not seem to be valid. \nNote: the expected format is %s') % (error_partner[0].vat, error_partner[0].name, vat_no)
_constraints = [(check_vat, _construct_constraint_msg, ["vat"])]
__check_vat_ch_re1 = re.compile(r'(MWST|TVA|IVA)[0-9]{6}$')
__check_vat_ch_re2 = re.compile(r'E([0-9]{9}|-[0-9]{3}\.[0-9]{3}\.[0-9]{3})(MWST|TVA|IVA)$')
def check_vat_ch(self, vat):
'''
Check Switzerland VAT number.
'''
# VAT number in Switzerland will change between 2011 and 2013
# http://www.estv.admin.ch/mwst/themen/00154/00589/01107/index.html?lang=fr
# Old format is "TVA 123456" we will admit the user has to enter ch before the number
# Format will becomes such as "CHE-999.999.99C TVA"
# Both old and new format will be accepted till end of 2013
# Accepted format are: (spaces are ignored)
# CH TVA ######
# CH IVA ######
# CH MWST #######
#
# CHE#########MWST
# CHE#########TVA
# CHE#########IVA
# CHE-###.###.### MWST
# CHE-###.###.### TVA
# CHE-###.###.### IVA
#
if self.__check_vat_ch_re1.match(vat):
return True
match = self.__check_vat_ch_re2.match(vat)
if match:
# For new TVA numbers, do a mod11 check
num = filter(lambda s: s.isdigit(), match.group(1)) # get the digits only
factor = (5,4,3,2,7,6,5,4)
csum = sum([int(num[i]) * factor[i] for i in range(8)])
check = (11 - (csum % 11)) % 11
return check == int(num[8])
return False
def _ie_check_char(self, vat):
vat = vat.zfill(8)
extra = 0
if vat[7] not in ' W':
if vat[7].isalpha():
extra = 9 * (ord(vat[7]) - 64)
else:
# invalid
return -1
checksum = extra + sum((8-i) * int(x) for i, x in enumerate(vat[:7]))
return 'WABCDEFGHIJKLMNOPQRSTUV'[checksum % 23]
def check_vat_ie(self, vat):
""" Temporary Ireland VAT validation to support the new format
introduced in January 2013 in Ireland, until upstream is fixed.
TODO: remove when fixed upstream"""
if len(vat) not in (8, 9) or not vat[2:7].isdigit():
return False
if len(vat) == 8:
# Normalize pre-2013 numbers: final space or 'W' not significant
vat += ' '
if vat[:7].isdigit():
return vat[7] == self._ie_check_char(vat[:7] + vat[8])
elif vat[1] in (string.ascii_uppercase + '+*'):
# Deprecated format
# See http://www.revenue.ie/en/online/third-party-reporting/reporting-payment-details/faqs.html#section3
return vat[7] == self._ie_check_char(vat[2:7] + vat[0] + vat[8])
return False
# Mexican VAT verification, contributed by Vauxoo
# and Panos Christeas <p_christ@hol.gr>
__check_vat_mx_re = re.compile(r"(?P<primeras>[A-Za-z\xd1\xf1&]{3,4})" \
r"[ \-_]?" \
r"(?P<ano>[0-9]{2})(?P<mes>[01][0-9])(?P<dia>[0-3][0-9])" \
r"[ \-_]?" \
r"(?P<code>[A-Za-z0-9&\xd1\xf1]{3})$")
def check_vat_mx(self, vat):
''' Mexican VAT verification
Verificar RFC México
'''
# we convert to 8-bit encoding, to help the regex parse only bytes
vat = ustr(vat).encode('iso8859-1')
m = self.__check_vat_mx_re.match(vat)
if not m:
#No valid format
return False
try:
ano = int(m.group('ano'))
if ano > 30:
ano = 1900 + ano
else:
ano = 2000 + ano
datetime.date(ano, int(m.group('mes')), int(m.group('dia')))
except ValueError:
return False
#Valid format and valid date
return True
# Norway VAT validation, contributed by Rolv Råen (adEgo) <rora@adego.no>
def check_vat_no(self, vat):
'''
Check Norway VAT number.See http://www.brreg.no/english/coordination/number.html
'''
if len(vat) != 9:
return False
try:
int(vat)
except ValueError:
return False
sum = (3 * int(vat[0])) + (2 * int(vat[1])) + \
(7 * int(vat[2])) + (6 * int(vat[3])) + \
(5 * int(vat[4])) + (4 * int(vat[5])) + \
(3 * int(vat[6])) + (2 * int(vat[7]))
check = 11 -(sum % 11)
if check == 11:
check = 0
if check == 10:
# 10 is not a valid check digit for an organization number
return False
return check == int(vat[8])
# Peruvian VAT validation, contributed by Vauxoo
def check_vat_pe(self, vat):
vat_type,vat = vat and len(vat)>=2 and (vat[0], vat[1:]) or (False, False)
if vat_type and vat_type.upper() == 'D':
#DNI
return True
elif vat_type and vat_type.upper() == 'R':
#verify RUC
factor = '5432765432'
sum = 0
dig_check = False
if len(vat) != 11:
return False
try:
int(vat)
except ValueError:
return False
for f in range(0,10):
sum += int(factor[f]) * int(vat[f])
subtraction = 11 - (sum % 11)
if subtraction == 10:
dig_check = 0
elif subtraction == 11:
dig_check = 1
else:
dig_check = subtraction
return int(vat[10]) == dig_check
else:
return False
# VAT validation in Turkey, contributed by # Levent Karakas @ Eska Yazilim A.S.
def check_vat_tr(self, vat):
if not (10 <= len(vat) <= 11):
return False
try:
int(vat)
except ValueError:
return False
# check vat number (vergi no)
if len(vat) == 10:
sum = 0
check = 0
for f in range(0,9):
c1 = (int(vat[f]) + (9-f)) % 10
c2 = ( c1 * (2 ** (9-f)) ) % 9
if (c1 != 0) and (c2 == 0): c2 = 9
sum += c2
if sum % 10 == 0:
check = 0
else:
check = 10 - (sum % 10)
return int(vat[9]) == check
# check personal id (tc kimlik no)
if len(vat) == 11:
c1a = 0
c1b = 0
c2 = 0
for f in range(0,9,2):
c1a += int(vat[f])
for f in range(1,9,2):
c1b += int(vat[f])
c1 = ( (7 * c1a) - c1b) % 10
for f in range(0,10):
c2 += int(vat[f])
c2 = c2 % 10
return int(vat[9]) == c1 and int(vat[10]) == c2
return False
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
orekyuu/intellij-community | python/lib/Lib/site-packages/django/contrib/gis/db/backends/mysql/operations.py | 312 | 2418 | from django.db.backends.mysql.base import DatabaseOperations
from django.contrib.gis.db.backends.adapter import WKTAdapter
from django.contrib.gis.db.backends.base import BaseSpatialOperations
class MySQLOperations(DatabaseOperations, BaseSpatialOperations):
compiler_module = 'django.contrib.gis.db.models.sql.compiler'
mysql = True
name = 'mysql'
select = 'AsText(%s)'
from_wkb = 'GeomFromWKB'
from_text = 'GeomFromText'
Adapter = WKTAdapter
Adaptor = Adapter # Backwards-compatibility alias.
geometry_functions = {
'bbcontains' : 'MBRContains', # For consistency w/PostGIS API
'bboverlaps' : 'MBROverlaps', # .. ..
'contained' : 'MBRWithin', # .. ..
'contains' : 'MBRContains',
'disjoint' : 'MBRDisjoint',
'equals' : 'MBREqual',
'exact' : 'MBREqual',
'intersects' : 'MBRIntersects',
'overlaps' : 'MBROverlaps',
'same_as' : 'MBREqual',
'touches' : 'MBRTouches',
'within' : 'MBRWithin',
}
gis_terms = dict([(term, None) for term in geometry_functions.keys() + ['isnull']])
def geo_db_type(self, f):
return f.geom_type
def get_geom_placeholder(self, value, srid):
"""
The placeholder here has to include MySQL's WKT constructor. Because
MySQL does not support spatial transformations, there is no need to
modify the placeholder based on the contents of the given value.
"""
if hasattr(value, 'expression'):
placeholder = '%s.%s' % tuple(map(self.quote_name, value.cols[value.expression]))
else:
placeholder = '%s(%%s)' % self.from_text
return placeholder
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
alias, col, db_type = lvalue
geo_col = '%s.%s' % (qn(alias), qn(col))
lookup_info = self.geometry_functions.get(lookup_type, False)
if lookup_info:
return "%s(%s, %s)" % (lookup_info, geo_col,
self.get_geom_placeholder(value, field.srid))
# TODO: Is this really necessary? MySQL can't handle NULL geometries
# in its spatial indexes anyways.
if lookup_type == 'isnull':
return "%s IS %sNULL" % (geo_col, (not value and 'NOT ' or ''))
raise TypeError("Got invalid lookup_type: %s" % repr(lookup_type))
| apache-2.0 |
nunogt/docker-registry | depends/docker-registry-core/docker_registry/testing/mock_dict.py | 38 | 1431 | # -*- coding: utf-8 -*-
# Copyright (c) 2014 Docker.
#
# 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.
'''Extend Mock class with dictionary behavior.
Call it as:
mocked_dict = MockDict()
mocked_dict.add_dict_methods()'''
import mock
MagicMock__init__ = mock.MagicMock.__init__
class MockDict(mock.MagicMock):
def __init__(self, *args, **kwargs):
MagicMock__init__(self, *args, **kwargs)
self._mock_dict = {}
@property
def get_dict(self):
return self._mock_dict
def add_dict_methods(self):
def setitem(key, value):
self._mock_dict[key] = value
def delitem(key):
del self._mock_dict[key]
self.__getitem__.side_effect = lambda key: self._mock_dict[key]
self.__setitem__.side_effect = setitem
self.__delitem__.side_effect = delitem
self.__contains__.side_effect = lambda key: key in self._mock_dict
| apache-2.0 |
lummyare/lummyare-lummy | py/test/selenium/webdriver/common/webserver.py | 9 | 4258 | # Copyright 2008-2009 WebDriver committers
# Copyright 2008-2009 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.
"""A simple web server for testing purpose.
It serves the testing html pages that are needed by the webdriver unit tests."""
import logging
import os
import socket
import threading
from io import open
try:
from urllib import request as urllib_request
except ImportError:
import urllib as urllib_request
try:
from http.server import BaseHTTPRequestHandler, HTTPServer
except ImportError:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
def updir():
dirname = os.path.dirname
return dirname(dirname(__file__))
LOGGER = logging.getLogger(__name__)
WEBDRIVER = os.environ.get("WEBDRIVER", updir())
HTML_ROOT = os.path.join(WEBDRIVER, "../../../../../../common/src/web")
if not os.path.isdir(HTML_ROOT):
message = ("Can't find 'common_web' directory, try setting WEBDRIVER"
" environment variable WEBDRIVER:" + WEBDRIVER + " HTML_ROOT:" + HTML_ROOT )
LOGGER.error(message)
assert 0, message
DEFAULT_PORT = 8000
class HtmlOnlyHandler(BaseHTTPRequestHandler):
"""Http handler."""
def do_GET(self):
"""GET method handler."""
try:
path = self.path[1:].split('?')[0]
html = open(os.path.join(HTML_ROOT, path), 'r', encoding='latin-1')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(html.read().encode('utf-8'))
html.close()
except IOError:
self.send_error(404, 'File Not Found: %s' % path)
def log_message(self, format, *args):
"""Override default to avoid trashing stderr"""
pass
class SimpleWebServer(object):
"""A very basic web server."""
def __init__(self, port=DEFAULT_PORT):
self.stop_serving = False
port = port
while True:
try:
self.server = HTTPServer(
('', port), HtmlOnlyHandler)
self.port = port
break
except socket.error:
LOGGER.debug("port %d is in use, trying to next one"
% port)
port += 1
self.thread = threading.Thread(target=self._run_web_server)
def _run_web_server(self):
"""Runs the server loop."""
LOGGER.debug("web server started")
while not self.stop_serving:
self.server.handle_request()
self.server.server_close()
def start(self):
"""Starts the server."""
self.thread.start()
def stop(self):
"""Stops the server."""
self.stop_serving = True
try:
# This is to force stop the server loop
urllib_request.URLopener().open("http://localhost:%d" % self.port)
except IOError:
pass
LOGGER.info("Shutting down the webserver")
self.thread.join()
def main(argv=None):
from optparse import OptionParser
from time import sleep
if argv is None:
import sys
argv = sys.argv
parser = OptionParser("%prog [options]")
parser.add_option("-p", "--port", dest="port", type="int",
help="port to listen (default: %s)" % DEFAULT_PORT,
default=DEFAULT_PORT)
opts, args = parser.parse_args(argv[1:])
if args:
parser.error("wrong number of arguments") # Will exit
server = SimpleWebServer(opts.port)
server.start()
print("Server started on port %s, hit CTRL-C to quit" % opts.port)
try:
while 1:
sleep(0.1)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
| apache-2.0 |
40023256/2015cdag1man | man5.py | 14 | 11239 |
import cherrypy
# 這是 MAN 類別的定義
'''
# 在 application 中導入子模組
import programs.cdag30.man as cdag30_man
# 加入 cdag30 模組下的 man.py 且以子模組 man 對應其 MAN() 類別
root.cdag30.man = cdag30_man.MAN()
# 完成設定後, 可以利用
/cdag30/man/assembly
# 呼叫 man.py 中 MAN 類別的 assembly 方法
'''
class MAN(object):
# 各組利用 index 引導隨後的程式執行
@cherrypy.expose
def index(self, *args, **kwargs):
outstring = '''
這是 2014CDA 協同專案下的 cdag30 模組下的 MAN 類別.<br /><br />
<!-- 這裡採用相對連結, 而非網址的絕對連結 (這一段為 html 註解) -->
<a href="assembly">執行 MAN 類別中的 assembly 方法</a><br /><br />
請確定下列零件於 V:/home/lego/man 目錄中, 且開啟空白 Creo 組立檔案.<br />
<a href="/static/lego_man.7z">lego_man.7z</a>(滑鼠右鍵存成 .7z 檔案)<br />
'''
return outstring
@cherrypy.expose
def assembly(self, *args, **kwargs):
outstring = '''
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<script type="text/javascript" src="/static/weblink/pfcUtils.js"></script>
<script type="text/javascript" src="/static/weblink/wl_header.js"></script>
</head>
<body>
</script><script language="JavaScript">
/*man2.py 完全利用函式呼叫進行組立*/
/*設計一個零件組立函式*/
// featID 為組立件第一個組立零件的編號
// inc 則為 part1 的組立順序編號, 第一個入組立檔編號為 featID+0
// part2 為外加的零件名稱
////////////////////////////////////////////////
// axis_plane_assembly 組立函式
////////////////////////////////////////////////
function axis_plane_assembly(session, assembly, transf, featID, inc, part2, axis1, plane1, axis2, plane2){
var descr = pfcCreate("pfcModelDescriptor").CreateFromFileName ("v:/home/lego/man/"+part2);
var componentModel = session.GetModelFromDescr(descr);
var componentModel = session.RetrieveModel(descr);
if (componentModel != void null)
{
var asmcomp = assembly.AssembleComponent (componentModel, transf);
}
var ids = pfcCreate("intseq");
ids.Append(featID+inc);
var subPath = pfcCreate("MpfcAssembly").CreateComponentPath(assembly, ids);
subassembly = subPath.Leaf;
var asmDatums = new Array(axis1, plane1);
var compDatums = new Array(axis2, plane2);
var relation = new Array (pfcCreate("pfcComponentConstraintType").ASM_CONSTRAINT_ALIGN, pfcCreate("pfcComponentConstraintType").ASM_CONSTRAINT_MATE);
var relationItem = new Array(pfcCreate("pfcModelItemType").ITEM_AXIS, pfcCreate("pfcModelItemType").ITEM_SURFACE);
var constrs = pfcCreate("pfcComponentConstraints");
for (var i = 0; i < 2; i++)
{
var asmItem = subassembly.GetItemByName (relationItem[i], asmDatums [i]);
if (asmItem == void null)
{
interactFlag = true;
continue;
}
var compItem = componentModel.GetItemByName (relationItem[i], compDatums [i]);
if (compItem == void null)
{
interactFlag = true;
continue;
}
var MpfcSelect = pfcCreate ("MpfcSelect");
var asmSel = MpfcSelect.CreateModelItemSelection (asmItem, subPath);
var compSel = MpfcSelect.CreateModelItemSelection (compItem, void null);
var constr = pfcCreate("pfcComponentConstraint").Create (relation[i]);
constr.AssemblyReference = asmSel;
constr.ComponentReference = compSel;
constr.Attributes = pfcCreate("pfcConstraintAttributes").Create (true, false);
constrs.Append(constr);
}
asmcomp.SetConstraints(constrs, void null);
}
// 以上為 axis_plane_assembly() 函式
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// three_plane_assembly 採 align 組立, 若 featID 為 0 表示為空組立檔案
///////////////////////////////////////////////////////////////////////////////////////////////////////////
function three_plane_assembly(session, assembly, transf, featID, inc, part2, plane1, plane2, plane3, plane4, plane5, plane6){
var descr = pfcCreate("pfcModelDescriptor").CreateFromFileName ("v:/home/lego/man/"+part2);
var componentModel = session.GetModelFromDescr(descr);
var componentModel = session.RetrieveModel(descr);
if (componentModel != void null)
{
var asmcomp = assembly.AssembleComponent (componentModel, transf);
}
var ids = pfcCreate("intseq");
// 若 featID 為 0 表示為空組立檔案
if (featID != 0){
ids.Append(featID+inc);
var subPath = pfcCreate("MpfcAssembly").CreateComponentPath(assembly, ids);
subassembly = subPath.Leaf;
}else{
var subPath = pfcCreate("MpfcAssembly").CreateComponentPath(assembly, ids);
subassembly = assembly;
// 設法取得第一個組立零件 first_featID
// 取得 assembly 項下的元件 id, 因為只有一個零件, 採用 index 0 取出其 featID
var components = assembly.ListFeaturesByType(true, pfcCreate ("pfcFeatureType").FEATTYPE_COMPONENT);
// 此一 featID 為組立件中的第一個零件編號, 也就是樂高人偶的 body
var first_featID = components.Item(0).Id;
}
var constrs = pfcCreate("pfcComponentConstraints");
var asmDatums = new Array(plane1, plane2, plane3);
var compDatums = new Array(plane4, plane5, plane6);
var MpfcSelect = pfcCreate("MpfcSelect");
for (var i = 0; i < 3; i++)
{
var asmItem = subassembly.GetItemByName(pfcCreate("pfcModelItemType").ITEM_SURFACE, asmDatums[i]);
if (asmItem == void null)
{
interactFlag = true;
continue;
}
var compItem = componentModel.GetItemByName(pfcCreate("pfcModelItemType").ITEM_SURFACE, compDatums[i]);
if (compItem == void null)
{
interactFlag = true;
continue;
}
var asmSel = MpfcSelect.CreateModelItemSelection(asmItem, subPath);
var compSel = MpfcSelect.CreateModelItemSelection(compItem, void null);
var constr = pfcCreate("pfcComponentConstraint").Create(pfcCreate("pfcComponentConstraintType").ASM_CONSTRAINT_ALIGN);
constr.AssemblyReference = asmSel;
constr.ComponentReference = compSel;
constr.Attributes = pfcCreate("pfcConstraintAttributes").Create (false, false);
constrs.Append(constr);
}
asmcomp.SetConstraints(constrs, void null);
// 若 featID = 0 則傳回 first_featID
if (featID == 0)
return first_featID;
}
// 以上為 three_plane_assembly() 函式
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// three_plane_assembly2 採 mate 組立, 若 featID 為 0 表示為空組立檔案
///////////////////////////////////////////////////////////////////////////////////////////////////////////
function three_plane_assembly2(session, assembly, transf, featID, inc, part2, plane1, plane2, plane3, plane4, plane5, plane6){
var descr = pfcCreate("pfcModelDescriptor").CreateFromFileName ("v:/home/lego/man/"+part2);
var componentModel = session.GetModelFromDescr(descr);
var componentModel = session.RetrieveModel(descr);
if (componentModel != void null)
{
var asmcomp = assembly.AssembleComponent (componentModel, transf);
}
var ids = pfcCreate("intseq");
// 若 featID 為 0 表示為空組立檔案
if (featID != 0){
ids.Append(featID+inc);
var subPath = pfcCreate("MpfcAssembly").CreateComponentPath(assembly, ids);
subassembly = subPath.Leaf;
}else{
var subPath = pfcCreate("MpfcAssembly").CreateComponentPath(assembly, ids);
subassembly = assembly;
// 設法取得第一個組立零件 first_featID
// 取得 assembly 項下的元件 id, 因為只有一個零件, 採用 index 0 取出其 featID
var components = assembly.ListFeaturesByType(true, pfcCreate ("pfcFeatureType").FEATTYPE_COMPONENT);
// 此一 featID 為組立件中的第一個零件編號, 也就是樂高人偶的 body
var first_featID = components.Item(0).Id;
}
var constrs = pfcCreate("pfcComponentConstraints");
var asmDatums = new Array(plane1, plane2, plane3);
var compDatums = new Array(plane4, plane5, plane6);
var MpfcSelect = pfcCreate("MpfcSelect");
for (var i = 0; i < 3; i++)
{
var asmItem = subassembly.GetItemByName(pfcCreate("pfcModelItemType").ITEM_SURFACE, asmDatums[i]);
if (asmItem == void null)
{
interactFlag = true;
continue;
}
var compItem = componentModel.GetItemByName(pfcCreate("pfcModelItemType").ITEM_SURFACE, compDatums[i]);
if (compItem == void null)
{
interactFlag = true;
continue;
}
var asmSel = MpfcSelect.CreateModelItemSelection(asmItem, subPath);
var compSel = MpfcSelect.CreateModelItemSelection(compItem, void null);
var constr = pfcCreate("pfcComponentConstraint").Create(pfcCreate("pfcComponentConstraintType").ASM_CONSTRAINT_MATE);
constr.AssemblyReference = asmSel;
constr.ComponentReference = compSel;
constr.Attributes = pfcCreate("pfcConstraintAttributes").Create (false, false);
constrs.Append(constr);
}
asmcomp.SetConstraints(constrs, void null);
// 若 featID = 0 則傳回 first_featID
if (featID == 0)
return first_featID;
}
// 以上為 three_plane_assembly2() 函式, 主要採三面 MATE 組立
//
// 假如 Creo 所在的操作系統不是 Windows 環境
if (!pfcIsWindows())
// 則啟動對應的 UniversalXPConnect 執行權限 (等同 Windows 下的 ActiveX)
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
// pfcGetProESession() 是位於 pfcUtils.js 中的函式, 確定此 JavaScript 是在嵌入式瀏覽器中執行
var session = pfcGetProESession();
// 設定 config option, 不要使用元件組立流程中內建的假設約束條件
session.SetConfigOption("comp_placement_assumptions","no");
// 建立擺放零件的位置矩陣, Pro/Web.Link 中的變數無法直接建立, 必須透過 pfcCreate() 建立
var identityMatrix = pfcCreate("pfcMatrix3D");
// 建立 identity 位置矩陣
for (var x = 0; x < 4; x++)
for (var y = 0; y < 4; y++)
{
if (x == y)
identityMatrix.Set(x, y, 1.0);
else
identityMatrix.Set(x, y, 0.0);
}
// 利用 identityMatrix 建立 transf 座標轉換矩陣
var transf = pfcCreate("pfcTransform3D").Create(identityMatrix);
// 取得目前的工作目錄
var currentDir = session.getCurrentDirectory();
// 以目前已開檔的空白組立檔案, 作為 model
var model = session.CurrentModel;
// 查驗有無 model, 或 model 類別是否為組立件, 若不符合條件則丟出錯誤訊息
if (model == void null || model.Type != pfcCreate("pfcModelType").MDL_ASSEMBLY)
throw new Error (0, "Current model is not an assembly.");
// 將此模型設為組立物件
var assembly = model;
/////////////////////////////////////////////////////////////////
// 開始執行組立, 全部採函式呼叫組立
/////////////////////////////////////////////////////////////////
// 紅帽
axis_plane_assembly(session, assembly, transf, 40,8,
"LEGO_HAT.prt", "A_2", "TOP", "A_2", "FRONT");
// regenerate 並且 repaint 組立檔案
assembly.Regenerate (void null);
session.GetModelWindow (assembly).Repaint();
</script>
</body>
</html>
'''
return outstring | gpl-3.0 |
FedoraScientific/salome-paravis | test/VisuPrs/DeformedShape/B2.py | 1 | 1529 | # Copyright (C) 2010-2014 CEA/DEN, EDF R&D
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
#
# This case corresponds to: /visu/DeformedShape/B2 case
# Create Deformed Shape for all data of the given MED file
import sys
from paravistest import datadir, pictureext, get_picture_dir
from presentations import CreatePrsForFile, PrsTypeEnum
import pvserver as paravis
# Create presentations
myParavis = paravis.myParavis
# Directory for saving snapshots
picturedir = get_picture_dir("DeformedShape/B2")
file = datadir + "cube_hexa8_quad4.med"
print " --------------------------------- "
print "file ", file
print " --------------------------------- "
print "CreatePrsForFile..."
CreatePrsForFile(myParavis, file, [PrsTypeEnum.DEFORMEDSHAPE], picturedir, pictureext)
| lgpl-2.1 |
dims/heat | heat/api/openstack/v1/software_configs.py | 3 | 3809 | #
# 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 six
from webob import exc
from heat.api.openstack.v1 import util
from heat.common import param_utils
from heat.common import serializers
from heat.common import wsgi
from heat.rpc import api as rpc_api
from heat.rpc import client as rpc_client
class SoftwareConfigController(object):
"""WSGI controller for Software config in Heat v1 API.
Implements the API actions.
"""
REQUEST_SCOPE = 'software_configs'
def __init__(self, options):
self.options = options
self.rpc_client = rpc_client.EngineClient()
def default(self, req, **args):
raise exc.HTTPNotFound()
def _extract_bool_param(self, name, value):
try:
return param_utils.extract_bool(name, value)
except ValueError as e:
raise exc.HTTPBadRequest(six.text_type(e))
def _index(self, req, tenant_safe=True):
whitelist = {
'limit': util.PARAM_TYPE_SINGLE,
'marker': util.PARAM_TYPE_SINGLE
}
params = util.get_allowed_params(req.params, whitelist)
scs = self.rpc_client.list_software_configs(req.context,
tenant_safe=tenant_safe,
**params)
return {'software_configs': scs}
@util.policy_enforce
def global_index(self, req):
return self._index(req, tenant_safe=False)
@util.policy_enforce
def index(self, req):
"""Lists summary information for all software configs."""
global_tenant = False
name = rpc_api.PARAM_GLOBAL_TENANT
if name in req.params:
global_tenant = self._extract_bool_param(
name,
req.params.get(name))
if global_tenant:
return self.global_index(req, req.context.tenant_id)
return self._index(req)
@util.policy_enforce
def show(self, req, config_id):
"""Gets detailed information for a software config."""
sc = self.rpc_client.show_software_config(
req.context, config_id)
return {'software_config': sc}
@util.policy_enforce
def create(self, req, body):
"""Create a new software config."""
create_data = {
'name': body.get('name'),
'group': body.get('group'),
'config': body.get('config'),
'inputs': body.get('inputs'),
'outputs': body.get('outputs'),
'options': body.get('options'),
}
sc = self.rpc_client.create_software_config(
req.context, **create_data)
return {'software_config': sc}
@util.policy_enforce
def delete(self, req, config_id):
"""Delete an existing software config."""
res = self.rpc_client.delete_software_config(req.context, config_id)
if res is not None:
raise exc.HTTPBadRequest(res['Error'])
raise exc.HTTPNoContent()
def create_resource(options):
"""Software configs resource factory method."""
deserializer = wsgi.JSONRequestDeserializer()
serializer = serializers.JSONResponseSerializer()
return wsgi.Resource(
SoftwareConfigController(options), deserializer, serializer)
| apache-2.0 |
EmadMokhtar/Django | tests/auth_tests/test_migrations.py | 14 | 7833 | from importlib import import_module
from django.apps import apps
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from django.test import TestCase
from .models import Proxy, UserProxy
update_proxy_permissions = import_module('django.contrib.auth.migrations.0011_update_proxy_permissions')
class ProxyModelWithDifferentAppLabelTests(TestCase):
available_apps = [
'auth_tests',
'django.contrib.auth',
'django.contrib.contenttypes',
]
def setUp(self):
"""
Create proxy permissions with content_type to the concrete model
rather than the proxy model (as they were before Django 2.2 and
migration 11).
"""
Permission.objects.all().delete()
self.concrete_content_type = ContentType.objects.get_for_model(UserProxy)
self.default_permission = Permission.objects.create(
content_type=self.concrete_content_type,
codename='add_userproxy',
name='Can add userproxy',
)
self.custom_permission = Permission.objects.create(
content_type=self.concrete_content_type,
codename='use_different_app_label',
name='May use a different app label',
)
def test_proxy_model_permissions_contenttype(self):
proxy_model_content_type = ContentType.objects.get_for_model(UserProxy, for_concrete_model=False)
self.assertEqual(self.default_permission.content_type, self.concrete_content_type)
self.assertEqual(self.custom_permission.content_type, self.concrete_content_type)
update_proxy_permissions.update_proxy_model_permissions(apps, None)
self.default_permission.refresh_from_db()
self.assertEqual(self.default_permission.content_type, proxy_model_content_type)
self.custom_permission.refresh_from_db()
self.assertEqual(self.custom_permission.content_type, proxy_model_content_type)
def test_user_has_now_proxy_model_permissions(self):
user = User.objects.create()
user.user_permissions.add(self.default_permission)
user.user_permissions.add(self.custom_permission)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm('auth.' + permission.codename))
self.assertFalse(user.has_perm('auth_tests.' + permission.codename))
update_proxy_permissions.update_proxy_model_permissions(apps, None)
# Reload user to purge the _perm_cache.
user = User._default_manager.get(pk=user.pk)
for permission in [self.default_permission, self.custom_permission]:
self.assertFalse(user.has_perm('auth.' + permission.codename))
self.assertTrue(user.has_perm('auth_tests.' + permission.codename))
def test_migrate_backwards(self):
update_proxy_permissions.update_proxy_model_permissions(apps, None)
update_proxy_permissions.revert_proxy_model_permissions(apps, None)
self.default_permission.refresh_from_db()
self.assertEqual(self.default_permission.content_type, self.concrete_content_type)
self.custom_permission.refresh_from_db()
self.assertEqual(self.custom_permission.content_type, self.concrete_content_type)
def test_user_keeps_same_permissions_after_migrating_backward(self):
user = User.objects.create()
user.user_permissions.add(self.default_permission)
user.user_permissions.add(self.custom_permission)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm('auth.' + permission.codename))
self.assertFalse(user.has_perm('auth_tests.' + permission.codename))
update_proxy_permissions.update_proxy_model_permissions(apps, None)
update_proxy_permissions.revert_proxy_model_permissions(apps, None)
# Reload user to purge the _perm_cache.
user = User._default_manager.get(pk=user.pk)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm('auth.' + permission.codename))
self.assertFalse(user.has_perm('auth_tests.' + permission.codename))
class ProxyModelWithSameAppLabelTests(TestCase):
available_apps = [
'auth_tests',
'django.contrib.auth',
'django.contrib.contenttypes',
]
def setUp(self):
"""
Create proxy permissions with content_type to the concrete model
rather than the proxy model (as they were before Django 2.2 and
migration 11).
"""
Permission.objects.all().delete()
self.concrete_content_type = ContentType.objects.get_for_model(Proxy)
self.default_permission = Permission.objects.create(
content_type=self.concrete_content_type,
codename='add_proxy',
name='Can add proxy',
)
self.custom_permission = Permission.objects.create(
content_type=self.concrete_content_type,
codename='display_proxys',
name='May display proxys information',
)
def test_proxy_model_permissions_contenttype(self):
proxy_model_content_type = ContentType.objects.get_for_model(Proxy, for_concrete_model=False)
self.assertEqual(self.default_permission.content_type, self.concrete_content_type)
self.assertEqual(self.custom_permission.content_type, self.concrete_content_type)
update_proxy_permissions.update_proxy_model_permissions(apps, None)
self.default_permission.refresh_from_db()
self.custom_permission.refresh_from_db()
self.assertEqual(self.default_permission.content_type, proxy_model_content_type)
self.assertEqual(self.custom_permission.content_type, proxy_model_content_type)
def test_user_still_has_proxy_model_permissions(self):
user = User.objects.create()
user.user_permissions.add(self.default_permission)
user.user_permissions.add(self.custom_permission)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm('auth_tests.' + permission.codename))
update_proxy_permissions.update_proxy_model_permissions(apps, None)
# Reload user to purge the _perm_cache.
user = User._default_manager.get(pk=user.pk)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm('auth_tests.' + permission.codename))
def test_migrate_backwards(self):
update_proxy_permissions.update_proxy_model_permissions(apps, None)
update_proxy_permissions.revert_proxy_model_permissions(apps, None)
self.default_permission.refresh_from_db()
self.assertEqual(self.default_permission.content_type, self.concrete_content_type)
self.custom_permission.refresh_from_db()
self.assertEqual(self.custom_permission.content_type, self.concrete_content_type)
def test_user_keeps_same_permissions_after_migrating_backward(self):
user = User.objects.create()
user.user_permissions.add(self.default_permission)
user.user_permissions.add(self.custom_permission)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm('auth_tests.' + permission.codename))
update_proxy_permissions.update_proxy_model_permissions(apps, None)
update_proxy_permissions.revert_proxy_model_permissions(apps, None)
# Reload user to purge the _perm_cache.
user = User._default_manager.get(pk=user.pk)
for permission in [self.default_permission, self.custom_permission]:
self.assertTrue(user.has_perm('auth_tests.' + permission.codename))
| mit |
kuc2477/news | tests/models/test_sqlalchemy_models.py | 1 | 1375 | from celery.states import ALL_STATES
def test_abstract_model_implementations(sa_session, sa_schedule, sa_child_news):
assert(isinstance(sa_schedule.id, int))
assert(isinstance(sa_child_news.id, int))
def test_abstract_schedule_implementation(
sa_scheduler, sa_session, sa_owner_model, sa_schedule):
assert(isinstance(sa_schedule.owner, sa_owner_model))
assert(isinstance(sa_schedule.url, str))
assert(isinstance(sa_schedule.cycle, int))
assert(isinstance(sa_schedule.options, dict))
assert(sa_schedule.get_state(sa_scheduler.celery) in ALL_STATES)
def test_abstract_news_implementation(
sa_session, sa_schedule, sa_root_news, sa_child_news):
assert(isinstance(sa_child_news.url, str))
assert(isinstance(sa_child_news.content, str))
assert(isinstance(sa_child_news.title, str))
assert(isinstance(sa_child_news.image, str) or sa_child_news.image is None)
assert(isinstance(sa_child_news.summary, str) or
sa_child_news.summary is None)
assert(sa_root_news.schedule == sa_schedule)
assert(sa_root_news.parent is None)
assert(sa_root_news.root == sa_root_news)
assert(sa_root_news.distance == 0)
assert(sa_child_news.schedule == sa_schedule)
assert(sa_child_news.parent == sa_root_news)
assert(sa_child_news.root == sa_root_news)
assert(sa_child_news.distance == 1)
| mit |
silence-star/android_kernel_nubia_NX503A | tools/perf/scripts/python/syscall-counts.py | 11181 | 1522 | # system call counts
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Displays system-wide system call totals, broken down by syscall.
# If a [comm] arg is specified, only syscalls called by [comm] are displayed.
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 syscall_name
usage = "perf script -s syscall-counts.py [comm]\n";
for_comm = None
if len(sys.argv) > 2:
sys.exit(usage)
if len(sys.argv) > 1:
for_comm = sys.argv[1]
syscalls = autodict()
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
print_syscall_totals()
def raw_syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, args):
if for_comm is not None:
if common_comm != for_comm:
return
try:
syscalls[id] += 1
except TypeError:
syscalls[id] = 1
def print_syscall_totals():
if for_comm is not None:
print "\nsyscall events for %s:\n\n" % (for_comm),
else:
print "\nsyscall events:\n\n",
print "%-40s %10s\n" % ("event", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"-----------"),
for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \
reverse = True):
print "%-40s %10d\n" % (syscall_name(id), val),
| gpl-2.0 |
dm-wyncode/zipped-code | content/posts/python-mongodb/sanity_checking_data_and_creating_new_collections.py | 1 | 10486 |
# coding: utf-8
# ## More solving the problem with some code before I write the code.
#
# 
#
# This post is a [continuation on solving a problem before writing the code]({filename}../meditations/mongodb-geojson/solving-a-ftlpd-data-delivery-problem-before-i-write-code.ipynb).
#
# ### Defining the problem.
#
# 2 objects I want to understand are unfamiliar to me:
#
# * [MongoDB](https://docs.mongodb.com/manual/tutorial/query-documents/)
# * [Data provided by the City of Fort Lauderdale](https://github.com/dm-wyncode/docker-mongo-flpd-hackathon-data/tree/master/mongo-seed/flpd-data) at the [Code for Fort Lauderdale first annual hackathon 2016]({filename}../hackathons/code-for-ftl-hackathon.rst).
#
# I ultimately have a goal of building an interactive website with the police data.
#
# I decided to first tackle the problem of learning how to query MongoDB.
#
# In the process of looking at the police data, I discovered that it needed some cleaning up.
#
# **As a user of the police data, I do not expect to see entries with blank or impossible values.**
#
# Of course finding impossible or illogical data is not unusual. Stuff happens!
#
# So the task at hand is to clean up the data and do some [sanity checks](https://en.wikipedia.org/wiki/Sanity_check).
# ## Sanity checking the data.
#
# *First, import some Python built-ins that will be needed to get the job done.*
# In[2]:
import logging
from pprint import pprint
from itertools import chain
from datetime import datetime
# *The running instance of MongoDB was created using Docker files from [dm-wyncode/docker-mongo-flpd-hackathon-data](https://github.com/dm-wyncode/docker-mongo-flpd-hackathon-data).*
#
# *I wrote an idiomatic Python package so I could easily reuse code. The repository is [dm-wyncode/flpd_helper](https://github.com/dm-wyncode/flpd_helper)*
#
# *import objects needed to talk to a running instance of MongoDb*
# In[3]:
from flpd_helper import (
citations, # a MongoDB collection created from CSV data
valid_citations, # a MongoDB collection where validated data will go
db, # a database instance
log_collection_counts, # function that prints collection counts
)
# importing from flpd_results in info being logged from that package
# *I created constants that avoid repetition and make the aggregation pipelines easier to read.*
#
# *You can see their values [in this Python module](https://github.com/dm-wyncode/flpd_helper/blob/master/flpd_helper/constants.py).*
# In[4]:
from bson import SON
from flpd_helper.constants import * # import almost all the constants.
from flpd_helper.constants import ( # underscores are not imported with import * syntax
_DATE_OCCURRED,
_ID,
)
# *Create a logger for logging debugging info and displaying it in this notebook.*
# In[5]:
from logging_utility import get_logger
logger = logging.getLogger(__name__)
logger = get_logger(logger)
logger.debug("The logger is working.")
# ## Sanity check: Are there blank values in the citation data entries?
# *Create a pipeline which is an array of dictionaries that contain MongoDb query instructions.*
#
# *This one aggregates the field "Date Occurred" and then counts and sorts the data with a limit of 10 items.*
# In[6]:
pipeline = [
{GROUP: {_ID: _DATE_OCCURRED, COUNT: {SUM: 1}}},
{SORT: SON([(COUNT, -1), (_ID, -1), ])},
{LIMIT: 10}
]
# *The actual string that makes up the pipeline looks like this. Recall that I created constants rather than repetedly typing the same quoted strings.*
# In[7]:
pprint(pipeline)
# **Note that there are 1071 records where the date is blank.**
# In[8]:
list(citations.aggregate(pipeline))
# ## Creating a new and better collection called "valid_citations".
#
# Another problem I discovered with the raw data was that the "Date Occured" field had a text string in it with [USA-styled date notation](https://www.theguardian.com/news/datablog/2013/dec/16/why-do-americans-write-the-month-before-the-day). While this date notation may be idiomatically comfortable to USAmericans, the reversal of the day and month makes it impossible to sort date strings in code.
#
# I decided to go one effort better and insert datetime objects into the "Date Occurred" field.
#
# The code to remove the blank entries and insert valid records with datetime objects is [here in the 'load_valid_date_data' function](https://github.com/dm-wyncode/flpd_helper/blob/master/scripts/reload_valid_data.py).
# *Check valid_citations collection has documents.*
# In[9]:
log_collection_counts((valid_citations, ))
# *Notice that the document count for the valid_citations collection is less than the document count for the citations collection because the invalid entries were removed..*
# In[10]:
log_collection_counts((citations, ))
# ## This aggregate results in a citations count per date.
#
# > Here datetime.datetime.utcfromtimestamp(0) will be fed into the pipeline as a BSON Date representing "epoch". When you \$subtract one BSON Date from another the difference in milliseconds is returned. This allows you to "round" the date to the current day by again subtracting the \$mod result to get the remainder of milliseconds difference from a day.
#
# > The same is true of \$add where "adding" a BSON Date to a numeric value will result in a BSON Date.
#
# Taken from [datetime aggregation how-to](http://stackoverflow.com/questions/22031853/pymongo-group-by-datetime).
# In[11]:
# give a citation count based on date and time
pipeline = [
{ GROUP: {
_ID: {
ADD: [
{ SUBTRACT: [
{ SUBTRACT: [ _DATE_OCCURRED, datetime.utcfromtimestamp(0) ] },
{ MOD: [
{ SUBTRACT: [ _DATE_OCCURRED, datetime.utcfromtimestamp(0) ] },
1000 * 60 * 60 * 24
]}
]},
datetime.utcfromtimestamp(0)
]
},
COUNT: { SUM: 1 }
}},
{ SORT: { _ID: 1 } },
]
logger.info(pipeline)
limited_pipeline = pipeline[:] # copy pipeline
limited_pipeline.append({LIMIT: 15})
list(valid_citations.aggregate(limited_pipeline))
# ## This aggregate results in a citations count per date using substrings rather than datetime objects.
# In[12]:
# padding with zeros, number of citations by date
pipeline = [
{GROUP: {
_ID : { CONCAT: [ # join the year, month, day with a dash
{SUBSTR: [{YEAR: _DATE_OCCURRED}, 0, 4 ]},
DASH,
{ COND: [ # pad the month with a leading "0" if less than 9
{ LESS_THAN_OR_EQUAL: [ { MONTH: _DATE_OCCURRED }, 9 ] },
{ CONCAT: [
ZERO_STRING, { SUBSTR: [ { MONTH: _DATE_OCCURRED }, 0, 2 ] }
]},
{ SUBSTR: [ { MONTH: _DATE_OCCURRED }, 0, 2 ] }
]},
DASH,
{ COND: [ # pad the day of month with a leading "0" if less than 9
{ LESS_THAN_OR_EQUAL: [ { DAYOFMONTH: _DATE_OCCURRED }, 9 ] },
{ CONCAT: [
ZERO_STRING, { SUBSTR: [ { DAYOFMONTH: _DATE_OCCURRED }, 0, 2 ] }
]},
{ SUBSTR: [ { DAYOFMONTH: _DATE_OCCURRED }, 0, 2 ] }
]},
]},
COUNT: {SUM: 1 } # count how many records for each YYYY-MM-DD entry
}},
{SORT: { _ID: 1 }} # sort on YYYY-MM-DD
]
logger.info(pipeline)
limited_pipeline = pipeline[:] # copy pipeline
limited_pipeline.append({LIMIT: 15})
list(valid_citations.aggregate(limited_pipeline))
# ## Using Python to get the max and min.
#
# TODO: Learn how to do it with MongoDB.
#
# ### max and min dates of the citations data in the citations collection.
# In[13]:
logger.info(min(date[_ID] for date in valid_citations.aggregate(pipeline)))
logger.info(max(date[_ID] for date in valid_citations.aggregate(pipeline)))
# ## How many empty dates are there?
# ## Using Python to do the counting with a simple find.
#
# I'll trust this simple method as the *gold standard* against which to compare a more complex MongoDb query.
#
# I wanted a method in which I am confident against which I could compare an aggregate method from MongoDB. Since I am learning the aggregate method I wanted to test my answer. Since I do not have canonical answers yet about this data set I have to make two educated guesses and compare them.
# In[14]:
from IPython.core.display import display, HTML
display(HTML('<span id="line-count"></span>'))
# ### Number of documents removed from the database.
# In[15]:
# plain search
# Python is doing the counting
blanks = list(citations.find(
{ # query filter
DATE_OCCURRED: ''
},
))
logger.info(len(blanks))
# ### Using a MongoDB aggregate to do the counting.
# In[16]:
# doing the count with MongoDB
pipeline = [
{ GROUP: {
_ID: {
EQUALS: [ _DATE_OCCURRED, EMPTY_STRING ],
},
COUNT: { SUM: 1 },
}},
{ SORT: { _ID: 1 } },
]
logger.info(pipeline)
counts = list(citations.aggregate(pipeline))
pprint(counts)
# ## Testing my two educated guesses.
# In[17]:
all_counts = empties, not_empties = list(chain(*[[count[COUNT] for count in counts
if count[_ID] is criteria]
for criteria in (True, False)]))
pipeline_sum = sum(all_counts)
citations_total = citations.count()
delimiter = ': '
labels = (
"empties count",
"not empties count",
'sum of empties and non-empties',
'total count',
'two methods equal',
)
data = (
empties,
not_empties,
pipeline_sum,
citations_total,
citations_total == pipeline_sum,
)
data = zip(labels, (str(datum) for datum in data))
for datum in data:
logger.info(delimiter.join(datum))
# ## Resources for creation MongoDB aggregations.
#
# * [datetime aggregation how-to](http://stackoverflow.com/questions/22031853/pymongo-group-by-datetime)
# * [padding a single-digit day and month with a zero](http://stackoverflow.com/questions/25114870/how-to-format-number-1-to-string-01-for-aggregation)
# ## In a future…
#
# I want to use [a React componet library called Griddle](http://griddlegriddle.github.io/Griddle/) to display the data.
| mit |
habeanf/Open-Knesset | tagvotes/models.py | 14 | 1404 | from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from tagging.models import Tag,TaggedItem
class TagVote(models.Model):
"""
Holds the data for user's vote on a tag.
"""
tagged_item = models.ForeignKey(TaggedItem,
verbose_name=_('tagged item'),
related_name='votes')
user = models.ForeignKey(User,
verbose_name=_('user'),
related_name='tagvotes')
vote = models.IntegerField()
class Meta:
# Enforce unique vote per user and tagged item
unique_together = (('tagged_item', 'user'),)
verbose_name = _('tag vote')
verbose_name_plural = _('tag votes')
def __unicode__(self):
return u'%s - %s [%d]' % (self.user, self.tagged_item, self.vote)
def get_absolute_url(self):
ct = ContentType.objects.get(app_label='laws', model='vote')
if self.tagged_item.content_type == ct:
return reverse('vote-tag',
kwargs={'tag':self.tagged_item.tag.name})
else:
return reverse('bill-tag',
kwargs={'tag':self.tagged_item.tag.name})
| bsd-3-clause |
auduny/home-assistant | homeassistant/components/volkszaehler/sensor.py | 7 | 4083 | """Support for consuming values for the Volkszaehler API."""
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_NAME, CONF_PORT, CONF_MONITORED_CONDITIONS, POWER_WATT,
ENERGY_WATT_HOUR)
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
_LOGGER = logging.getLogger(__name__)
CONF_UUID = 'uuid'
DEFAULT_HOST = 'localhost'
DEFAULT_NAME = 'Volkszaehler'
DEFAULT_PORT = 80
MIN_TIME_BETWEEN_UPDATES = timedelta(minutes=1)
SENSOR_TYPES = {
'average': ['Average', POWER_WATT, 'mdi:power-off'],
'consumption': ['Consumption', ENERGY_WATT_HOUR, 'mdi:power-plug'],
'max': ['Max', POWER_WATT, 'mdi:arrow-up'],
'min': ['Min', POWER_WATT, 'mdi:arrow-down'],
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_UUID): cv.string,
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_MONITORED_CONDITIONS, default=['average']):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
})
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None):
"""Set up the Volkszaehler sensors."""
from volkszaehler import Volkszaehler
host = config[CONF_HOST]
name = config[CONF_NAME]
port = config[CONF_PORT]
uuid = config[CONF_UUID]
conditions = config[CONF_MONITORED_CONDITIONS]
session = async_get_clientsession(hass)
vz_api = VolkszaehlerData(
Volkszaehler(hass.loop, session, uuid, host=host, port=port))
await vz_api.async_update()
if vz_api.api.data is None:
raise PlatformNotReady
dev = []
for condition in conditions:
dev.append(VolkszaehlerSensor(vz_api, name, condition))
async_add_entities(dev, True)
class VolkszaehlerSensor(Entity):
"""Implementation of a Volkszaehler sensor."""
def __init__(self, vz_api, name, sensor_type):
"""Initialize the Volkszaehler sensor."""
self.vz_api = vz_api
self._name = name
self.type = sensor_type
self._state = None
@property
def name(self):
"""Return the name of the sensor."""
return '{} {}'.format(self._name, SENSOR_TYPES[self.type][0])
@property
def icon(self):
"""Icon to use in the frontend, if any."""
return SENSOR_TYPES[self.type][2]
@property
def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return SENSOR_TYPES[self.type][1]
@property
def available(self):
"""Could the device be accessed during the last update call."""
return self.vz_api.available
@property
def state(self):
"""Return the state of the resources."""
return self._state
async def async_update(self):
"""Get the latest data from REST API."""
await self.vz_api.async_update()
if self.vz_api.api.data is not None:
self._state = round(getattr(self.vz_api.api, self.type), 2)
class VolkszaehlerData:
"""The class for handling the data retrieval from the Volkszaehler API."""
def __init__(self, api):
"""Initialize the data object."""
self.api = api
self.available = True
@Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self):
"""Get the latest data from the Volkszaehler REST API."""
from volkszaehler.exceptions import VolkszaehlerApiConnectionError
try:
await self.api.get_data()
self.available = True
except VolkszaehlerApiConnectionError:
_LOGGER.error("Unable to fetch data from the Volkszaehler API")
self.available = False
| apache-2.0 |
jhonatajh/mtasa-blue | vendor/google-breakpad/src/tools/gyp/pylib/gyp/xml_fix.py | 2767 | 2174 | # Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Applies a fix to CR LF TAB handling in xml.dom.
Fixes this: http://code.google.com/p/chromium/issues/detail?id=76293
Working around this: http://bugs.python.org/issue5752
TODO(bradnelson): Consider dropping this when we drop XP support.
"""
import xml.dom.minidom
def _Replacement_write_data(writer, data, is_attrib=False):
"""Writes datachars to writer."""
data = data.replace("&", "&").replace("<", "<")
data = data.replace("\"", """).replace(">", ">")
if is_attrib:
data = data.replace(
"\r", "
").replace(
"\n", "
").replace(
"\t", "	")
writer.write(data)
def _Replacement_writexml(self, writer, indent="", addindent="", newl=""):
# indent = current indentation
# addindent = indentation to add to higher levels
# newl = newline string
writer.write(indent+"<" + self.tagName)
attrs = self._get_attributes()
a_names = attrs.keys()
a_names.sort()
for a_name in a_names:
writer.write(" %s=\"" % a_name)
_Replacement_write_data(writer, attrs[a_name].value, is_attrib=True)
writer.write("\"")
if self.childNodes:
writer.write(">%s" % newl)
for node in self.childNodes:
node.writexml(writer, indent + addindent, addindent, newl)
writer.write("%s</%s>%s" % (indent, self.tagName, newl))
else:
writer.write("/>%s" % newl)
class XmlFix(object):
"""Object to manage temporary patching of xml.dom.minidom."""
def __init__(self):
# Preserve current xml.dom.minidom functions.
self.write_data = xml.dom.minidom._write_data
self.writexml = xml.dom.minidom.Element.writexml
# Inject replacement versions of a function and a method.
xml.dom.minidom._write_data = _Replacement_write_data
xml.dom.minidom.Element.writexml = _Replacement_writexml
def Cleanup(self):
if self.write_data:
xml.dom.minidom._write_data = self.write_data
xml.dom.minidom.Element.writexml = self.writexml
self.write_data = None
def __del__(self):
self.Cleanup()
| gpl-3.0 |
canaltinova/servo | tests/wpt/web-platform-tests/tools/wpt/run.py | 3 | 15503 | import argparse
import os
import platform
import shutil
import subprocess
import sys
import tarfile
from distutils.spawn import find_executable
wpt_root = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
sys.path.insert(0, os.path.abspath(os.path.join(wpt_root, "tools")))
from . import browser, utils, virtualenv
from ..serve import serve
logger = None
class WptrunError(Exception):
pass
class WptrunnerHelpAction(argparse.Action):
def __init__(self,
option_strings,
dest=argparse.SUPPRESS,
default=argparse.SUPPRESS,
help=None):
super(WptrunnerHelpAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
from wptrunner import wptcommandline
wptparser = wptcommandline.create_parser()
wptparser.usage = parser.usage
wptparser.print_help()
parser.exit()
def create_parser():
from wptrunner import wptcommandline
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument("product", action="store",
help="Browser to run tests in")
parser.add_argument("--yes", "-y", dest="prompt", action="store_false", default=True,
help="Don't prompt before installing components")
parser.add_argument("--stability", action="store_true",
help="Stability check tests")
parser.add_argument("--install-browser", action="store_true",
help="Install the latest development version of the browser")
parser._add_container_actions(wptcommandline.create_parser())
return parser
def exit(msg):
logger.error(msg)
sys.exit(1)
def args_general(kwargs):
kwargs.set_if_none("tests_root", wpt_root)
kwargs.set_if_none("metadata_root", wpt_root)
kwargs.set_if_none("manifest_update", True)
kwargs.set_if_none("manifest_download", True)
if kwargs["ssl_type"] in (None, "pregenerated"):
cert_root = os.path.join(wpt_root, "tools", "certs")
if kwargs["ca_cert_path"] is None:
kwargs["ca_cert_path"] = os.path.join(cert_root, "cacert.pem")
if kwargs["host_key_path"] is None:
kwargs["host_key_path"] = os.path.join(cert_root, "web-platform.test.key")
if kwargs["host_cert_path"] is None:
kwargs["host_cert_path"] = os.path.join(cert_root, "web-platform.test.pem")
elif kwargs["ssl_type"] == "openssl":
if not find_executable(kwargs["openssl_binary"]):
if os.uname()[0] == "Windows":
raise WptrunError("""OpenSSL binary not found. If you need HTTPS tests, install OpenSSL from
https://slproweb.com/products/Win32OpenSSL.html
Ensuring that libraries are added to /bin and add the resulting bin directory to
your PATH.
Otherwise run with --ssl-type=none""")
else:
raise WptrunError("""OpenSSL not found. If you don't need HTTPS support run with --ssl-type=none,
otherwise install OpenSSL and ensure that it's on your $PATH.""")
def check_environ(product):
if product not in ("firefox", "servo"):
config = serve.load_config(os.path.join(wpt_root, "config.default.json"),
os.path.join(wpt_root, "config.json"))
expected_hosts = (set(config["domains"].itervalues()) ^
set(config["not_domains"].itervalues()))
missing_hosts = set(expected_hosts)
if platform.uname()[0] != "Windows":
hosts_path = "/etc/hosts"
else:
hosts_path = "C:\Windows\System32\drivers\etc\hosts"
with open(hosts_path, "r") as f:
for line in f:
line = line.split("#", 1)[0].strip()
parts = line.split()
hosts = parts[1:]
for host in hosts:
missing_hosts.discard(host)
if missing_hosts:
if platform.uname()[0] != "Windows":
message = """Missing hosts file configuration. Run
./wpt make-hosts-file | sudo tee -a %s""" % hosts_path
else:
message = """Missing hosts file configuration. Run
python wpt make-hosts-file >> %s
from a shell with Administrator privileges.""" % hosts_path
raise WptrunError(message)
class BrowserSetup(object):
name = None
browser_cls = None
def __init__(self, venv, prompt=True, sub_product=None):
self.browser = self.browser_cls()
self.venv = venv
self.prompt = prompt
self.sub_product = sub_product
def prompt_install(self, component):
if not self.prompt:
return True
while True:
resp = raw_input("Download and install %s [Y/n]? " % component).strip().lower()
if not resp or resp == "y":
return True
elif resp == "n":
return False
def install(self, venv):
if self.prompt_install(self.name):
return self.browser.install(venv.path)
def install_requirements(self):
self.venv.install_requirements(os.path.join(wpt_root, "tools", "wptrunner", self.browser.requirements))
def setup(self, kwargs):
self.setup_kwargs(kwargs)
class Firefox(BrowserSetup):
name = "firefox"
browser_cls = browser.Firefox
def setup_kwargs(self, kwargs):
if kwargs["binary"] is None:
binary = self.browser.find_binary(self.venv.path)
if binary is None:
raise WptrunError("""Firefox binary not found on $PATH.
Install Firefox or use --binary to set the binary path""")
kwargs["binary"] = binary
if kwargs["certutil_binary"] is None and kwargs["ssl_type"] != "none":
certutil = self.browser.find_certutil()
if certutil is None:
# Can't download this for now because it's missing the libnss3 library
logger.info("""Can't find certutil, certificates will not be checked.
Consider installing certutil via your OS package manager or directly.""")
else:
print("Using certutil %s" % certutil)
kwargs["certutil_binary"] = certutil
if kwargs["webdriver_binary"] is None and "wdspec" in kwargs["test_types"]:
webdriver_binary = self.browser.find_webdriver()
if webdriver_binary is None:
install = self.prompt_install("geckodriver")
if install:
print("Downloading geckodriver")
webdriver_binary = self.browser.install_webdriver(dest=self.venv.bin_path)
else:
print("Using webdriver binary %s" % webdriver_binary)
if webdriver_binary:
kwargs["webdriver_binary"] = webdriver_binary
else:
print("Unable to find or install geckodriver, skipping wdspec tests")
kwargs["test_types"].remove("wdspec")
if kwargs["prefs_root"] is None:
prefs_root = self.browser.install_prefs(kwargs["binary"], self.venv.path)
kwargs["prefs_root"] = prefs_root
class Chrome(BrowserSetup):
name = "chrome"
browser_cls = browser.Chrome
def setup_kwargs(self, kwargs):
if kwargs["webdriver_binary"] is None:
webdriver_binary = self.browser.find_webdriver()
if webdriver_binary is None:
install = self.prompt_install("chromedriver")
if install:
print("Downloading chromedriver")
webdriver_binary = self.browser.install_webdriver(dest=self.venv.bin_path)
else:
print("Using webdriver binary %s" % webdriver_binary)
if webdriver_binary:
kwargs["webdriver_binary"] = webdriver_binary
else:
raise WptrunError("Unable to locate or install chromedriver binary")
class ChromeAndroid(BrowserSetup):
name = "chrome_android"
browser_cls = browser.ChromeAndroid
def setup_kwargs(self, kwargs):
if kwargs["webdriver_binary"] is None:
webdriver_binary = self.browser.find_webdriver()
if webdriver_binary is None:
install = self.prompt_install("chromedriver")
if install:
print("Downloading chromedriver")
webdriver_binary = self.browser.install_webdriver(dest=self.venv.bin_path)
else:
print("Using webdriver binary %s" % webdriver_binary)
if webdriver_binary:
kwargs["webdriver_binary"] = webdriver_binary
else:
raise WptrunError("Unable to locate or install chromedriver binary")
class Opera(BrowserSetup):
name = "opera"
browser_cls = browser.Opera
def setup_kwargs(self, kwargs):
if kwargs["webdriver_binary"] is None:
webdriver_binary = self.browser.find_webdriver()
if webdriver_binary is None:
install = self.prompt_install("operadriver")
if install:
print("Downloading operadriver")
webdriver_binary = self.browser.install_webdriver(dest=self.venv.bin_path)
else:
print("Using webdriver binary %s" % webdriver_binary)
if webdriver_binary:
kwargs["webdriver_binary"] = webdriver_binary
else:
raise WptrunError("Unable to locate or install operadriver binary")
class Edge(BrowserSetup):
name = "edge"
browser_cls = browser.Edge
def install(self, venv):
raise NotImplementedError
def setup_kwargs(self, kwargs):
if kwargs["webdriver_binary"] is None:
webdriver_binary = self.browser.find_webdriver()
if webdriver_binary is None:
raise WptrunError("""Unable to find WebDriver and we aren't yet clever enough to work out which
version to download. Please go to the following URL and install the correct
version for your Edge/Windows release somewhere on the %PATH%:
https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
""")
kwargs["webdriver_binary"] = webdriver_binary
class InternetExplorer(BrowserSetup):
name = "ie"
browser_cls = browser.InternetExplorer
def install(self, venv):
raise NotImplementedError
def setup_kwargs(self, kwargs):
if kwargs["webdriver_binary"] is None:
webdriver_binary = self.browser.find_webdriver()
if webdriver_binary is None:
raise WptrunError("""Unable to find WebDriver and we aren't yet clever enough to work out which
version to download. Please go to the following URL and install the driver for Internet Explorer
somewhere on the %PATH%:
https://selenium-release.storage.googleapis.com/index.html
""")
kwargs["webdriver_binary"] = webdriver_binary
class Safari(BrowserSetup):
name = "safari"
browser_cls = browser.Safari
def install(self, venv):
raise NotImplementedError
def setup_kwargs(self, kwargs):
if kwargs["webdriver_binary"] is None:
webdriver_binary = self.browser.find_webdriver()
if webdriver_binary is None:
raise WptrunError("Unable to locate safaridriver binary")
kwargs["webdriver_binary"] = webdriver_binary
class Sauce(BrowserSetup):
name = "sauce"
browser_cls = browser.Sauce
def install(self, venv):
raise NotImplementedError
def setup_kwargs(self, kwargs):
kwargs.set_if_none("sauce_browser", self.sub_product[0])
kwargs.set_if_none("sauce_version", self.sub_product[1])
kwargs["test_types"] = ["testharness", "reftest"]
class Servo(BrowserSetup):
name = "servo"
browser_cls = browser.Servo
def install(self, venv):
if self.prompt_install(self.name):
return self.browser.install(venv.path)
def setup_kwargs(self, kwargs):
if kwargs["binary"] is None:
binary = self.browser.find_binary()
if binary is None:
raise WptrunError("Unable to find servo binary on the PATH")
kwargs["binary"] = binary
class WebKit(BrowserSetup):
name = "webkit"
browser_cls = browser.WebKit
def install(self, venv):
raise NotImplementedError
def setup_kwargs(self, kwargs):
pass
product_setup = {
"firefox": Firefox,
"chrome": Chrome,
"chrome_android": ChromeAndroid,
"edge": Edge,
"ie": InternetExplorer,
"safari": Safari,
"servo": Servo,
"sauce": Sauce,
"opera": Opera,
"webkit": WebKit,
}
def setup_wptrunner(venv, prompt=True, install=False, **kwargs):
from wptrunner import wptrunner, wptcommandline
global logger
kwargs = utils.Kwargs(kwargs.iteritems())
product_parts = kwargs["product"].split(":")
kwargs["product"] = product_parts[0]
sub_product = product_parts[1:]
wptrunner.setup_logging(kwargs, {"mach": sys.stdout})
logger = wptrunner.logger
check_environ(kwargs["product"])
args_general(kwargs)
if kwargs["product"] not in product_setup:
raise WptrunError("Unsupported product %s" % kwargs["product"])
setup_cls = product_setup[kwargs["product"]](venv, prompt, sub_product)
setup_cls.install_requirements()
if install:
logger.info("Installing browser")
kwargs["binary"] = setup_cls.install(venv)
setup_cls.setup(kwargs)
wptcommandline.check_args(kwargs)
wptrunner_path = os.path.join(wpt_root, "tools", "wptrunner")
venv.install_requirements(os.path.join(wptrunner_path, "requirements.txt"))
return kwargs
def run(venv, **kwargs):
#Remove arguments that aren't passed to wptrunner
prompt = kwargs.pop("prompt", True)
stability = kwargs.pop("stability", True)
install_browser = kwargs.pop("install_browser", False)
kwargs = setup_wptrunner(venv,
prompt=prompt,
install=install_browser,
**kwargs)
if stability:
import stability
iterations, results, inconsistent = stability.run(venv, logger, **kwargs)
def log(x):
print(x)
if inconsistent:
stability.write_inconsistent(log, inconsistent, iterations)
else:
log("All tests stable")
rv = len(inconsistent) > 0
else:
rv = run_single(venv, **kwargs) > 0
return rv
def run_single(venv, **kwargs):
from wptrunner import wptrunner
wptrunner.start(**kwargs)
return
def main():
try:
parser = create_parser()
args = parser.parse_args()
venv = virtualenv.Virtualenv(os.path.join(wpt_root, "_venv_%s") % platform.uname()[0])
venv.start()
venv.install_requirements(os.path.join(wpt_root, "tools", "wptrunner", "requirements.txt"))
venv.install("requests")
return run(venv, vars(args))
except WptrunError as e:
exit(e.message)
if __name__ == "__main__":
import pdb
from tools import localpaths
try:
main()
except Exception:
pdb.post_mortem()
| mpl-2.0 |
utkbansal/kuma | vendor/packages/translate/filters/decorators.py | 26 | 2078 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2012 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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.
#
# translate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
"""Decorators to categorize pofilter checks."""
from functools import wraps
#: Quality checks' failure categories
class Category(object):
CRITICAL = 100
FUNCTIONAL = 60
COSMETIC = 30
EXTRACTION = 10
NO_CATEGORY = 0
def critical(f):
@wraps(f)
def critical_f(self, *args, **kwargs):
if f.__name__ not in self.__class__.categories:
self.__class__.categories[f.__name__] = Category.CRITICAL
return f(self, *args, **kwargs)
return critical_f
def functional(f):
@wraps(f)
def functional_f(self, *args, **kwargs):
if f.__name__ not in self.__class__.categories:
self.__class__.categories[f.__name__] = Category.FUNCTIONAL
return f(self, *args, **kwargs)
return functional_f
def cosmetic(f):
@wraps(f)
def cosmetic_f(self, *args, **kwargs):
if f.__name__ not in self.__class__.categories:
self.__class__.categories[f.__name__] = Category.COSMETIC
return f(self, *args, **kwargs)
return cosmetic_f
def extraction(f):
@wraps(f)
def extraction_f(self, *args, **kwargs):
if f.__name__ not in self.__class__.categories:
self.__class__.categories[f.__name__] = Category.EXTRACTION
return f(self, *args, **kwargs)
return extraction_f
| mpl-2.0 |
mengxn/tensorflow | tensorflow/contrib/bayesflow/examples/reinforce_simple/reinforce_simple_example.py | 105 | 5003 | # Copyright 2016 The TensorFlow Authors. 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.
# ==============================================================================
"""Simple examples of the REINFORCE algorithm."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
distributions = tf.contrib.distributions
sg = tf.contrib.bayesflow.stochastic_graph
st = tf.contrib.bayesflow.stochastic_tensor
def split_apply_merge(inp, partitions, fns):
"""Split input according to partitions. Pass results through fns and merge.
Args:
inp: the input vector
partitions: tensor of same length as input vector, having values 0, 1
fns: the two functions.
Returns:
the vector routed, where routed[i] = fns[partitions[i]](inp[i])
"""
new_inputs = tf.dynamic_partition(inp, partitions, len(fns))
new_outputs = [fns[i](x) for i, x in enumerate(new_inputs)]
new_indices = tf.dynamic_partition(
tf.range(0, inp.get_shape()[0]), partitions, len(fns))
return tf.dynamic_stitch(new_indices, new_outputs)
def plus_1(inputs):
return inputs + 1.0
def minus_1(inputs):
return inputs - 1.0
def build_split_apply_merge_model():
"""Build the Split-Apply-Merge Model.
Route each value of input [-1, -1, 1, 1] through one of the
functions, plus_1, minus_1. The decision for routing is made by
4 Bernoulli R.V.s whose parameters are determined by a neural network
applied to the input. REINFORCE is used to update the NN parameters.
Returns:
The 3-tuple (route_selection, routing_loss, final_loss), where:
- route_selection is an int 4-vector
- routing_loss is a float 4-vector
- final_loss is a float scalar.
"""
inputs = tf.constant([[-1.0], [-1.0], [1.0], [1.0]])
targets = tf.constant([[0.0], [0.0], [0.0], [0.0]])
paths = [plus_1, minus_1]
weights = tf.get_variable("w", [1, 2])
bias = tf.get_variable("b", [1, 1])
logits = tf.matmul(inputs, weights) + bias
# REINFORCE forward step
route_selection = st.StochasticTensor(
distributions.Categorical(logits=logits))
# Accessing route_selection as a Tensor below forces a sample of
# the Categorical distribution based on its logits.
# This is equivalent to calling route_selection.value().
#
# route_selection.value() returns an int32 4-vector with random
# values in {0, 1}
# COPY+ROUTE+PASTE
outputs = split_apply_merge(inputs, route_selection, paths)
# flatten routing_loss to a row vector (from a column vector)
routing_loss = tf.reshape(tf.square(outputs - targets), shape=[-1])
# Total loss: score function loss + routing loss.
# The score function loss (through `route_selection.loss(routing_loss)`)
# returns:
# [stop_gradient(routing_loss) *
# route_selection.log_pmf(stop_gradient(route_selection.value()))],
# where log_pmf has gradients going all the way back to weights and bias.
# In this case, the routing_loss depends on the variables only through
# "route_selection", which has a stop_gradient on it. So the
# gradient of the loss really come through the score function
surrogate_loss = sg.surrogate_loss([routing_loss])
final_loss = tf.reduce_sum(surrogate_loss)
return (route_selection, routing_loss, final_loss)
class REINFORCESimpleExample(tf.test.TestCase):
def testSplitApplyMerge(self):
# Repeatability. SGD has a tendency to jump around, even here.
tf.set_random_seed(1)
with self.test_session() as sess:
# Use sampling to train REINFORCE
with st.value_type(st.SampleValue()):
(route_selection,
routing_loss,
final_loss) = build_split_apply_merge_model()
sgd = tf.train.GradientDescentOptimizer(1.0).minimize(final_loss)
tf.global_variables_initializer().run()
for i in range(10):
# Run loss and inference step. This toy problem converges VERY quickly.
(routing_loss_v, final_loss_v, route_selection_v, _) = sess.run(
[routing_loss, final_loss, tf.identity(route_selection), sgd])
print(
"Iteration %d, routing loss: %s, final_loss: %s, "
"route selection: %s"
% (i, routing_loss_v, final_loss_v, route_selection_v))
self.assertAllEqual([0, 0, 1, 1], route_selection_v)
self.assertAllClose([0.0, 0.0, 0.0, 0.0], routing_loss_v)
self.assertAllClose(0.0, final_loss_v)
if __name__ == "__main__":
tf.test.main()
| apache-2.0 |
yosshy/nova | nova/tests/unit/test_api_validation.py | 7 | 40406 | # Copyright 2013 NEC Corporation. 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 copy
import re
from nova.api.openstack import api_version_request as api_version
from nova.api import validation
from nova.api.validation import parameter_types
from nova import exception
from nova import test
class FakeRequest(object):
api_version_request = api_version.APIVersionRequest("2.1")
environ = {}
legacy_v2 = False
def is_legacy_v2(self):
return self.legacy_v2
class APIValidationTestCase(test.NoDBTestCase):
def check_validation_error(self, method, body, expected_detail, req=None):
if not req:
req = FakeRequest()
try:
method(body=body, req=req,)
except exception.ValidationError as ex:
self.assertEqual(400, ex.kwargs['code'])
if not re.match(expected_detail, ex.kwargs['detail']):
self.assertEqual(expected_detail, ex.kwargs['detail'],
'Exception details did not match expected')
except Exception as ex:
self.fail('An unexpected exception happens: %s' % ex)
else:
self.fail('Any exception does not happen.')
class MicroversionsSchemaTestCase(APIValidationTestCase):
def setUp(self):
super(MicroversionsSchemaTestCase, self).setUp()
schema_v21_int = {
'type': 'object',
'properties': {
'foo': {
'type': 'integer',
}
}
}
schema_v20_str = copy.deepcopy(schema_v21_int)
schema_v20_str['properties']['foo'] = {'type': 'string'}
@validation.schema(schema_v20_str, '2.0', '2.0')
@validation.schema(schema_v21_int, '2.1')
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_v2compatible_request(self):
req = FakeRequest()
req.legacy_v2 = True
self.assertEqual(self.post(body={'foo': 'bar'}, req=req),
'Validation succeeded.')
detail = ("Invalid input for field/attribute foo. Value: 1. "
"1 is not of type 'string'")
self.check_validation_error(self.post, body={'foo': 1},
expected_detail=detail, req=req)
def test_validate_v21_request(self):
req = FakeRequest()
self.assertEqual(self.post(body={'foo': 1}, req=req),
'Validation succeeded.')
detail = ("Invalid input for field/attribute foo. Value: bar. "
"'bar' is not of type 'integer'")
self.check_validation_error(self.post, body={'foo': 'bar'},
expected_detail=detail, req=req)
class RequiredDisableTestCase(APIValidationTestCase):
def setUp(self):
super(RequiredDisableTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'integer',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_required_disable(self):
self.assertEqual(self.post(body={'foo': 1}, req=FakeRequest()),
'Validation succeeded.')
self.assertEqual(self.post(body={'abc': 1}, req=FakeRequest()),
'Validation succeeded.')
class RequiredEnableTestCase(APIValidationTestCase):
def setUp(self):
super(RequiredEnableTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'integer',
},
},
'required': ['foo']
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_required_enable(self):
self.assertEqual(self.post(body={'foo': 1},
req=FakeRequest()), 'Validation succeeded.')
def test_validate_required_enable_fails(self):
detail = "'foo' is a required property"
self.check_validation_error(self.post, body={'abc': 1},
expected_detail=detail)
class AdditionalPropertiesEnableTestCase(APIValidationTestCase):
def setUp(self):
super(AdditionalPropertiesEnableTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'integer',
},
},
'required': ['foo'],
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_additionalProperties_enable(self):
self.assertEqual(self.post(body={'foo': 1}, req=FakeRequest()),
'Validation succeeded.')
self.assertEqual(self.post(body={'foo': 1, 'ext': 1},
req=FakeRequest()),
'Validation succeeded.')
class AdditionalPropertiesDisableTestCase(APIValidationTestCase):
def setUp(self):
super(AdditionalPropertiesDisableTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'integer',
},
},
'required': ['foo'],
'additionalProperties': False,
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_additionalProperties_disable(self):
self.assertEqual(self.post(body={'foo': 1}, req=FakeRequest()),
'Validation succeeded.')
def test_validate_additionalProperties_disable_fails(self):
detail = "Additional properties are not allowed ('ext' was unexpected)"
self.check_validation_error(self.post, body={'foo': 1, 'ext': 1},
expected_detail=detail)
class PatternPropertiesTestCase(APIValidationTestCase):
def setUp(self):
super(PatternPropertiesTestCase, self).setUp()
schema = {
'patternProperties': {
'^[a-zA-Z0-9]{1,10}$': {
'type': 'string'
},
},
'additionalProperties': False,
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_patternProperties(self):
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'bar'}, req=FakeRequest()))
def test_validate_patternProperties_fails(self):
detail = "Additional properties are not allowed ('__' was unexpected)"
self.check_validation_error(self.post, body={'__': 'bar'},
expected_detail=detail)
detail = "Additional properties are not allowed ('' was unexpected)"
self.check_validation_error(self.post, body={'': 'bar'},
expected_detail=detail)
detail = ("Additional properties are not allowed ('0123456789a' was"
" unexpected)")
self.check_validation_error(self.post, body={'0123456789a': 'bar'},
expected_detail=detail)
detail = "expected string or buffer"
self.check_validation_error(self.post, body={None: 'bar'},
expected_detail=detail)
class StringTestCase(APIValidationTestCase):
def setUp(self):
super(StringTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'string',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_string(self):
self.assertEqual(self.post(body={'foo': 'abc'}, req=FakeRequest()),
'Validation succeeded.')
self.assertEqual(self.post(body={'foo': '0'}, req=FakeRequest()),
'Validation succeeded.')
self.assertEqual(self.post(body={'foo': ''}, req=FakeRequest()),
'Validation succeeded.')
def test_validate_string_fails(self):
detail = ("Invalid input for field/attribute foo. Value: 1."
" 1 is not of type 'string'")
self.check_validation_error(self.post, body={'foo': 1},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 1.5."
" 1.5 is not of type 'string'")
self.check_validation_error(self.post, body={'foo': 1.5},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: True."
" True is not of type 'string'")
self.check_validation_error(self.post, body={'foo': True},
expected_detail=detail)
class StringLengthTestCase(APIValidationTestCase):
def setUp(self):
super(StringLengthTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'string',
'minLength': 1,
'maxLength': 10,
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_string_length(self):
self.assertEqual(self.post(body={'foo': '0'}, req=FakeRequest()),
'Validation succeeded.')
self.assertEqual(self.post(body={'foo': '0123456789'},
req=FakeRequest()),
'Validation succeeded.')
def test_validate_string_length_fails(self):
detail = ("Invalid input for field/attribute foo. Value: ."
" '' is too short")
self.check_validation_error(self.post, body={'foo': ''},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 0123456789a."
" '0123456789a' is too long")
self.check_validation_error(self.post, body={'foo': '0123456789a'},
expected_detail=detail)
class IntegerTestCase(APIValidationTestCase):
def setUp(self):
super(IntegerTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': ['integer', 'string'],
'pattern': '^[0-9]+$',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_integer(self):
self.assertEqual(self.post(body={'foo': 1}, req=FakeRequest()),
'Validation succeeded.')
self.assertEqual(self.post(body={'foo': '1'}, req=FakeRequest()),
'Validation succeeded.')
self.assertEqual(self.post(body={'foo': '0123456789'},
req=FakeRequest()),
'Validation succeeded.')
def test_validate_integer_fails(self):
detail = ("Invalid input for field/attribute foo. Value: abc."
" 'abc' does not match '^[0-9]+$'")
self.check_validation_error(self.post, body={'foo': 'abc'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: True."
" True is not of type 'integer', 'string'")
self.check_validation_error(self.post, body={'foo': True},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 0xffff."
" '0xffff' does not match '^[0-9]+$'")
self.check_validation_error(self.post, body={'foo': '0xffff'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 1.0."
" 1.0 is not of type 'integer', 'string'")
self.check_validation_error(self.post, body={'foo': 1.0},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 1.0."
" '1.0' does not match '^[0-9]+$'")
self.check_validation_error(self.post, body={'foo': '1.0'},
expected_detail=detail)
class IntegerRangeTestCase(APIValidationTestCase):
def setUp(self):
super(IntegerRangeTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': ['integer', 'string'],
'pattern': '^[0-9]+$',
'minimum': 1,
'maximum': 10,
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_integer_range(self):
self.assertEqual(self.post(body={'foo': 1}, req=FakeRequest()),
'Validation succeeded.')
self.assertEqual(self.post(body={'foo': 10}, req=FakeRequest()),
'Validation succeeded.')
self.assertEqual(self.post(body={'foo': '1'}, req=FakeRequest()),
'Validation succeeded.')
def test_validate_integer_range_fails(self):
detail = ("Invalid input for field/attribute foo. Value: 0."
" 0(.0)? is less than the minimum of 1")
self.check_validation_error(self.post, body={'foo': 0},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 11."
" 11(.0)? is greater than the maximum of 10")
self.check_validation_error(self.post, body={'foo': 11},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 0."
" 0(.0)? is less than the minimum of 1")
self.check_validation_error(self.post, body={'foo': '0'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 11."
" 11(.0)? is greater than the maximum of 10")
self.check_validation_error(self.post, body={'foo': '11'},
expected_detail=detail)
class BooleanTestCase(APIValidationTestCase):
def setUp(self):
super(BooleanTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': parameter_types.boolean,
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_boolean(self):
self.assertEqual('Validation succeeded.',
self.post(body={'foo': True}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': False}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'True'}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'False'}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': '1'}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': '0'}, req=FakeRequest()))
def test_validate_boolean_fails(self):
enum_boolean = ("[True, 'True', 'TRUE', 'true', '1', 'ON', 'On',"
" 'on', 'YES', 'Yes', 'yes',"
" False, 'False', 'FALSE', 'false', '0', 'OFF', 'Off',"
" 'off', 'NO', 'No', 'no']")
detail = ("Invalid input for field/attribute foo. Value: bar."
" 'bar' is not one of %s") % enum_boolean
self.check_validation_error(self.post, body={'foo': 'bar'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 2."
" '2' is not one of %s") % enum_boolean
self.check_validation_error(self.post, body={'foo': '2'},
expected_detail=detail)
class HostnameTestCase(APIValidationTestCase):
def setUp(self):
super(HostnameTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': parameter_types.hostname,
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_hostname(self):
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'localhost'},
req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'localhost.localdomain.com'},
req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'my-host'}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'my_host'}, req=FakeRequest()))
def test_validate_hostname_fails(self):
detail = ("Invalid input for field/attribute foo. Value: True."
" True is not of type 'string'")
self.check_validation_error(self.post, body={'foo': True},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 1."
" 1 is not of type 'string'")
self.check_validation_error(self.post, body={'foo': 1},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: my$host."
" 'my$host' does not match '^[a-zA-Z0-9-._]*$'")
self.check_validation_error(self.post, body={'foo': 'my$host'},
expected_detail=detail)
class HostnameIPaddressTestCase(APIValidationTestCase):
def setUp(self):
super(HostnameIPaddressTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': parameter_types.hostname_or_ip_address,
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_hostname_or_ip_address(self):
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'localhost'},
req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'localhost.localdomain.com'},
req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'my-host'}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'my_host'}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': '192.168.10.100'},
req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': '2001:db8::9abc'},
req=FakeRequest()))
def test_validate_hostname_or_ip_address_fails(self):
detail = ("Invalid input for field/attribute foo. Value: True."
" True is not of type 'string'")
self.check_validation_error(self.post, body={'foo': True},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 1."
" 1 is not of type 'string'")
self.check_validation_error(self.post, body={'foo': 1},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: my$host."
" 'my$host' does not match '^[a-zA-Z0-9-_.:]*$'")
self.check_validation_error(self.post, body={'foo': 'my$host'},
expected_detail=detail)
class NameTestCase(APIValidationTestCase):
def setUp(self):
super(NameTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': parameter_types.name,
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_name(self):
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'm1.small'},
req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'my server'},
req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'a'}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': u'\u0434'}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': u'\u0434\u2006\ufffd'},
req=FakeRequest()))
def test_validate_name_fails(self):
detail = (u"Invalid input for field/attribute foo. Value: ."
" ' ' does not match .*")
self.check_validation_error(self.post, body={'foo': ' '},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: server."
" ' server' does not match .*")
self.check_validation_error(self.post, body={'foo': ' server'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: server ."
" 'server ' does not match .*")
self.check_validation_error(self.post, body={'foo': 'server '},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: a."
" ' a' does not match .*")
self.check_validation_error(self.post, body={'foo': ' a'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: a ."
" 'a ' does not match .*")
self.check_validation_error(self.post, body={'foo': 'a '},
expected_detail=detail)
# NOTE(stpierre): Quoting for the unicode values in the error
# messages below gets *really* messy, so we just wildcard it
# out. (e.g., '.* does not match'). In practice, we don't
# particularly care about that part of the error message.
# trailing unicode space
detail = (u"Invalid input for field/attribute foo. Value: a\xa0."
u' .* does not match .*')
self.check_validation_error(self.post, body={'foo': u'a\xa0'},
expected_detail=detail)
# non-printable unicode
detail = (u"Invalid input for field/attribute foo. Value: \uffff."
u" .* does not match .*")
self.check_validation_error(self.post, body={'foo': u'\uffff'},
expected_detail=detail)
# four-byte unicode, if supported by this python build
try:
detail = (u"Invalid input for field/attribute foo. Value: "
u"\U00010000. .* does not match .*")
self.check_validation_error(self.post, body={'foo': u'\U00010000'},
expected_detail=detail)
except ValueError:
pass
class NoneTypeTestCase(APIValidationTestCase):
def setUp(self):
super(NoneTypeTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': parameter_types.none
}
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_none(self):
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'None'},
req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': None},
req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': {}},
req=FakeRequest()))
def test_validate_none_fails(self):
detail = ("Invalid input for field/attribute foo. Value: ."
" '' is not one of ['None', None, {}]")
self.check_validation_error(self.post, body={'foo': ''},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: "
"{'key': 'val'}. {'key': 'val'} is not one of "
"['None', None, {}]")
self.check_validation_error(self.post, body={'foo': {'key': 'val'}},
expected_detail=detail)
class TcpUdpPortTestCase(APIValidationTestCase):
def setUp(self):
super(TcpUdpPortTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': parameter_types.tcp_udp_port,
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_tcp_udp_port(self):
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 1024}, req=FakeRequest()))
self.assertEqual('Validation succeeded.',
self.post(body={'foo': '1024'}, req=FakeRequest()))
def test_validate_tcp_udp_port_fails(self):
detail = ("Invalid input for field/attribute foo. Value: True."
" True is not of type 'integer', 'string'")
self.check_validation_error(self.post, body={'foo': True},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 65536."
" 65536(.0)? is greater than the maximum of 65535")
self.check_validation_error(self.post, body={'foo': 65536},
expected_detail=detail)
class CidrFormatTestCase(APIValidationTestCase):
def setUp(self):
super(CidrFormatTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'string',
'format': 'cidr',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_cidr(self):
self.assertEqual('Validation succeeded.',
self.post(
body={'foo': '192.168.10.0/24'},
req=FakeRequest()
))
def test_validate_cidr_fails(self):
detail = ("Invalid input for field/attribute foo."
" Value: bar."
" 'bar' is not a 'cidr'")
self.check_validation_error(self.post,
body={'foo': 'bar'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo."
" Value: . '' is not a 'cidr'")
self.check_validation_error(self.post, body={'foo': ''},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo."
" Value: 192.168.1.0. '192.168.1.0' is not a 'cidr'")
self.check_validation_error(self.post, body={'foo': '192.168.1.0'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo."
" Value: 192.168.1.0 /24."
" '192.168.1.0 /24' is not a 'cidr'")
self.check_validation_error(self.post, body={'foo': '192.168.1.0 /24'},
expected_detail=detail)
class DatetimeTestCase(APIValidationTestCase):
def setUp(self):
super(DatetimeTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'string',
'format': 'date-time',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_datetime(self):
self.assertEqual('Validation succeeded.',
self.post(
body={'foo': '2014-01-14T01:00:00Z'},
req=FakeRequest()
))
def test_validate_datetime_fails(self):
detail = ("Invalid input for field/attribute foo."
" Value: 2014-13-14T01:00:00Z."
" '2014-13-14T01:00:00Z' is not a 'date-time'")
self.check_validation_error(self.post,
body={'foo': '2014-13-14T01:00:00Z'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo."
" Value: bar. 'bar' is not a 'date-time'")
self.check_validation_error(self.post, body={'foo': 'bar'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 1."
" '1' is not a 'date-time'")
self.check_validation_error(self.post, body={'foo': '1'},
expected_detail=detail)
class UuidTestCase(APIValidationTestCase):
def setUp(self):
super(UuidTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'string',
'format': 'uuid',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_uuid(self):
self.assertEqual('Validation succeeded.',
self.post(
body={'foo': '70a599e0-31e7-49b7-b260-868f441e862b'},
req=FakeRequest()
))
def test_validate_uuid_fails(self):
detail = ("Invalid input for field/attribute foo."
" Value: 70a599e031e749b7b260868f441e862."
" '70a599e031e749b7b260868f441e862' is not a 'uuid'")
self.check_validation_error(self.post,
body={'foo': '70a599e031e749b7b260868f441e862'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: 1."
" '1' is not a 'uuid'")
self.check_validation_error(self.post, body={'foo': '1'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: abc."
" 'abc' is not a 'uuid'")
self.check_validation_error(self.post, body={'foo': 'abc'},
expected_detail=detail)
class UriTestCase(APIValidationTestCase):
def setUp(self):
super(UriTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'string',
'format': 'uri',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_uri(self):
self.assertEqual('Validation succeeded.',
self.post(
body={'foo': 'http://localhost:8774/v2/servers'},
req=FakeRequest()
))
self.assertEqual('Validation succeeded.',
self.post(
body={'foo': 'http://[::1]:8774/v2/servers'},
req=FakeRequest()
))
def test_validate_uri_fails(self):
base_detail = ("Invalid input for field/attribute foo. Value: {0}. "
"'{0}' is not a 'uri'")
invalid_uri = 'http://localhost:8774/v2/servers##'
self.check_validation_error(self.post,
body={'foo': invalid_uri},
expected_detail=base_detail.format(
invalid_uri))
invalid_uri = 'http://[fdf8:01]:8774/v2/servers'
self.check_validation_error(self.post,
body={'foo': invalid_uri},
expected_detail=base_detail.format(
invalid_uri))
invalid_uri = '1'
self.check_validation_error(self.post,
body={'foo': invalid_uri},
expected_detail=base_detail.format(
invalid_uri))
invalid_uri = 'abc'
self.check_validation_error(self.post,
body={'foo': invalid_uri},
expected_detail=base_detail.format(
invalid_uri))
class Ipv4TestCase(APIValidationTestCase):
def setUp(self):
super(Ipv4TestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'string',
'format': 'ipv4',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_ipv4(self):
self.assertEqual('Validation succeeded.',
self.post(
body={'foo': '192.168.0.100'},
req=FakeRequest()
))
def test_validate_ipv4_fails(self):
detail = ("Invalid input for field/attribute foo. Value: abc."
" 'abc' is not a 'ipv4'")
self.check_validation_error(self.post, body={'foo': 'abc'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: localhost."
" 'localhost' is not a 'ipv4'")
self.check_validation_error(self.post, body={'foo': 'localhost'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo."
" Value: 2001:db8::1234:0:0:9abc."
" '2001:db8::1234:0:0:9abc' is not a 'ipv4'")
self.check_validation_error(self.post,
body={'foo': '2001:db8::1234:0:0:9abc'},
expected_detail=detail)
class Ipv6TestCase(APIValidationTestCase):
def setUp(self):
super(Ipv6TestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'string',
'format': 'ipv6',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_ipv6(self):
self.assertEqual('Validation succeeded.',
self.post(
body={'foo': '2001:db8::1234:0:0:9abc'},
req=FakeRequest()
))
def test_validate_ipv6_fails(self):
detail = ("Invalid input for field/attribute foo. Value: abc."
" 'abc' is not a 'ipv6'")
self.check_validation_error(self.post, body={'foo': 'abc'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo. Value: localhost."
" 'localhost' is not a 'ipv6'")
self.check_validation_error(self.post, body={'foo': 'localhost'},
expected_detail=detail)
detail = ("Invalid input for field/attribute foo."
" Value: 192.168.0.100. '192.168.0.100' is not a 'ipv6'")
self.check_validation_error(self.post, body={'foo': '192.168.0.100'},
expected_detail=detail)
class Base64TestCase(APIValidationTestCase):
def setUp(self):
super(APIValidationTestCase, self).setUp()
schema = {
'type': 'object',
'properties': {
'foo': {
'type': 'string',
'format': 'base64',
},
},
}
@validation.schema(request_body_schema=schema)
def post(req, body):
return 'Validation succeeded.'
self.post = post
def test_validate_base64(self):
self.assertEqual('Validation succeeded.',
self.post(body={'foo': 'aGVsbG8gd29ybGQ='},
req=FakeRequest()))
# 'aGVsbG8gd29ybGQ=' is the base64 code of 'hello world'
def test_validate_base64_fails(self):
value = 'A random string'
detail = ("Invalid input for field/attribute foo. "
"Value: %s. '%s' is not a 'base64'") % (value, value)
self.check_validation_error(self.post, body={'foo': value},
expected_detail=detail)
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.